PackageManagerService.java revision 65cde7d42d741c7d9aa2714a397b7333f688ab55
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 com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.AppGlobals;
84import android.app.IActivityManager;
85import android.app.admin.IDevicePolicyManager;
86import android.app.backup.IBackupManager;
87import android.content.BroadcastReceiver;
88import android.content.ComponentName;
89import android.content.Context;
90import android.content.IIntentReceiver;
91import android.content.Intent;
92import android.content.IntentFilter;
93import android.content.IntentSender;
94import android.content.IntentSender.SendIntentException;
95import android.content.ServiceConnection;
96import android.content.pm.ActivityInfo;
97import android.content.pm.ApplicationInfo;
98import android.content.pm.FeatureInfo;
99import android.content.pm.IPackageDataObserver;
100import android.content.pm.IPackageDeleteObserver;
101import android.content.pm.IPackageDeleteObserver2;
102import android.content.pm.IPackageInstallObserver2;
103import android.content.pm.IPackageInstaller;
104import android.content.pm.IPackageManager;
105import android.content.pm.IPackageMoveObserver;
106import android.content.pm.IPackageStatsObserver;
107import android.content.pm.InstrumentationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageParser;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.storage.StorageManager;
142import android.os.Debug;
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.Objects;
206import java.util.Set;
207import java.util.concurrent.atomic.AtomicBoolean;
208import java.util.concurrent.atomic.AtomicLong;
209
210import dalvik.system.DexFile;
211import dalvik.system.StaleDexCacheError;
212import dalvik.system.VMRuntime;
213
214import libcore.io.IoUtils;
215import libcore.util.EmptyArray;
216
217/**
218 * Keep track of all those .apks everywhere.
219 *
220 * This is very central to the platform's security; please run the unit
221 * tests whenever making modifications here:
222 *
223mmm frameworks/base/tests/AndroidTests
224adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
225adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
226 *
227 * {@hide}
228 */
229public class PackageManagerService extends IPackageManager.Stub {
230    static final String TAG = "PackageManager";
231    static final boolean DEBUG_SETTINGS = false;
232    static final boolean DEBUG_PREFERRED = false;
233    static final boolean DEBUG_UPGRADE = false;
234    private static final boolean DEBUG_INSTALL = false;
235    private static final boolean DEBUG_REMOVE = false;
236    private static final boolean DEBUG_BROADCASTS = false;
237    private static final boolean DEBUG_SHOW_INFO = false;
238    private static final boolean DEBUG_PACKAGE_INFO = false;
239    private static final boolean DEBUG_INTENT_MATCHING = false;
240    private static final boolean DEBUG_PACKAGE_SCANNING = false;
241    private static final boolean DEBUG_VERIFY = false;
242    private static final boolean DEBUG_DEXOPT = false;
243    private static final boolean DEBUG_ABI_SELECTION = false;
244
245    private static final int RADIO_UID = Process.PHONE_UID;
246    private static final int LOG_UID = Process.LOG_UID;
247    private static final int NFC_UID = Process.NFC_UID;
248    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
249    private static final int SHELL_UID = Process.SHELL_UID;
250
251    // Cap the size of permission trees that 3rd party apps can define
252    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
253
254    // Suffix used during package installation when copying/moving
255    // package apks to install directory.
256    private static final String INSTALL_PACKAGE_SUFFIX = "-";
257
258    static final int SCAN_NO_DEX = 1<<1;
259    static final int SCAN_FORCE_DEX = 1<<2;
260    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
261    static final int SCAN_NEW_INSTALL = 1<<4;
262    static final int SCAN_NO_PATHS = 1<<5;
263    static final int SCAN_UPDATE_TIME = 1<<6;
264    static final int SCAN_DEFER_DEX = 1<<7;
265    static final int SCAN_BOOTING = 1<<8;
266    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
267    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
268    static final int SCAN_REPLACING = 1<<11;
269
270    static final int REMOVE_CHATTY = 1<<16;
271
272    /**
273     * Timeout (in milliseconds) after which the watchdog should declare that
274     * our handler thread is wedged.  The usual default for such things is one
275     * minute but we sometimes do very lengthy I/O operations on this thread,
276     * such as installing multi-gigabyte applications, so ours needs to be longer.
277     */
278    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
279
280    /**
281     * Whether verification is enabled by default.
282     */
283    private static final boolean DEFAULT_VERIFY_ENABLE = true;
284
285    /**
286     * The default maximum time to wait for the verification agent to return in
287     * milliseconds.
288     */
289    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
290
291    /**
292     * The default response for package verification timeout.
293     *
294     * This can be either PackageManager.VERIFICATION_ALLOW or
295     * PackageManager.VERIFICATION_REJECT.
296     */
297    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
298
299    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
300
301    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
302            DEFAULT_CONTAINER_PACKAGE,
303            "com.android.defcontainer.DefaultContainerService");
304
305    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
306
307    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
308
309    private static String sPreferredInstructionSet;
310
311    final ServiceThread mHandlerThread;
312
313    private static final String IDMAP_PREFIX = "/data/resource-cache/";
314    private static final String IDMAP_SUFFIX = "@idmap";
315
316    final PackageHandler mHandler;
317
318    /**
319     * Messages for {@link #mHandler} that need to wait for system ready before
320     * being dispatched.
321     */
322    private ArrayList<Message> mPostSystemReadyMessages;
323
324    final int mSdkVersion = Build.VERSION.SDK_INT;
325
326    final Context mContext;
327    final boolean mFactoryTest;
328    final boolean mOnlyCore;
329    final boolean mLazyDexOpt;
330    final DisplayMetrics mMetrics;
331    final int mDefParseFlags;
332    final String[] mSeparateProcesses;
333
334    // This is where all application persistent data goes.
335    final File mAppDataDir;
336
337    // This is where all application persistent data goes for secondary users.
338    final File mUserAppDataDir;
339
340    /** The location for ASEC container files on internal storage. */
341    final String mAsecInternalPath;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    /** Directory where installed third-party apps stored */
348    final File mAppInstallDir;
349
350    /**
351     * Directory to which applications installed internally have their
352     * 32 bit native libraries copied.
353     */
354    private File mAppLib32InstallDir;
355
356    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
357    // apps.
358    final File mDrmAppPrivateInstallDir;
359
360    // ----------------------------------------------------------------
361
362    // Lock for state used when installing and doing other long running
363    // operations.  Methods that must be called with this lock held have
364    // the suffix "LI".
365    final Object mInstallLock = new Object();
366
367    // ----------------------------------------------------------------
368
369    // Keys are String (package name), values are Package.  This also serves
370    // as the lock for the global state.  Methods that must be called with
371    // this lock held have the prefix "LP".
372    final HashMap<String, PackageParser.Package> mPackages =
373            new HashMap<String, PackageParser.Package>();
374
375    // Tracks available target package names -> overlay package paths.
376    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
377        new HashMap<String, HashMap<String, PackageParser.Package>>();
378
379    final Settings mSettings;
380    boolean mRestoredSettings;
381
382    // System configuration read by SystemConfig.
383    final int[] mGlobalGids;
384    final SparseArray<HashSet<String>> mSystemPermissions;
385    final HashMap<String, FeatureInfo> mAvailableFeatures;
386
387    // If mac_permissions.xml was found for seinfo labeling.
388    boolean mFoundPolicyFile;
389
390    // If a recursive restorecon of /data/data/<pkg> is needed.
391    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
392
393    public static final class SharedLibraryEntry {
394        public final String path;
395        public final String apk;
396
397        SharedLibraryEntry(String _path, String _apk) {
398            path = _path;
399            apk = _apk;
400        }
401    }
402
403    // Currently known shared libraries.
404    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
405            new HashMap<String, SharedLibraryEntry>();
406
407    // All available activities, for your resolving pleasure.
408    final ActivityIntentResolver mActivities =
409            new ActivityIntentResolver();
410
411    // All available receivers, for your resolving pleasure.
412    final ActivityIntentResolver mReceivers =
413            new ActivityIntentResolver();
414
415    // All available services, for your resolving pleasure.
416    final ServiceIntentResolver mServices = new ServiceIntentResolver();
417
418    // All available providers, for your resolving pleasure.
419    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
420
421    // Mapping from provider base names (first directory in content URI codePath)
422    // to the provider information.
423    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
424            new HashMap<String, PackageParser.Provider>();
425
426    // Mapping from instrumentation class names to info about them.
427    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
428            new HashMap<ComponentName, PackageParser.Instrumentation>();
429
430    // Mapping from permission names to info about them.
431    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
432            new HashMap<String, PackageParser.PermissionGroup>();
433
434    // Packages whose data we have transfered into another package, thus
435    // should no longer exist.
436    final HashSet<String> mTransferedPackages = new HashSet<String>();
437
438    // Broadcast actions that are only available to the system.
439    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
440
441    /** List of packages waiting for verification. */
442    final SparseArray<PackageVerificationState> mPendingVerification
443            = new SparseArray<PackageVerificationState>();
444
445    /** Set of packages associated with each app op permission. */
446    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
447
448    final PackageInstallerService mInstallerService;
449
450    HashSet<PackageParser.Package> mDeferredDexOpt = null;
451
452    // Cache of users who need badging.
453    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
454
455    /** Token for keys in mPendingVerification. */
456    private int mPendingVerificationToken = 0;
457
458    volatile boolean mSystemReady;
459    volatile boolean mSafeMode;
460    volatile boolean mHasSystemUidErrors;
461
462    ApplicationInfo mAndroidApplication;
463    final ActivityInfo mResolveActivity = new ActivityInfo();
464    final ResolveInfo mResolveInfo = new ResolveInfo();
465    ComponentName mResolveComponentName;
466    PackageParser.Package mPlatformPackage;
467    ComponentName mCustomResolverComponentName;
468
469    boolean mResolverReplaced = false;
470
471    // Set of pending broadcasts for aggregating enable/disable of components.
472    static class PendingPackageBroadcasts {
473        // for each user id, a map of <package name -> components within that package>
474        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
475
476        public PendingPackageBroadcasts() {
477            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
478        }
479
480        public ArrayList<String> get(int userId, String packageName) {
481            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
482            return packages.get(packageName);
483        }
484
485        public void put(int userId, String packageName, ArrayList<String> components) {
486            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
487            packages.put(packageName, components);
488        }
489
490        public void remove(int userId, String packageName) {
491            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
492            if (packages != null) {
493                packages.remove(packageName);
494            }
495        }
496
497        public void remove(int userId) {
498            mUidMap.remove(userId);
499        }
500
501        public int userIdCount() {
502            return mUidMap.size();
503        }
504
505        public int userIdAt(int n) {
506            return mUidMap.keyAt(n);
507        }
508
509        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
510            return mUidMap.get(userId);
511        }
512
513        public int size() {
514            // total number of pending broadcast entries across all userIds
515            int num = 0;
516            for (int i = 0; i< mUidMap.size(); i++) {
517                num += mUidMap.valueAt(i).size();
518            }
519            return num;
520        }
521
522        public void clear() {
523            mUidMap.clear();
524        }
525
526        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
527            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
528            if (map == null) {
529                map = new HashMap<String, ArrayList<String>>();
530                mUidMap.put(userId, map);
531            }
532            return map;
533        }
534    }
535    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
536
537    // Service Connection to remote media container service to copy
538    // package uri's from external media onto secure containers
539    // or internal storage.
540    private IMediaContainerService mContainerService = null;
541
542    static final int SEND_PENDING_BROADCAST = 1;
543    static final int MCS_BOUND = 3;
544    static final int END_COPY = 4;
545    static final int INIT_COPY = 5;
546    static final int MCS_UNBIND = 6;
547    static final int START_CLEANING_PACKAGE = 7;
548    static final int FIND_INSTALL_LOC = 8;
549    static final int POST_INSTALL = 9;
550    static final int MCS_RECONNECT = 10;
551    static final int MCS_GIVE_UP = 11;
552    static final int UPDATED_MEDIA_STATUS = 12;
553    static final int WRITE_SETTINGS = 13;
554    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
555    static final int PACKAGE_VERIFIED = 15;
556    static final int CHECK_PENDING_VERIFICATION = 16;
557
558    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
559
560    // Delay time in millisecs
561    static final int BROADCAST_DELAY = 10 * 1000;
562
563    static UserManagerService sUserManager;
564
565    // Stores a list of users whose package restrictions file needs to be updated
566    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
567
568    final private DefaultContainerConnection mDefContainerConn =
569            new DefaultContainerConnection();
570    class DefaultContainerConnection implements ServiceConnection {
571        public void onServiceConnected(ComponentName name, IBinder service) {
572            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
573            IMediaContainerService imcs =
574                IMediaContainerService.Stub.asInterface(service);
575            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
576        }
577
578        public void onServiceDisconnected(ComponentName name) {
579            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
580        }
581    };
582
583    // Recordkeeping of restore-after-install operations that are currently in flight
584    // between the Package Manager and the Backup Manager
585    class PostInstallData {
586        public InstallArgs args;
587        public PackageInstalledInfo res;
588
589        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
590            args = _a;
591            res = _r;
592        }
593    };
594    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
595    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
596
597    private final String mRequiredVerifierPackage;
598
599    private final PackageUsage mPackageUsage = new PackageUsage();
600
601    private class PackageUsage {
602        private static final int WRITE_INTERVAL
603            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
604
605        private final Object mFileLock = new Object();
606        private final AtomicLong mLastWritten = new AtomicLong(0);
607        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
608
609        private boolean mIsHistoricalPackageUsageAvailable = true;
610
611        boolean isHistoricalPackageUsageAvailable() {
612            return mIsHistoricalPackageUsageAvailable;
613        }
614
615        void write(boolean force) {
616            if (force) {
617                writeInternal();
618                return;
619            }
620            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
621                && !DEBUG_DEXOPT) {
622                return;
623            }
624            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
625                new Thread("PackageUsage_DiskWriter") {
626                    @Override
627                    public void run() {
628                        try {
629                            writeInternal();
630                        } finally {
631                            mBackgroundWriteRunning.set(false);
632                        }
633                    }
634                }.start();
635            }
636        }
637
638        private void writeInternal() {
639            synchronized (mPackages) {
640                synchronized (mFileLock) {
641                    AtomicFile file = getFile();
642                    FileOutputStream f = null;
643                    try {
644                        f = file.startWrite();
645                        BufferedOutputStream out = new BufferedOutputStream(f);
646                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
647                        StringBuilder sb = new StringBuilder();
648                        for (PackageParser.Package pkg : mPackages.values()) {
649                            if (pkg.mLastPackageUsageTimeInMills == 0) {
650                                continue;
651                            }
652                            sb.setLength(0);
653                            sb.append(pkg.packageName);
654                            sb.append(' ');
655                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
656                            sb.append('\n');
657                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
658                        }
659                        out.flush();
660                        file.finishWrite(f);
661                    } catch (IOException e) {
662                        if (f != null) {
663                            file.failWrite(f);
664                        }
665                        Log.e(TAG, "Failed to write package usage times", e);
666                    }
667                }
668            }
669            mLastWritten.set(SystemClock.elapsedRealtime());
670        }
671
672        void readLP() {
673            synchronized (mFileLock) {
674                AtomicFile file = getFile();
675                BufferedInputStream in = null;
676                try {
677                    in = new BufferedInputStream(file.openRead());
678                    StringBuffer sb = new StringBuffer();
679                    while (true) {
680                        String packageName = readToken(in, sb, ' ');
681                        if (packageName == null) {
682                            break;
683                        }
684                        String timeInMillisString = readToken(in, sb, '\n');
685                        if (timeInMillisString == null) {
686                            throw new IOException("Failed to find last usage time for package "
687                                                  + packageName);
688                        }
689                        PackageParser.Package pkg = mPackages.get(packageName);
690                        if (pkg == null) {
691                            continue;
692                        }
693                        long timeInMillis;
694                        try {
695                            timeInMillis = Long.parseLong(timeInMillisString.toString());
696                        } catch (NumberFormatException e) {
697                            throw new IOException("Failed to parse " + timeInMillisString
698                                                  + " as a long.", e);
699                        }
700                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
701                    }
702                } catch (FileNotFoundException expected) {
703                    mIsHistoricalPackageUsageAvailable = false;
704                } catch (IOException e) {
705                    Log.w(TAG, "Failed to read package usage times", e);
706                } finally {
707                    IoUtils.closeQuietly(in);
708                }
709            }
710            mLastWritten.set(SystemClock.elapsedRealtime());
711        }
712
713        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
714                throws IOException {
715            sb.setLength(0);
716            while (true) {
717                int ch = in.read();
718                if (ch == -1) {
719                    if (sb.length() == 0) {
720                        return null;
721                    }
722                    throw new IOException("Unexpected EOF");
723                }
724                if (ch == endOfToken) {
725                    return sb.toString();
726                }
727                sb.append((char)ch);
728            }
729        }
730
731        private AtomicFile getFile() {
732            File dataDir = Environment.getDataDirectory();
733            File systemDir = new File(dataDir, "system");
734            File fname = new File(systemDir, "package-usage.list");
735            return new AtomicFile(fname);
736        }
737    }
738
739    class PackageHandler extends Handler {
740        private boolean mBound = false;
741        final ArrayList<HandlerParams> mPendingInstalls =
742            new ArrayList<HandlerParams>();
743
744        private boolean connectToService() {
745            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
746                    " DefaultContainerService");
747            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
748            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
749            if (mContext.bindServiceAsUser(service, mDefContainerConn,
750                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
751                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
752                mBound = true;
753                return true;
754            }
755            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
756            return false;
757        }
758
759        private void disconnectService() {
760            mContainerService = null;
761            mBound = false;
762            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
763            mContext.unbindService(mDefContainerConn);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
765        }
766
767        PackageHandler(Looper looper) {
768            super(looper);
769        }
770
771        public void handleMessage(Message msg) {
772            try {
773                doHandleMessage(msg);
774            } finally {
775                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
776            }
777        }
778
779        void doHandleMessage(Message msg) {
780            switch (msg.what) {
781                case INIT_COPY: {
782                    HandlerParams params = (HandlerParams) msg.obj;
783                    int idx = mPendingInstalls.size();
784                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
785                    // If a bind was already initiated we dont really
786                    // need to do anything. The pending install
787                    // will be processed later on.
788                    if (!mBound) {
789                        // If this is the only one pending we might
790                        // have to bind to the service again.
791                        if (!connectToService()) {
792                            Slog.e(TAG, "Failed to bind to media container service");
793                            params.serviceError();
794                            return;
795                        } else {
796                            // Once we bind to the service, the first
797                            // pending request will be processed.
798                            mPendingInstalls.add(idx, params);
799                        }
800                    } else {
801                        mPendingInstalls.add(idx, params);
802                        // Already bound to the service. Just make
803                        // sure we trigger off processing the first request.
804                        if (idx == 0) {
805                            mHandler.sendEmptyMessage(MCS_BOUND);
806                        }
807                    }
808                    break;
809                }
810                case MCS_BOUND: {
811                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
812                    if (msg.obj != null) {
813                        mContainerService = (IMediaContainerService) msg.obj;
814                    }
815                    if (mContainerService == null) {
816                        // Something seriously wrong. Bail out
817                        Slog.e(TAG, "Cannot bind to media container service");
818                        for (HandlerParams params : mPendingInstalls) {
819                            // Indicate service bind error
820                            params.serviceError();
821                        }
822                        mPendingInstalls.clear();
823                    } else if (mPendingInstalls.size() > 0) {
824                        HandlerParams params = mPendingInstalls.get(0);
825                        if (params != null) {
826                            if (params.startCopy()) {
827                                // We are done...  look for more work or to
828                                // go idle.
829                                if (DEBUG_SD_INSTALL) Log.i(TAG,
830                                        "Checking for more work or unbind...");
831                                // Delete pending install
832                                if (mPendingInstalls.size() > 0) {
833                                    mPendingInstalls.remove(0);
834                                }
835                                if (mPendingInstalls.size() == 0) {
836                                    if (mBound) {
837                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
838                                                "Posting delayed MCS_UNBIND");
839                                        removeMessages(MCS_UNBIND);
840                                        Message ubmsg = obtainMessage(MCS_UNBIND);
841                                        // Unbind after a little delay, to avoid
842                                        // continual thrashing.
843                                        sendMessageDelayed(ubmsg, 10000);
844                                    }
845                                } else {
846                                    // There are more pending requests in queue.
847                                    // Just post MCS_BOUND message to trigger processing
848                                    // of next pending install.
849                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
850                                            "Posting MCS_BOUND for next work");
851                                    mHandler.sendEmptyMessage(MCS_BOUND);
852                                }
853                            }
854                        }
855                    } else {
856                        // Should never happen ideally.
857                        Slog.w(TAG, "Empty queue");
858                    }
859                    break;
860                }
861                case MCS_RECONNECT: {
862                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
863                    if (mPendingInstalls.size() > 0) {
864                        if (mBound) {
865                            disconnectService();
866                        }
867                        if (!connectToService()) {
868                            Slog.e(TAG, "Failed to bind to media container service");
869                            for (HandlerParams params : mPendingInstalls) {
870                                // Indicate service bind error
871                                params.serviceError();
872                            }
873                            mPendingInstalls.clear();
874                        }
875                    }
876                    break;
877                }
878                case MCS_UNBIND: {
879                    // If there is no actual work left, then time to unbind.
880                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
881
882                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
883                        if (mBound) {
884                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
885
886                            disconnectService();
887                        }
888                    } else if (mPendingInstalls.size() > 0) {
889                        // There are more pending requests in queue.
890                        // Just post MCS_BOUND message to trigger processing
891                        // of next pending install.
892                        mHandler.sendEmptyMessage(MCS_BOUND);
893                    }
894
895                    break;
896                }
897                case MCS_GIVE_UP: {
898                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
899                    mPendingInstalls.remove(0);
900                    break;
901                }
902                case SEND_PENDING_BROADCAST: {
903                    String packages[];
904                    ArrayList<String> components[];
905                    int size = 0;
906                    int uids[];
907                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
908                    synchronized (mPackages) {
909                        if (mPendingBroadcasts == null) {
910                            return;
911                        }
912                        size = mPendingBroadcasts.size();
913                        if (size <= 0) {
914                            // Nothing to be done. Just return
915                            return;
916                        }
917                        packages = new String[size];
918                        components = new ArrayList[size];
919                        uids = new int[size];
920                        int i = 0;  // filling out the above arrays
921
922                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
923                            int packageUserId = mPendingBroadcasts.userIdAt(n);
924                            Iterator<Map.Entry<String, ArrayList<String>>> it
925                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
926                                            .entrySet().iterator();
927                            while (it.hasNext() && i < size) {
928                                Map.Entry<String, ArrayList<String>> ent = it.next();
929                                packages[i] = ent.getKey();
930                                components[i] = ent.getValue();
931                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
932                                uids[i] = (ps != null)
933                                        ? UserHandle.getUid(packageUserId, ps.appId)
934                                        : -1;
935                                i++;
936                            }
937                        }
938                        size = i;
939                        mPendingBroadcasts.clear();
940                    }
941                    // Send broadcasts
942                    for (int i = 0; i < size; i++) {
943                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
944                    }
945                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
946                    break;
947                }
948                case START_CLEANING_PACKAGE: {
949                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
950                    final String packageName = (String)msg.obj;
951                    final int userId = msg.arg1;
952                    final boolean andCode = msg.arg2 != 0;
953                    synchronized (mPackages) {
954                        if (userId == UserHandle.USER_ALL) {
955                            int[] users = sUserManager.getUserIds();
956                            for (int user : users) {
957                                mSettings.addPackageToCleanLPw(
958                                        new PackageCleanItem(user, packageName, andCode));
959                            }
960                        } else {
961                            mSettings.addPackageToCleanLPw(
962                                    new PackageCleanItem(userId, packageName, andCode));
963                        }
964                    }
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
966                    startCleaningPackages();
967                } break;
968                case POST_INSTALL: {
969                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
970                    PostInstallData data = mRunningInstalls.get(msg.arg1);
971                    mRunningInstalls.delete(msg.arg1);
972                    boolean deleteOld = false;
973
974                    if (data != null) {
975                        InstallArgs args = data.args;
976                        PackageInstalledInfo res = data.res;
977
978                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
979                            res.removedInfo.sendBroadcast(false, true, false);
980                            Bundle extras = new Bundle(1);
981                            extras.putInt(Intent.EXTRA_UID, res.uid);
982                            // Determine the set of users who are adding this
983                            // package for the first time vs. those who are seeing
984                            // an update.
985                            int[] firstUsers;
986                            int[] updateUsers = new int[0];
987                            if (res.origUsers == null || res.origUsers.length == 0) {
988                                firstUsers = res.newUsers;
989                            } else {
990                                firstUsers = new int[0];
991                                for (int i=0; i<res.newUsers.length; i++) {
992                                    int user = res.newUsers[i];
993                                    boolean isNew = true;
994                                    for (int j=0; j<res.origUsers.length; j++) {
995                                        if (res.origUsers[j] == user) {
996                                            isNew = false;
997                                            break;
998                                        }
999                                    }
1000                                    if (isNew) {
1001                                        int[] newFirst = new int[firstUsers.length+1];
1002                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1003                                                firstUsers.length);
1004                                        newFirst[firstUsers.length] = user;
1005                                        firstUsers = newFirst;
1006                                    } else {
1007                                        int[] newUpdate = new int[updateUsers.length+1];
1008                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1009                                                updateUsers.length);
1010                                        newUpdate[updateUsers.length] = user;
1011                                        updateUsers = newUpdate;
1012                                    }
1013                                }
1014                            }
1015                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1016                                    res.pkg.applicationInfo.packageName,
1017                                    extras, null, null, firstUsers);
1018                            final boolean update = res.removedInfo.removedPackage != null;
1019                            if (update) {
1020                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1021                            }
1022                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1023                                    res.pkg.applicationInfo.packageName,
1024                                    extras, null, null, updateUsers);
1025                            if (update) {
1026                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1027                                        res.pkg.applicationInfo.packageName,
1028                                        extras, null, null, updateUsers);
1029                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1030                                        null, null,
1031                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1032
1033                                // treat asec-hosted packages like removable media on upgrade
1034                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1035                                    if (DEBUG_INSTALL) {
1036                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1037                                                + " is ASEC-hosted -> AVAILABLE");
1038                                    }
1039                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1040                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1041                                    pkgList.add(res.pkg.applicationInfo.packageName);
1042                                    sendResourcesChangedBroadcast(true, true,
1043                                            pkgList,uidArray, null);
1044                                }
1045                            }
1046                            if (res.removedInfo.args != null) {
1047                                // Remove the replaced package's older resources safely now
1048                                deleteOld = true;
1049                            }
1050
1051                            // Log current value of "unknown sources" setting
1052                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1053                                getUnknownSourcesSettings());
1054                        }
1055                        // Force a gc to clear up things
1056                        Runtime.getRuntime().gc();
1057                        // We delete after a gc for applications  on sdcard.
1058                        if (deleteOld) {
1059                            synchronized (mInstallLock) {
1060                                res.removedInfo.args.doPostDeleteLI(true);
1061                            }
1062                        }
1063                        if (args.observer != null) {
1064                            try {
1065                                Bundle extras = extrasForInstallResult(res);
1066                                args.observer.onPackageInstalled(res.name, res.returnCode,
1067                                        res.returnMsg, extras);
1068                            } catch (RemoteException e) {
1069                                Slog.i(TAG, "Observer no longer exists.");
1070                            }
1071                        }
1072                    } else {
1073                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1074                    }
1075                } break;
1076                case UPDATED_MEDIA_STATUS: {
1077                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1078                    boolean reportStatus = msg.arg1 == 1;
1079                    boolean doGc = msg.arg2 == 1;
1080                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1081                    if (doGc) {
1082                        // Force a gc to clear up stale containers.
1083                        Runtime.getRuntime().gc();
1084                    }
1085                    if (msg.obj != null) {
1086                        @SuppressWarnings("unchecked")
1087                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1088                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1089                        // Unload containers
1090                        unloadAllContainers(args);
1091                    }
1092                    if (reportStatus) {
1093                        try {
1094                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1095                            PackageHelper.getMountService().finishMediaUpdate();
1096                        } catch (RemoteException e) {
1097                            Log.e(TAG, "MountService not running?");
1098                        }
1099                    }
1100                } break;
1101                case WRITE_SETTINGS: {
1102                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1103                    synchronized (mPackages) {
1104                        removeMessages(WRITE_SETTINGS);
1105                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1106                        mSettings.writeLPr();
1107                        mDirtyUsers.clear();
1108                    }
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1110                } break;
1111                case WRITE_PACKAGE_RESTRICTIONS: {
1112                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113                    synchronized (mPackages) {
1114                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1115                        for (int userId : mDirtyUsers) {
1116                            mSettings.writePackageRestrictionsLPr(userId);
1117                        }
1118                        mDirtyUsers.clear();
1119                    }
1120                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1121                } break;
1122                case CHECK_PENDING_VERIFICATION: {
1123                    final int verificationId = msg.arg1;
1124                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1125
1126                    if ((state != null) && !state.timeoutExtended()) {
1127                        final InstallArgs args = state.getInstallArgs();
1128                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1129
1130                        Slog.i(TAG, "Verification timed out for " + originUri);
1131                        mPendingVerification.remove(verificationId);
1132
1133                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1134
1135                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1136                            Slog.i(TAG, "Continuing with installation of " + originUri);
1137                            state.setVerifierResponse(Binder.getCallingUid(),
1138                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1139                            broadcastPackageVerified(verificationId, originUri,
1140                                    PackageManager.VERIFICATION_ALLOW,
1141                                    state.getInstallArgs().getUser());
1142                            try {
1143                                ret = args.copyApk(mContainerService, true);
1144                            } catch (RemoteException e) {
1145                                Slog.e(TAG, "Could not contact the ContainerService");
1146                            }
1147                        } else {
1148                            broadcastPackageVerified(verificationId, originUri,
1149                                    PackageManager.VERIFICATION_REJECT,
1150                                    state.getInstallArgs().getUser());
1151                        }
1152
1153                        processPendingInstall(args, ret);
1154                        mHandler.sendEmptyMessage(MCS_UNBIND);
1155                    }
1156                    break;
1157                }
1158                case PACKAGE_VERIFIED: {
1159                    final int verificationId = msg.arg1;
1160
1161                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1162                    if (state == null) {
1163                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1164                        break;
1165                    }
1166
1167                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1168
1169                    state.setVerifierResponse(response.callerUid, response.code);
1170
1171                    if (state.isVerificationComplete()) {
1172                        mPendingVerification.remove(verificationId);
1173
1174                        final InstallArgs args = state.getInstallArgs();
1175                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1176
1177                        int ret;
1178                        if (state.isInstallAllowed()) {
1179                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1180                            broadcastPackageVerified(verificationId, originUri,
1181                                    response.code, state.getInstallArgs().getUser());
1182                            try {
1183                                ret = args.copyApk(mContainerService, true);
1184                            } catch (RemoteException e) {
1185                                Slog.e(TAG, "Could not contact the ContainerService");
1186                            }
1187                        } else {
1188                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1189                        }
1190
1191                        processPendingInstall(args, ret);
1192
1193                        mHandler.sendEmptyMessage(MCS_UNBIND);
1194                    }
1195
1196                    break;
1197                }
1198            }
1199        }
1200    }
1201
1202    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1203        Bundle extras = null;
1204        switch (res.returnCode) {
1205            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1206                extras = new Bundle();
1207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1208                        res.origPermission);
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1210                        res.origPackage);
1211                break;
1212            }
1213        }
1214        return extras;
1215    }
1216
1217    void scheduleWriteSettingsLocked() {
1218        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1219            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1220        }
1221    }
1222
1223    void scheduleWritePackageRestrictionsLocked(int userId) {
1224        if (!sUserManager.exists(userId)) return;
1225        mDirtyUsers.add(userId);
1226        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1227            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1228        }
1229    }
1230
1231    public static final PackageManagerService main(Context context, Installer installer,
1232            boolean factoryTest, boolean onlyCore) {
1233        PackageManagerService m = new PackageManagerService(context, installer,
1234                factoryTest, onlyCore);
1235        ServiceManager.addService("package", m);
1236        return m;
1237    }
1238
1239    static String[] splitString(String str, char sep) {
1240        int count = 1;
1241        int i = 0;
1242        while ((i=str.indexOf(sep, i)) >= 0) {
1243            count++;
1244            i++;
1245        }
1246
1247        String[] res = new String[count];
1248        i=0;
1249        count = 0;
1250        int lastI=0;
1251        while ((i=str.indexOf(sep, i)) >= 0) {
1252            res[count] = str.substring(lastI, i);
1253            count++;
1254            i++;
1255            lastI = i;
1256        }
1257        res[count] = str.substring(lastI, str.length());
1258        return res;
1259    }
1260
1261    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1262        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1263                Context.DISPLAY_SERVICE);
1264        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1265    }
1266
1267    public PackageManagerService(Context context, Installer installer,
1268            boolean factoryTest, boolean onlyCore) {
1269        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1270                SystemClock.uptimeMillis());
1271
1272        if (mSdkVersion <= 0) {
1273            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1274        }
1275
1276        mContext = context;
1277        mFactoryTest = factoryTest;
1278        mOnlyCore = onlyCore;
1279        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1280        mMetrics = new DisplayMetrics();
1281        mSettings = new Settings(context);
1282        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1283                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1284        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1293                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1294
1295        String separateProcesses = SystemProperties.get("debug.separate_processes");
1296        if (separateProcesses != null && separateProcesses.length() > 0) {
1297            if ("*".equals(separateProcesses)) {
1298                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1299                mSeparateProcesses = null;
1300                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1301            } else {
1302                mDefParseFlags = 0;
1303                mSeparateProcesses = separateProcesses.split(",");
1304                Slog.w(TAG, "Running with debug.separate_processes: "
1305                        + separateProcesses);
1306            }
1307        } else {
1308            mDefParseFlags = 0;
1309            mSeparateProcesses = null;
1310        }
1311
1312        mInstaller = installer;
1313
1314        getDefaultDisplayMetrics(context, mMetrics);
1315
1316        SystemConfig systemConfig = SystemConfig.getInstance();
1317        mGlobalGids = systemConfig.getGlobalGids();
1318        mSystemPermissions = systemConfig.getSystemPermissions();
1319        mAvailableFeatures = systemConfig.getAvailableFeatures();
1320
1321        synchronized (mInstallLock) {
1322        // writer
1323        synchronized (mPackages) {
1324            mHandlerThread = new ServiceThread(TAG,
1325                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1326            mHandlerThread.start();
1327            mHandler = new PackageHandler(mHandlerThread.getLooper());
1328            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1329
1330            File dataDir = Environment.getDataDirectory();
1331            mAppDataDir = new File(dataDir, "data");
1332            mAppInstallDir = new File(dataDir, "app");
1333            mAppLib32InstallDir = new File(dataDir, "app-lib");
1334            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1335            mUserAppDataDir = new File(dataDir, "user");
1336            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1337
1338            sUserManager = new UserManagerService(context, this,
1339                    mInstallLock, mPackages);
1340
1341            // Propagate permission configuration in to package manager.
1342            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1343                    = systemConfig.getPermissions();
1344            for (int i=0; i<permConfig.size(); i++) {
1345                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1346                BasePermission bp = mSettings.mPermissions.get(perm.name);
1347                if (bp == null) {
1348                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1349                    mSettings.mPermissions.put(perm.name, bp);
1350                }
1351                if (perm.gids != null) {
1352                    bp.gids = appendInts(bp.gids, perm.gids);
1353                }
1354            }
1355
1356            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1357            for (int i=0; i<libConfig.size(); i++) {
1358                mSharedLibraries.put(libConfig.keyAt(i),
1359                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1360            }
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1393            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1394
1395            if (bootClassPath != null) {
1396                String[] bootClassPathElements = splitString(bootClassPath, ':');
1397                for (String element : bootClassPathElements) {
1398                    alreadyDexOpted.add(element);
1399                }
1400            } else {
1401                Slog.w(TAG, "No BOOTCLASSPATH found!");
1402            }
1403
1404            if (systemServerClassPath != null) {
1405                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1406                for (String element : systemServerClassPathElements) {
1407                    alreadyDexOpted.add(element);
1408                }
1409            } else {
1410                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1411            }
1412
1413            boolean didDexOptLibraryOrTool = false;
1414
1415            final List<String> allInstructionSets = getAllInstructionSets();
1416            final String[] dexCodeInstructionSets =
1417                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1418
1419            /**
1420             * Ensure all external libraries have had dexopt run on them.
1421             */
1422            if (mSharedLibraries.size() > 0) {
1423                // NOTE: For now, we're compiling these system "shared libraries"
1424                // (and framework jars) into all available architectures. It's possible
1425                // to compile them only when we come across an app that uses them (there's
1426                // already logic for that in scanPackageLI) but that adds some complexity.
1427                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1428                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1429                        final String lib = libEntry.path;
1430                        if (lib == null) {
1431                            continue;
1432                        }
1433
1434                        try {
1435                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1436                                                                                 dexCodeInstructionSet,
1437                                                                                 false);
1438                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1439                                alreadyDexOpted.add(lib);
1440
1441                                // The list of "shared libraries" we have at this point is
1442                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1443                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1444                                } else {
1445                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1446                                }
1447                                didDexOptLibraryOrTool = true;
1448                            }
1449                        } catch (FileNotFoundException e) {
1450                            Slog.w(TAG, "Library not found: " + lib);
1451                        } catch (IOException e) {
1452                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1453                                    + e.getMessage());
1454                        }
1455                    }
1456                }
1457            }
1458
1459            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1460
1461            // Gross hack for now: we know this file doesn't contain any
1462            // code, so don't dexopt it to avoid the resulting log spew.
1463            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1464
1465            // Gross hack for now: we know this file is only part of
1466            // the boot class path for art, so don't dexopt it to
1467            // avoid the resulting log spew.
1468            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1469
1470            /**
1471             * And there are a number of commands implemented in Java, which
1472             * we currently need to do the dexopt on so that they can be
1473             * run from a non-root shell.
1474             */
1475            String[] frameworkFiles = frameworkDir.list();
1476            if (frameworkFiles != null) {
1477                // TODO: We could compile these only for the most preferred ABI. We should
1478                // first double check that the dex files for these commands are not referenced
1479                // by other system apps.
1480                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1481                    for (int i=0; i<frameworkFiles.length; i++) {
1482                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1483                        String path = libPath.getPath();
1484                        // Skip the file if we already did it.
1485                        if (alreadyDexOpted.contains(path)) {
1486                            continue;
1487                        }
1488                        // Skip the file if it is not a type we want to dexopt.
1489                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1490                            continue;
1491                        }
1492                        try {
1493                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1494                                                                                 dexCodeInstructionSet,
1495                                                                                 false);
1496                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1497                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1498                                didDexOptLibraryOrTool = true;
1499                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1500                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1501                                didDexOptLibraryOrTool = true;
1502                            }
1503                        } catch (FileNotFoundException e) {
1504                            Slog.w(TAG, "Jar not found: " + path);
1505                        } catch (IOException e) {
1506                            Slog.w(TAG, "Exception reading jar: " + path, e);
1507                        }
1508                    }
1509                }
1510            }
1511
1512            // Collect vendor overlay packages.
1513            // (Do this before scanning any apps.)
1514            // For security and version matching reason, only consider
1515            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1516            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1517            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1518                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1519
1520            // Find base frameworks (resource packages without code).
1521            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1522                    | PackageParser.PARSE_IS_SYSTEM_DIR
1523                    | PackageParser.PARSE_IS_PRIVILEGED,
1524                    scanFlags | SCAN_NO_DEX, 0);
1525
1526            // Collected privileged system packages.
1527            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1528            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1529                    | PackageParser.PARSE_IS_SYSTEM_DIR
1530                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1531
1532            // Collect ordinary system packages.
1533            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1534            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1535                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1536
1537            // Collect all vendor packages.
1538            File vendorAppDir = new File("/vendor/app");
1539            try {
1540                vendorAppDir = vendorAppDir.getCanonicalFile();
1541            } catch (IOException e) {
1542                // failed to look up canonical path, continue with original one
1543            }
1544            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1546
1547            // Collect all OEM packages.
1548            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1549            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1550                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1551
1552            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1553            mInstaller.moveFiles();
1554
1555            // Prune any system packages that no longer exist.
1556            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1557            if (!mOnlyCore) {
1558                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1559                while (psit.hasNext()) {
1560                    PackageSetting ps = psit.next();
1561
1562                    /*
1563                     * If this is not a system app, it can't be a
1564                     * disable system app.
1565                     */
1566                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1567                        continue;
1568                    }
1569
1570                    /*
1571                     * If the package is scanned, it's not erased.
1572                     */
1573                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1574                    if (scannedPkg != null) {
1575                        /*
1576                         * If the system app is both scanned and in the
1577                         * disabled packages list, then it must have been
1578                         * added via OTA. Remove it from the currently
1579                         * scanned package so the previously user-installed
1580                         * application can be scanned.
1581                         */
1582                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1583                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1584                                    + "; removing system app");
1585                            removePackageLI(ps, true);
1586                        }
1587
1588                        continue;
1589                    }
1590
1591                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1592                        psit.remove();
1593                        String msg = "System package " + ps.name
1594                                + " no longer exists; wiping its data";
1595                        reportSettingsProblem(Log.WARN, msg);
1596                        removeDataDirsLI(ps.name);
1597                    } else {
1598                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1599                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1600                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1601                        }
1602                    }
1603                }
1604            }
1605
1606            //look for any incomplete package installations
1607            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1608            //clean up list
1609            for(int i = 0; i < deletePkgsList.size(); i++) {
1610                //clean up here
1611                cleanupInstallFailedPackage(deletePkgsList.get(i));
1612            }
1613            //delete tmp files
1614            deleteTempPackageFiles();
1615
1616            // Remove any shared userIDs that have no associated packages
1617            mSettings.pruneSharedUsersLPw();
1618
1619            if (!mOnlyCore) {
1620                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1621                        SystemClock.uptimeMillis());
1622                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1623
1624                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1625                        scanFlags, 0);
1626
1627                /**
1628                 * Remove disable package settings for any updated system
1629                 * apps that were removed via an OTA. If they're not a
1630                 * previously-updated app, remove them completely.
1631                 * Otherwise, just revoke their system-level permissions.
1632                 */
1633                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1634                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1635                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1636
1637                    String msg;
1638                    if (deletedPkg == null) {
1639                        msg = "Updated system package " + deletedAppName
1640                                + " no longer exists; wiping its data";
1641                        removeDataDirsLI(deletedAppName);
1642                    } else {
1643                        msg = "Updated system app + " + deletedAppName
1644                                + " no longer present; removing system privileges for "
1645                                + deletedAppName;
1646
1647                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1648
1649                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1650                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1651                    }
1652                    reportSettingsProblem(Log.WARN, msg);
1653                }
1654            }
1655
1656            // Now that we know all of the shared libraries, update all clients to have
1657            // the correct library paths.
1658            updateAllSharedLibrariesLPw();
1659
1660            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1661                // NOTE: We ignore potential failures here during a system scan (like
1662                // the rest of the commands above) because there's precious little we
1663                // can do about it. A settings error is reported, though.
1664                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1665                        false /* force dexopt */, false /* defer dexopt */);
1666            }
1667
1668            // Now that we know all the packages we are keeping,
1669            // read and update their last usage times.
1670            mPackageUsage.readLP();
1671
1672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1673                    SystemClock.uptimeMillis());
1674            Slog.i(TAG, "Time to scan packages: "
1675                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1676                    + " seconds");
1677
1678            // If the platform SDK has changed since the last time we booted,
1679            // we need to re-grant app permission to catch any new ones that
1680            // appear.  This is really a hack, and means that apps can in some
1681            // cases get permissions that the user didn't initially explicitly
1682            // allow...  it would be nice to have some better way to handle
1683            // this situation.
1684            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1685                    != mSdkVersion;
1686            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1687                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1688                    + "; regranting permissions for internal storage");
1689            mSettings.mInternalSdkPlatform = mSdkVersion;
1690
1691            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1692                    | (regrantPermissions
1693                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1694                            : 0));
1695
1696            // If this is the first boot, and it is a normal boot, then
1697            // we need to initialize the default preferred apps.
1698            if (!mRestoredSettings && !onlyCore) {
1699                mSettings.readDefaultPreferredAppsLPw(this, 0);
1700            }
1701
1702            // If this is first boot after an OTA, and a normal boot, then
1703            // we need to clear code cache directories.
1704            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1705                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1706                for (String pkgName : mSettings.mPackages.keySet()) {
1707                    deleteCodeCacheDirsLI(pkgName);
1708                }
1709                mSettings.mFingerprint = Build.FINGERPRINT;
1710            }
1711
1712            // All the changes are done during package scanning.
1713            mSettings.updateInternalDatabaseVersion();
1714
1715            // can downgrade to reader
1716            mSettings.writeLPr();
1717
1718            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1719                    SystemClock.uptimeMillis());
1720
1721
1722            mRequiredVerifierPackage = getRequiredVerifierLPr();
1723        } // synchronized (mPackages)
1724        } // synchronized (mInstallLock)
1725
1726        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1727
1728        // Now after opening every single application zip, make sure they
1729        // are all flushed.  Not really needed, but keeps things nice and
1730        // tidy.
1731        Runtime.getRuntime().gc();
1732    }
1733
1734    @Override
1735    public boolean isFirstBoot() {
1736        return !mRestoredSettings;
1737    }
1738
1739    @Override
1740    public boolean isOnlyCoreApps() {
1741        return mOnlyCore;
1742    }
1743
1744    private String getRequiredVerifierLPr() {
1745        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1746        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1747                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1748
1749        String requiredVerifier = null;
1750
1751        final int N = receivers.size();
1752        for (int i = 0; i < N; i++) {
1753            final ResolveInfo info = receivers.get(i);
1754
1755            if (info.activityInfo == null) {
1756                continue;
1757            }
1758
1759            final String packageName = info.activityInfo.packageName;
1760
1761            final PackageSetting ps = mSettings.mPackages.get(packageName);
1762            if (ps == null) {
1763                continue;
1764            }
1765
1766            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1767            if (!gp.grantedPermissions
1768                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1769                continue;
1770            }
1771
1772            if (requiredVerifier != null) {
1773                throw new RuntimeException("There can be only one required verifier");
1774            }
1775
1776            requiredVerifier = packageName;
1777        }
1778
1779        return requiredVerifier;
1780    }
1781
1782    @Override
1783    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1784            throws RemoteException {
1785        try {
1786            return super.onTransact(code, data, reply, flags);
1787        } catch (RuntimeException e) {
1788            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1789                Slog.wtf(TAG, "Package Manager Crash", e);
1790            }
1791            throw e;
1792        }
1793    }
1794
1795    void cleanupInstallFailedPackage(PackageSetting ps) {
1796        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1797        removeDataDirsLI(ps.name);
1798        if (ps.codePath != null) {
1799            if (ps.codePath.isDirectory()) {
1800                FileUtils.deleteContents(ps.codePath);
1801            }
1802            ps.codePath.delete();
1803        }
1804        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1805            if (ps.resourcePath.isDirectory()) {
1806                FileUtils.deleteContents(ps.resourcePath);
1807            }
1808            ps.resourcePath.delete();
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, 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, 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, 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, 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, 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 PackageParser.generateActivityInfo(mResolveActivity, flags,
2167                        new PackageUserState(), userId);
2168            }
2169        }
2170        return null;
2171    }
2172
2173    @Override
2174    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2175            String resolvedType) {
2176        synchronized (mPackages) {
2177            PackageParser.Activity a = mActivities.mActivities.get(component);
2178            if (a == null) {
2179                return false;
2180            }
2181            for (int i=0; i<a.intents.size(); i++) {
2182                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2183                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2184                    return true;
2185                }
2186            }
2187            return false;
2188        }
2189    }
2190
2191    @Override
2192    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2193        if (!sUserManager.exists(userId)) return null;
2194        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2195        synchronized (mPackages) {
2196            PackageParser.Activity a = mReceivers.mActivities.get(component);
2197            if (DEBUG_PACKAGE_INFO) Log.v(
2198                TAG, "getReceiverInfo " + component + ": " + a);
2199            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2200                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2201                if (ps == null) return null;
2202                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2203                        userId);
2204            }
2205        }
2206        return null;
2207    }
2208
2209    @Override
2210    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2211        if (!sUserManager.exists(userId)) return null;
2212        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2213        synchronized (mPackages) {
2214            PackageParser.Service s = mServices.mServices.get(component);
2215            if (DEBUG_PACKAGE_INFO) Log.v(
2216                TAG, "getServiceInfo " + component + ": " + s);
2217            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2218                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2219                if (ps == null) return null;
2220                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2221                        userId);
2222            }
2223        }
2224        return null;
2225    }
2226
2227    @Override
2228    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2229        if (!sUserManager.exists(userId)) return null;
2230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2231        synchronized (mPackages) {
2232            PackageParser.Provider p = mProviders.mProviders.get(component);
2233            if (DEBUG_PACKAGE_INFO) Log.v(
2234                TAG, "getProviderInfo " + component + ": " + p);
2235            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2236                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2237                if (ps == null) return null;
2238                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2239                        userId);
2240            }
2241        }
2242        return null;
2243    }
2244
2245    @Override
2246    public String[] getSystemSharedLibraryNames() {
2247        Set<String> libSet;
2248        synchronized (mPackages) {
2249            libSet = mSharedLibraries.keySet();
2250            int size = libSet.size();
2251            if (size > 0) {
2252                String[] libs = new String[size];
2253                libSet.toArray(libs);
2254                return libs;
2255            }
2256        }
2257        return null;
2258    }
2259
2260    @Override
2261    public FeatureInfo[] getSystemAvailableFeatures() {
2262        Collection<FeatureInfo> featSet;
2263        synchronized (mPackages) {
2264            featSet = mAvailableFeatures.values();
2265            int size = featSet.size();
2266            if (size > 0) {
2267                FeatureInfo[] features = new FeatureInfo[size+1];
2268                featSet.toArray(features);
2269                FeatureInfo fi = new FeatureInfo();
2270                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2271                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2272                features[size] = fi;
2273                return features;
2274            }
2275        }
2276        return null;
2277    }
2278
2279    @Override
2280    public boolean hasSystemFeature(String name) {
2281        synchronized (mPackages) {
2282            return mAvailableFeatures.containsKey(name);
2283        }
2284    }
2285
2286    private void checkValidCaller(int uid, int userId) {
2287        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2288            return;
2289
2290        throw new SecurityException("Caller uid=" + uid
2291                + " is not privileged to communicate with user=" + userId);
2292    }
2293
2294    @Override
2295    public int checkPermission(String permName, String pkgName) {
2296        synchronized (mPackages) {
2297            PackageParser.Package p = mPackages.get(pkgName);
2298            if (p != null && p.mExtras != null) {
2299                PackageSetting ps = (PackageSetting)p.mExtras;
2300                if (ps.sharedUser != null) {
2301                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2302                        return PackageManager.PERMISSION_GRANTED;
2303                    }
2304                } else if (ps.grantedPermissions.contains(permName)) {
2305                    return PackageManager.PERMISSION_GRANTED;
2306                }
2307            }
2308        }
2309        return PackageManager.PERMISSION_DENIED;
2310    }
2311
2312    @Override
2313    public int checkUidPermission(String permName, int uid) {
2314        synchronized (mPackages) {
2315            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2316            if (obj != null) {
2317                GrantedPermissions gp = (GrantedPermissions)obj;
2318                if (gp.grantedPermissions.contains(permName)) {
2319                    return PackageManager.PERMISSION_GRANTED;
2320                }
2321            } else {
2322                HashSet<String> perms = mSystemPermissions.get(uid);
2323                if (perms != null && perms.contains(permName)) {
2324                    return PackageManager.PERMISSION_GRANTED;
2325                }
2326            }
2327        }
2328        return PackageManager.PERMISSION_DENIED;
2329    }
2330
2331    /**
2332     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2333     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2334     * @param checkShell TODO(yamasani):
2335     * @param message the message to log on security exception
2336     */
2337    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2338            boolean checkShell, String message) {
2339        if (userId < 0) {
2340            throw new IllegalArgumentException("Invalid userId " + userId);
2341        }
2342        if (checkShell) {
2343            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2344        }
2345        if (userId == UserHandle.getUserId(callingUid)) return;
2346        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2347            if (requireFullPermission) {
2348                mContext.enforceCallingOrSelfPermission(
2349                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2350            } else {
2351                try {
2352                    mContext.enforceCallingOrSelfPermission(
2353                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2354                } catch (SecurityException se) {
2355                    mContext.enforceCallingOrSelfPermission(
2356                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2357                }
2358            }
2359        }
2360    }
2361
2362    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2363        if (callingUid == Process.SHELL_UID) {
2364            if (userHandle >= 0
2365                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2366                throw new SecurityException("Shell does not have permission to access user "
2367                        + userHandle);
2368            } else if (userHandle < 0) {
2369                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2370                        + Debug.getCallers(3));
2371            }
2372        }
2373    }
2374
2375    private BasePermission findPermissionTreeLP(String permName) {
2376        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2377            if (permName.startsWith(bp.name) &&
2378                    permName.length() > bp.name.length() &&
2379                    permName.charAt(bp.name.length()) == '.') {
2380                return bp;
2381            }
2382        }
2383        return null;
2384    }
2385
2386    private BasePermission checkPermissionTreeLP(String permName) {
2387        if (permName != null) {
2388            BasePermission bp = findPermissionTreeLP(permName);
2389            if (bp != null) {
2390                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2391                    return bp;
2392                }
2393                throw new SecurityException("Calling uid "
2394                        + Binder.getCallingUid()
2395                        + " is not allowed to add to permission tree "
2396                        + bp.name + " owned by uid " + bp.uid);
2397            }
2398        }
2399        throw new SecurityException("No permission tree found for " + permName);
2400    }
2401
2402    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2403        if (s1 == null) {
2404            return s2 == null;
2405        }
2406        if (s2 == null) {
2407            return false;
2408        }
2409        if (s1.getClass() != s2.getClass()) {
2410            return false;
2411        }
2412        return s1.equals(s2);
2413    }
2414
2415    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2416        if (pi1.icon != pi2.icon) return false;
2417        if (pi1.logo != pi2.logo) return false;
2418        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2419        if (!compareStrings(pi1.name, pi2.name)) return false;
2420        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2421        // We'll take care of setting this one.
2422        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2423        // These are not currently stored in settings.
2424        //if (!compareStrings(pi1.group, pi2.group)) return false;
2425        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2426        //if (pi1.labelRes != pi2.labelRes) return false;
2427        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2428        return true;
2429    }
2430
2431    int permissionInfoFootprint(PermissionInfo info) {
2432        int size = info.name.length();
2433        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2434        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2435        return size;
2436    }
2437
2438    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2439        int size = 0;
2440        for (BasePermission perm : mSettings.mPermissions.values()) {
2441            if (perm.uid == tree.uid) {
2442                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2443            }
2444        }
2445        return size;
2446    }
2447
2448    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2449        // We calculate the max size of permissions defined by this uid and throw
2450        // if that plus the size of 'info' would exceed our stated maximum.
2451        if (tree.uid != Process.SYSTEM_UID) {
2452            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2453            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2454                throw new SecurityException("Permission tree size cap exceeded");
2455            }
2456        }
2457    }
2458
2459    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2460        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2461            throw new SecurityException("Label must be specified in permission");
2462        }
2463        BasePermission tree = checkPermissionTreeLP(info.name);
2464        BasePermission bp = mSettings.mPermissions.get(info.name);
2465        boolean added = bp == null;
2466        boolean changed = true;
2467        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2468        if (added) {
2469            enforcePermissionCapLocked(info, tree);
2470            bp = new BasePermission(info.name, tree.sourcePackage,
2471                    BasePermission.TYPE_DYNAMIC);
2472        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2473            throw new SecurityException(
2474                    "Not allowed to modify non-dynamic permission "
2475                    + info.name);
2476        } else {
2477            if (bp.protectionLevel == fixedLevel
2478                    && bp.perm.owner.equals(tree.perm.owner)
2479                    && bp.uid == tree.uid
2480                    && comparePermissionInfos(bp.perm.info, info)) {
2481                changed = false;
2482            }
2483        }
2484        bp.protectionLevel = fixedLevel;
2485        info = new PermissionInfo(info);
2486        info.protectionLevel = fixedLevel;
2487        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2488        bp.perm.info.packageName = tree.perm.info.packageName;
2489        bp.uid = tree.uid;
2490        if (added) {
2491            mSettings.mPermissions.put(info.name, bp);
2492        }
2493        if (changed) {
2494            if (!async) {
2495                mSettings.writeLPr();
2496            } else {
2497                scheduleWriteSettingsLocked();
2498            }
2499        }
2500        return added;
2501    }
2502
2503    @Override
2504    public boolean addPermission(PermissionInfo info) {
2505        synchronized (mPackages) {
2506            return addPermissionLocked(info, false);
2507        }
2508    }
2509
2510    @Override
2511    public boolean addPermissionAsync(PermissionInfo info) {
2512        synchronized (mPackages) {
2513            return addPermissionLocked(info, true);
2514        }
2515    }
2516
2517    @Override
2518    public void removePermission(String name) {
2519        synchronized (mPackages) {
2520            checkPermissionTreeLP(name);
2521            BasePermission bp = mSettings.mPermissions.get(name);
2522            if (bp != null) {
2523                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2524                    throw new SecurityException(
2525                            "Not allowed to modify non-dynamic permission "
2526                            + name);
2527                }
2528                mSettings.mPermissions.remove(name);
2529                mSettings.writeLPr();
2530            }
2531        }
2532    }
2533
2534    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2535        int index = pkg.requestedPermissions.indexOf(bp.name);
2536        if (index == -1) {
2537            throw new SecurityException("Package " + pkg.packageName
2538                    + " has not requested permission " + bp.name);
2539        }
2540        boolean isNormal =
2541                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2542                        == PermissionInfo.PROTECTION_NORMAL);
2543        boolean isDangerous =
2544                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2545                        == PermissionInfo.PROTECTION_DANGEROUS);
2546        boolean isDevelopment =
2547                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2548
2549        if (!isNormal && !isDangerous && !isDevelopment) {
2550            throw new SecurityException("Permission " + bp.name
2551                    + " is not a changeable permission type");
2552        }
2553
2554        if (isNormal || isDangerous) {
2555            if (pkg.requestedPermissionsRequired.get(index)) {
2556                throw new SecurityException("Can't change " + bp.name
2557                        + ". It is required by the application");
2558            }
2559        }
2560    }
2561
2562    @Override
2563    public void grantPermission(String packageName, String permissionName) {
2564        mContext.enforceCallingOrSelfPermission(
2565                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2566        synchronized (mPackages) {
2567            final PackageParser.Package pkg = mPackages.get(packageName);
2568            if (pkg == null) {
2569                throw new IllegalArgumentException("Unknown package: " + packageName);
2570            }
2571            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2572            if (bp == null) {
2573                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2574            }
2575
2576            checkGrantRevokePermissions(pkg, bp);
2577
2578            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2579            if (ps == null) {
2580                return;
2581            }
2582            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2583            if (gp.grantedPermissions.add(permissionName)) {
2584                if (ps.haveGids) {
2585                    gp.gids = appendInts(gp.gids, bp.gids);
2586                }
2587                mSettings.writeLPr();
2588            }
2589        }
2590    }
2591
2592    @Override
2593    public void revokePermission(String packageName, String permissionName) {
2594        int changedAppId = -1;
2595
2596        synchronized (mPackages) {
2597            final PackageParser.Package pkg = mPackages.get(packageName);
2598            if (pkg == null) {
2599                throw new IllegalArgumentException("Unknown package: " + packageName);
2600            }
2601            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2602                mContext.enforceCallingOrSelfPermission(
2603                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2604            }
2605            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2606            if (bp == null) {
2607                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2608            }
2609
2610            checkGrantRevokePermissions(pkg, bp);
2611
2612            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2613            if (ps == null) {
2614                return;
2615            }
2616            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2617            if (gp.grantedPermissions.remove(permissionName)) {
2618                gp.grantedPermissions.remove(permissionName);
2619                if (ps.haveGids) {
2620                    gp.gids = removeInts(gp.gids, bp.gids);
2621                }
2622                mSettings.writeLPr();
2623                changedAppId = ps.appId;
2624            }
2625        }
2626
2627        if (changedAppId >= 0) {
2628            // We changed the perm on someone, kill its processes.
2629            IActivityManager am = ActivityManagerNative.getDefault();
2630            if (am != null) {
2631                final int callingUserId = UserHandle.getCallingUserId();
2632                final long ident = Binder.clearCallingIdentity();
2633                try {
2634                    //XXX we should only revoke for the calling user's app permissions,
2635                    // but for now we impact all users.
2636                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2637                    //        "revoke " + permissionName);
2638                    int[] users = sUserManager.getUserIds();
2639                    for (int user : users) {
2640                        am.killUid(UserHandle.getUid(user, changedAppId),
2641                                "revoke " + permissionName);
2642                    }
2643                } catch (RemoteException e) {
2644                } finally {
2645                    Binder.restoreCallingIdentity(ident);
2646                }
2647            }
2648        }
2649    }
2650
2651    @Override
2652    public boolean isProtectedBroadcast(String actionName) {
2653        synchronized (mPackages) {
2654            return mProtectedBroadcasts.contains(actionName);
2655        }
2656    }
2657
2658    @Override
2659    public int checkSignatures(String pkg1, String pkg2) {
2660        synchronized (mPackages) {
2661            final PackageParser.Package p1 = mPackages.get(pkg1);
2662            final PackageParser.Package p2 = mPackages.get(pkg2);
2663            if (p1 == null || p1.mExtras == null
2664                    || p2 == null || p2.mExtras == null) {
2665                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2666            }
2667            return compareSignatures(p1.mSignatures, p2.mSignatures);
2668        }
2669    }
2670
2671    @Override
2672    public int checkUidSignatures(int uid1, int uid2) {
2673        // Map to base uids.
2674        uid1 = UserHandle.getAppId(uid1);
2675        uid2 = UserHandle.getAppId(uid2);
2676        // reader
2677        synchronized (mPackages) {
2678            Signature[] s1;
2679            Signature[] s2;
2680            Object obj = mSettings.getUserIdLPr(uid1);
2681            if (obj != null) {
2682                if (obj instanceof SharedUserSetting) {
2683                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2684                } else if (obj instanceof PackageSetting) {
2685                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2686                } else {
2687                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2688                }
2689            } else {
2690                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2691            }
2692            obj = mSettings.getUserIdLPr(uid2);
2693            if (obj != null) {
2694                if (obj instanceof SharedUserSetting) {
2695                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2696                } else if (obj instanceof PackageSetting) {
2697                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2698                } else {
2699                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2700                }
2701            } else {
2702                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2703            }
2704            return compareSignatures(s1, s2);
2705        }
2706    }
2707
2708    /**
2709     * Compares two sets of signatures. Returns:
2710     * <br />
2711     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2712     * <br />
2713     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2714     * <br />
2715     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2716     * <br />
2717     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2718     * <br />
2719     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2720     */
2721    static int compareSignatures(Signature[] s1, Signature[] s2) {
2722        if (s1 == null) {
2723            return s2 == null
2724                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2725                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2726        }
2727
2728        if (s2 == null) {
2729            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2730        }
2731
2732        if (s1.length != s2.length) {
2733            return PackageManager.SIGNATURE_NO_MATCH;
2734        }
2735
2736        // Since both signature sets are of size 1, we can compare without HashSets.
2737        if (s1.length == 1) {
2738            return s1[0].equals(s2[0]) ?
2739                    PackageManager.SIGNATURE_MATCH :
2740                    PackageManager.SIGNATURE_NO_MATCH;
2741        }
2742
2743        HashSet<Signature> set1 = new HashSet<Signature>();
2744        for (Signature sig : s1) {
2745            set1.add(sig);
2746        }
2747        HashSet<Signature> set2 = new HashSet<Signature>();
2748        for (Signature sig : s2) {
2749            set2.add(sig);
2750        }
2751        // Make sure s2 contains all signatures in s1.
2752        if (set1.equals(set2)) {
2753            return PackageManager.SIGNATURE_MATCH;
2754        }
2755        return PackageManager.SIGNATURE_NO_MATCH;
2756    }
2757
2758    /**
2759     * If the database version for this type of package (internal storage or
2760     * external storage) is less than the version where package signatures
2761     * were updated, return true.
2762     */
2763    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2764        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2765                DatabaseVersion.SIGNATURE_END_ENTITY))
2766                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2767                        DatabaseVersion.SIGNATURE_END_ENTITY));
2768    }
2769
2770    /**
2771     * Used for backward compatibility to make sure any packages with
2772     * certificate chains get upgraded to the new style. {@code existingSigs}
2773     * will be in the old format (since they were stored on disk from before the
2774     * system upgrade) and {@code scannedSigs} will be in the newer format.
2775     */
2776    private int compareSignaturesCompat(PackageSignatures existingSigs,
2777            PackageParser.Package scannedPkg) {
2778        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2779            return PackageManager.SIGNATURE_NO_MATCH;
2780        }
2781
2782        HashSet<Signature> existingSet = new HashSet<Signature>();
2783        for (Signature sig : existingSigs.mSignatures) {
2784            existingSet.add(sig);
2785        }
2786        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2787        for (Signature sig : scannedPkg.mSignatures) {
2788            try {
2789                Signature[] chainSignatures = sig.getChainSignatures();
2790                for (Signature chainSig : chainSignatures) {
2791                    scannedCompatSet.add(chainSig);
2792                }
2793            } catch (CertificateEncodingException e) {
2794                scannedCompatSet.add(sig);
2795            }
2796        }
2797        /*
2798         * Make sure the expanded scanned set contains all signatures in the
2799         * existing one.
2800         */
2801        if (scannedCompatSet.equals(existingSet)) {
2802            // Migrate the old signatures to the new scheme.
2803            existingSigs.assignSignatures(scannedPkg.mSignatures);
2804            // The new KeySets will be re-added later in the scanning process.
2805            synchronized (mPackages) {
2806                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2807            }
2808            return PackageManager.SIGNATURE_MATCH;
2809        }
2810        return PackageManager.SIGNATURE_NO_MATCH;
2811    }
2812
2813    @Override
2814    public String[] getPackagesForUid(int uid) {
2815        uid = UserHandle.getAppId(uid);
2816        // reader
2817        synchronized (mPackages) {
2818            Object obj = mSettings.getUserIdLPr(uid);
2819            if (obj instanceof SharedUserSetting) {
2820                final SharedUserSetting sus = (SharedUserSetting) obj;
2821                final int N = sus.packages.size();
2822                final String[] res = new String[N];
2823                final Iterator<PackageSetting> it = sus.packages.iterator();
2824                int i = 0;
2825                while (it.hasNext()) {
2826                    res[i++] = it.next().name;
2827                }
2828                return res;
2829            } else if (obj instanceof PackageSetting) {
2830                final PackageSetting ps = (PackageSetting) obj;
2831                return new String[] { ps.name };
2832            }
2833        }
2834        return null;
2835    }
2836
2837    @Override
2838    public String getNameForUid(int uid) {
2839        // reader
2840        synchronized (mPackages) {
2841            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2842            if (obj instanceof SharedUserSetting) {
2843                final SharedUserSetting sus = (SharedUserSetting) obj;
2844                return sus.name + ":" + sus.userId;
2845            } else if (obj instanceof PackageSetting) {
2846                final PackageSetting ps = (PackageSetting) obj;
2847                return ps.name;
2848            }
2849        }
2850        return null;
2851    }
2852
2853    @Override
2854    public int getUidForSharedUser(String sharedUserName) {
2855        if(sharedUserName == null) {
2856            return -1;
2857        }
2858        // reader
2859        synchronized (mPackages) {
2860            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2861            if (suid == null) {
2862                return -1;
2863            }
2864            return suid.userId;
2865        }
2866    }
2867
2868    @Override
2869    public int getFlagsForUid(int uid) {
2870        synchronized (mPackages) {
2871            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2872            if (obj instanceof SharedUserSetting) {
2873                final SharedUserSetting sus = (SharedUserSetting) obj;
2874                return sus.pkgFlags;
2875            } else if (obj instanceof PackageSetting) {
2876                final PackageSetting ps = (PackageSetting) obj;
2877                return ps.pkgFlags;
2878            }
2879        }
2880        return 0;
2881    }
2882
2883    @Override
2884    public String[] getAppOpPermissionPackages(String permissionName) {
2885        synchronized (mPackages) {
2886            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2887            if (pkgs == null) {
2888                return null;
2889            }
2890            return pkgs.toArray(new String[pkgs.size()]);
2891        }
2892    }
2893
2894    @Override
2895    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2896            int flags, int userId) {
2897        if (!sUserManager.exists(userId)) return null;
2898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2899        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2900        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2901    }
2902
2903    @Override
2904    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2905            IntentFilter filter, int match, ComponentName activity) {
2906        final int userId = UserHandle.getCallingUserId();
2907        if (DEBUG_PREFERRED) {
2908            Log.v(TAG, "setLastChosenActivity intent=" + intent
2909                + " resolvedType=" + resolvedType
2910                + " flags=" + flags
2911                + " filter=" + filter
2912                + " match=" + match
2913                + " activity=" + activity);
2914            filter.dump(new PrintStreamPrinter(System.out), "    ");
2915        }
2916        intent.setComponent(null);
2917        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2918        // Find any earlier preferred or last chosen entries and nuke them
2919        findPreferredActivity(intent, resolvedType,
2920                flags, query, 0, false, true, false, userId);
2921        // Add the new activity as the last chosen for this filter
2922        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2923                "Setting last chosen");
2924    }
2925
2926    @Override
2927    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2928        final int userId = UserHandle.getCallingUserId();
2929        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2930        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2931        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2932                false, false, false, userId);
2933    }
2934
2935    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2936            int flags, List<ResolveInfo> query, int userId) {
2937        if (query != null) {
2938            final int N = query.size();
2939            if (N == 1) {
2940                return query.get(0);
2941            } else if (N > 1) {
2942                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2943                // If there is more than one activity with the same priority,
2944                // then let the user decide between them.
2945                ResolveInfo r0 = query.get(0);
2946                ResolveInfo r1 = query.get(1);
2947                if (DEBUG_INTENT_MATCHING || debug) {
2948                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2949                            + r1.activityInfo.name + "=" + r1.priority);
2950                }
2951                // If the first activity has a higher priority, or a different
2952                // default, then it is always desireable to pick it.
2953                if (r0.priority != r1.priority
2954                        || r0.preferredOrder != r1.preferredOrder
2955                        || r0.isDefault != r1.isDefault) {
2956                    return query.get(0);
2957                }
2958                // If we have saved a preference for a preferred activity for
2959                // this Intent, use that.
2960                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2961                        flags, query, r0.priority, true, false, debug, userId);
2962                if (ri != null) {
2963                    return ri;
2964                }
2965                if (userId != 0) {
2966                    ri = new ResolveInfo(mResolveInfo);
2967                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2968                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2969                            ri.activityInfo.applicationInfo);
2970                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2971                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2972                    return ri;
2973                }
2974                return mResolveInfo;
2975            }
2976        }
2977        return null;
2978    }
2979
2980    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2981            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2982        final int N = query.size();
2983        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2984                .get(userId);
2985        // Get the list of persistent preferred activities that handle the intent
2986        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2987        List<PersistentPreferredActivity> pprefs = ppir != null
2988                ? ppir.queryIntent(intent, resolvedType,
2989                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2990                : null;
2991        if (pprefs != null && pprefs.size() > 0) {
2992            final int M = pprefs.size();
2993            for (int i=0; i<M; i++) {
2994                final PersistentPreferredActivity ppa = pprefs.get(i);
2995                if (DEBUG_PREFERRED || debug) {
2996                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2997                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2998                            + "\n  component=" + ppa.mComponent);
2999                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3000                }
3001                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3002                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3003                if (DEBUG_PREFERRED || debug) {
3004                    Slog.v(TAG, "Found persistent preferred activity:");
3005                    if (ai != null) {
3006                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3007                    } else {
3008                        Slog.v(TAG, "  null");
3009                    }
3010                }
3011                if (ai == null) {
3012                    // This previously registered persistent preferred activity
3013                    // component is no longer known. Ignore it and do NOT remove it.
3014                    continue;
3015                }
3016                for (int j=0; j<N; j++) {
3017                    final ResolveInfo ri = query.get(j);
3018                    if (!ri.activityInfo.applicationInfo.packageName
3019                            .equals(ai.applicationInfo.packageName)) {
3020                        continue;
3021                    }
3022                    if (!ri.activityInfo.name.equals(ai.name)) {
3023                        continue;
3024                    }
3025                    //  Found a persistent preference that can handle the intent.
3026                    if (DEBUG_PREFERRED || debug) {
3027                        Slog.v(TAG, "Returning persistent preferred activity: " +
3028                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3029                    }
3030                    return ri;
3031                }
3032            }
3033        }
3034        return null;
3035    }
3036
3037    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3038            List<ResolveInfo> query, int priority, boolean always,
3039            boolean removeMatches, boolean debug, int userId) {
3040        if (!sUserManager.exists(userId)) return null;
3041        // writer
3042        synchronized (mPackages) {
3043            if (intent.getSelector() != null) {
3044                intent = intent.getSelector();
3045            }
3046            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3047
3048            // Try to find a matching persistent preferred activity.
3049            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3050                    debug, userId);
3051
3052            // If a persistent preferred activity matched, use it.
3053            if (pri != null) {
3054                return pri;
3055            }
3056
3057            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3058            // Get the list of preferred activities that handle the intent
3059            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3060            List<PreferredActivity> prefs = pir != null
3061                    ? pir.queryIntent(intent, resolvedType,
3062                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3063                    : null;
3064            if (prefs != null && prefs.size() > 0) {
3065                boolean changed = false;
3066                try {
3067                    // First figure out how good the original match set is.
3068                    // We will only allow preferred activities that came
3069                    // from the same match quality.
3070                    int match = 0;
3071
3072                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3073
3074                    final int N = query.size();
3075                    for (int j=0; j<N; j++) {
3076                        final ResolveInfo ri = query.get(j);
3077                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3078                                + ": 0x" + Integer.toHexString(match));
3079                        if (ri.match > match) {
3080                            match = ri.match;
3081                        }
3082                    }
3083
3084                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3085                            + Integer.toHexString(match));
3086
3087                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3088                    final int M = prefs.size();
3089                    for (int i=0; i<M; i++) {
3090                        final PreferredActivity pa = prefs.get(i);
3091                        if (DEBUG_PREFERRED || debug) {
3092                            Slog.v(TAG, "Checking PreferredActivity ds="
3093                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3094                                    + "\n  component=" + pa.mPref.mComponent);
3095                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3096                        }
3097                        if (pa.mPref.mMatch != match) {
3098                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3099                                    + Integer.toHexString(pa.mPref.mMatch));
3100                            continue;
3101                        }
3102                        // If it's not an "always" type preferred activity and that's what we're
3103                        // looking for, skip it.
3104                        if (always && !pa.mPref.mAlways) {
3105                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3106                            continue;
3107                        }
3108                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3109                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3110                        if (DEBUG_PREFERRED || debug) {
3111                            Slog.v(TAG, "Found preferred activity:");
3112                            if (ai != null) {
3113                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3114                            } else {
3115                                Slog.v(TAG, "  null");
3116                            }
3117                        }
3118                        if (ai == null) {
3119                            // This previously registered preferred activity
3120                            // component is no longer known.  Most likely an update
3121                            // to the app was installed and in the new version this
3122                            // component no longer exists.  Clean it up by removing
3123                            // it from the preferred activities list, and skip it.
3124                            Slog.w(TAG, "Removing dangling preferred activity: "
3125                                    + pa.mPref.mComponent);
3126                            pir.removeFilter(pa);
3127                            changed = true;
3128                            continue;
3129                        }
3130                        for (int j=0; j<N; j++) {
3131                            final ResolveInfo ri = query.get(j);
3132                            if (!ri.activityInfo.applicationInfo.packageName
3133                                    .equals(ai.applicationInfo.packageName)) {
3134                                continue;
3135                            }
3136                            if (!ri.activityInfo.name.equals(ai.name)) {
3137                                continue;
3138                            }
3139
3140                            if (removeMatches) {
3141                                pir.removeFilter(pa);
3142                                changed = true;
3143                                if (DEBUG_PREFERRED) {
3144                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3145                                }
3146                                break;
3147                            }
3148
3149                            // Okay we found a previously set preferred or last chosen app.
3150                            // If the result set is different from when this
3151                            // was created, we need to clear it and re-ask the
3152                            // user their preference, if we're looking for an "always" type entry.
3153                            if (always && !pa.mPref.sameSet(query, priority)) {
3154                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3155                                        + intent + " type " + resolvedType);
3156                                if (DEBUG_PREFERRED) {
3157                                    Slog.v(TAG, "Removing preferred activity since set changed "
3158                                            + pa.mPref.mComponent);
3159                                }
3160                                pir.removeFilter(pa);
3161                                // Re-add the filter as a "last chosen" entry (!always)
3162                                PreferredActivity lastChosen = new PreferredActivity(
3163                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3164                                pir.addFilter(lastChosen);
3165                                changed = true;
3166                                return null;
3167                            }
3168
3169                            // Yay! Either the set matched or we're looking for the last chosen
3170                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3171                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3172                            return ri;
3173                        }
3174                    }
3175                } finally {
3176                    if (changed) {
3177                        if (DEBUG_PREFERRED) {
3178                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3179                        }
3180                        mSettings.writePackageRestrictionsLPr(userId);
3181                    }
3182                }
3183            }
3184        }
3185        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3186        return null;
3187    }
3188
3189    /*
3190     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3191     */
3192    @Override
3193    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3194            int targetUserId) {
3195        mContext.enforceCallingOrSelfPermission(
3196                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3197        List<CrossProfileIntentFilter> matches =
3198                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3199        if (matches != null) {
3200            int size = matches.size();
3201            for (int i = 0; i < size; i++) {
3202                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3203            }
3204        }
3205        return false;
3206    }
3207
3208    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3209            String resolvedType, int userId) {
3210        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3211        if (resolver != null) {
3212            return resolver.queryIntent(intent, resolvedType, false, userId);
3213        }
3214        return null;
3215    }
3216
3217    @Override
3218    public List<ResolveInfo> queryIntentActivities(Intent intent,
3219            String resolvedType, int flags, int userId) {
3220        if (!sUserManager.exists(userId)) return Collections.emptyList();
3221        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3222        ComponentName comp = intent.getComponent();
3223        if (comp == null) {
3224            if (intent.getSelector() != null) {
3225                intent = intent.getSelector();
3226                comp = intent.getComponent();
3227            }
3228        }
3229
3230        if (comp != null) {
3231            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3232            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3233            if (ai != null) {
3234                final ResolveInfo ri = new ResolveInfo();
3235                ri.activityInfo = ai;
3236                list.add(ri);
3237            }
3238            return list;
3239        }
3240
3241        // reader
3242        synchronized (mPackages) {
3243            final String pkgName = intent.getPackage();
3244            if (pkgName == null) {
3245                List<CrossProfileIntentFilter> matchingFilters =
3246                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3247                // Check for results that need to skip the current profile.
3248                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3249                        resolvedType, flags, userId);
3250                if (resolveInfo != null) {
3251                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3252                    result.add(resolveInfo);
3253                    return result;
3254                }
3255                // Check for cross profile results.
3256                resolveInfo = queryCrossProfileIntents(
3257                        matchingFilters, intent, resolvedType, flags, userId);
3258
3259                // Check for results in the current profile.
3260                List<ResolveInfo> result = mActivities.queryIntent(
3261                        intent, resolvedType, flags, userId);
3262                if (resolveInfo != null) {
3263                    result.add(resolveInfo);
3264                    Collections.sort(result, mResolvePrioritySorter);
3265                }
3266                return result;
3267            }
3268            final PackageParser.Package pkg = mPackages.get(pkgName);
3269            if (pkg != null) {
3270                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3271                        pkg.activities, userId);
3272            }
3273            return new ArrayList<ResolveInfo>();
3274        }
3275    }
3276
3277    private ResolveInfo querySkipCurrentProfileIntents(
3278            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3279            int flags, int sourceUserId) {
3280        if (matchingFilters != null) {
3281            int size = matchingFilters.size();
3282            for (int i = 0; i < size; i ++) {
3283                CrossProfileIntentFilter filter = matchingFilters.get(i);
3284                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3285                    // Checking if there are activities in the target user that can handle the
3286                    // intent.
3287                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3288                            flags, sourceUserId);
3289                    if (resolveInfo != null) {
3290                        return resolveInfo;
3291                    }
3292                }
3293            }
3294        }
3295        return null;
3296    }
3297
3298    // Return matching ResolveInfo if any for skip current profile intent filters.
3299    private ResolveInfo queryCrossProfileIntents(
3300            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3301            int flags, int sourceUserId) {
3302        if (matchingFilters != null) {
3303            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3304            // match the same intent. For performance reasons, it is better not to
3305            // run queryIntent twice for the same userId
3306            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3307            int size = matchingFilters.size();
3308            for (int i = 0; i < size; i++) {
3309                CrossProfileIntentFilter filter = matchingFilters.get(i);
3310                int targetUserId = filter.getTargetUserId();
3311                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3312                        && !alreadyTriedUserIds.get(targetUserId)) {
3313                    // Checking if there are activities in the target user that can handle the
3314                    // intent.
3315                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3316                            flags, sourceUserId);
3317                    if (resolveInfo != null) return resolveInfo;
3318                    alreadyTriedUserIds.put(targetUserId, true);
3319                }
3320            }
3321        }
3322        return null;
3323    }
3324
3325    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3326            String resolvedType, int flags, int sourceUserId) {
3327        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3328                resolvedType, flags, filter.getTargetUserId());
3329        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3330            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3331        }
3332        return null;
3333    }
3334
3335    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3336            int sourceUserId, int targetUserId) {
3337        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3338        String className;
3339        if (targetUserId == UserHandle.USER_OWNER) {
3340            className = FORWARD_INTENT_TO_USER_OWNER;
3341        } else {
3342            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3343        }
3344        ComponentName forwardingActivityComponentName = new ComponentName(
3345                mAndroidApplication.packageName, className);
3346        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3347                sourceUserId);
3348        if (targetUserId == UserHandle.USER_OWNER) {
3349            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3350            forwardingResolveInfo.noResourceId = true;
3351        }
3352        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3353        forwardingResolveInfo.priority = 0;
3354        forwardingResolveInfo.preferredOrder = 0;
3355        forwardingResolveInfo.match = 0;
3356        forwardingResolveInfo.isDefault = true;
3357        forwardingResolveInfo.filter = filter;
3358        forwardingResolveInfo.targetUserId = targetUserId;
3359        return forwardingResolveInfo;
3360    }
3361
3362    @Override
3363    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3364            Intent[] specifics, String[] specificTypes, Intent intent,
3365            String resolvedType, int flags, int userId) {
3366        if (!sUserManager.exists(userId)) return Collections.emptyList();
3367        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3368                false, "query intent activity options");
3369        final String resultsAction = intent.getAction();
3370
3371        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3372                | PackageManager.GET_RESOLVED_FILTER, userId);
3373
3374        if (DEBUG_INTENT_MATCHING) {
3375            Log.v(TAG, "Query " + intent + ": " + results);
3376        }
3377
3378        int specificsPos = 0;
3379        int N;
3380
3381        // todo: note that the algorithm used here is O(N^2).  This
3382        // isn't a problem in our current environment, but if we start running
3383        // into situations where we have more than 5 or 10 matches then this
3384        // should probably be changed to something smarter...
3385
3386        // First we go through and resolve each of the specific items
3387        // that were supplied, taking care of removing any corresponding
3388        // duplicate items in the generic resolve list.
3389        if (specifics != null) {
3390            for (int i=0; i<specifics.length; i++) {
3391                final Intent sintent = specifics[i];
3392                if (sintent == null) {
3393                    continue;
3394                }
3395
3396                if (DEBUG_INTENT_MATCHING) {
3397                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3398                }
3399
3400                String action = sintent.getAction();
3401                if (resultsAction != null && resultsAction.equals(action)) {
3402                    // If this action was explicitly requested, then don't
3403                    // remove things that have it.
3404                    action = null;
3405                }
3406
3407                ResolveInfo ri = null;
3408                ActivityInfo ai = null;
3409
3410                ComponentName comp = sintent.getComponent();
3411                if (comp == null) {
3412                    ri = resolveIntent(
3413                        sintent,
3414                        specificTypes != null ? specificTypes[i] : null,
3415                            flags, userId);
3416                    if (ri == null) {
3417                        continue;
3418                    }
3419                    if (ri == mResolveInfo) {
3420                        // ACK!  Must do something better with this.
3421                    }
3422                    ai = ri.activityInfo;
3423                    comp = new ComponentName(ai.applicationInfo.packageName,
3424                            ai.name);
3425                } else {
3426                    ai = getActivityInfo(comp, flags, userId);
3427                    if (ai == null) {
3428                        continue;
3429                    }
3430                }
3431
3432                // Look for any generic query activities that are duplicates
3433                // of this specific one, and remove them from the results.
3434                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3435                N = results.size();
3436                int j;
3437                for (j=specificsPos; j<N; j++) {
3438                    ResolveInfo sri = results.get(j);
3439                    if ((sri.activityInfo.name.equals(comp.getClassName())
3440                            && sri.activityInfo.applicationInfo.packageName.equals(
3441                                    comp.getPackageName()))
3442                        || (action != null && sri.filter.matchAction(action))) {
3443                        results.remove(j);
3444                        if (DEBUG_INTENT_MATCHING) Log.v(
3445                            TAG, "Removing duplicate item from " + j
3446                            + " due to specific " + specificsPos);
3447                        if (ri == null) {
3448                            ri = sri;
3449                        }
3450                        j--;
3451                        N--;
3452                    }
3453                }
3454
3455                // Add this specific item to its proper place.
3456                if (ri == null) {
3457                    ri = new ResolveInfo();
3458                    ri.activityInfo = ai;
3459                }
3460                results.add(specificsPos, ri);
3461                ri.specificIndex = i;
3462                specificsPos++;
3463            }
3464        }
3465
3466        // Now we go through the remaining generic results and remove any
3467        // duplicate actions that are found here.
3468        N = results.size();
3469        for (int i=specificsPos; i<N-1; i++) {
3470            final ResolveInfo rii = results.get(i);
3471            if (rii.filter == null) {
3472                continue;
3473            }
3474
3475            // Iterate over all of the actions of this result's intent
3476            // filter...  typically this should be just one.
3477            final Iterator<String> it = rii.filter.actionsIterator();
3478            if (it == null) {
3479                continue;
3480            }
3481            while (it.hasNext()) {
3482                final String action = it.next();
3483                if (resultsAction != null && resultsAction.equals(action)) {
3484                    // If this action was explicitly requested, then don't
3485                    // remove things that have it.
3486                    continue;
3487                }
3488                for (int j=i+1; j<N; j++) {
3489                    final ResolveInfo rij = results.get(j);
3490                    if (rij.filter != null && rij.filter.hasAction(action)) {
3491                        results.remove(j);
3492                        if (DEBUG_INTENT_MATCHING) Log.v(
3493                            TAG, "Removing duplicate item from " + j
3494                            + " due to action " + action + " at " + i);
3495                        j--;
3496                        N--;
3497                    }
3498                }
3499            }
3500
3501            // If the caller didn't request filter information, drop it now
3502            // so we don't have to marshall/unmarshall it.
3503            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3504                rii.filter = null;
3505            }
3506        }
3507
3508        // Filter out the caller activity if so requested.
3509        if (caller != null) {
3510            N = results.size();
3511            for (int i=0; i<N; i++) {
3512                ActivityInfo ainfo = results.get(i).activityInfo;
3513                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3514                        && caller.getClassName().equals(ainfo.name)) {
3515                    results.remove(i);
3516                    break;
3517                }
3518            }
3519        }
3520
3521        // If the caller didn't request filter information,
3522        // drop them now so we don't have to
3523        // marshall/unmarshall it.
3524        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3525            N = results.size();
3526            for (int i=0; i<N; i++) {
3527                results.get(i).filter = null;
3528            }
3529        }
3530
3531        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3532        return results;
3533    }
3534
3535    @Override
3536    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3537            int userId) {
3538        if (!sUserManager.exists(userId)) return Collections.emptyList();
3539        ComponentName comp = intent.getComponent();
3540        if (comp == null) {
3541            if (intent.getSelector() != null) {
3542                intent = intent.getSelector();
3543                comp = intent.getComponent();
3544            }
3545        }
3546        if (comp != null) {
3547            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3548            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3549            if (ai != null) {
3550                ResolveInfo ri = new ResolveInfo();
3551                ri.activityInfo = ai;
3552                list.add(ri);
3553            }
3554            return list;
3555        }
3556
3557        // reader
3558        synchronized (mPackages) {
3559            String pkgName = intent.getPackage();
3560            if (pkgName == null) {
3561                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3562            }
3563            final PackageParser.Package pkg = mPackages.get(pkgName);
3564            if (pkg != null) {
3565                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3566                        userId);
3567            }
3568            return null;
3569        }
3570    }
3571
3572    @Override
3573    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3574        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3575        if (!sUserManager.exists(userId)) return null;
3576        if (query != null) {
3577            if (query.size() >= 1) {
3578                // If there is more than one service with the same priority,
3579                // just arbitrarily pick the first one.
3580                return query.get(0);
3581            }
3582        }
3583        return null;
3584    }
3585
3586    @Override
3587    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3588            int userId) {
3589        if (!sUserManager.exists(userId)) return Collections.emptyList();
3590        ComponentName comp = intent.getComponent();
3591        if (comp == null) {
3592            if (intent.getSelector() != null) {
3593                intent = intent.getSelector();
3594                comp = intent.getComponent();
3595            }
3596        }
3597        if (comp != null) {
3598            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3599            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3600            if (si != null) {
3601                final ResolveInfo ri = new ResolveInfo();
3602                ri.serviceInfo = si;
3603                list.add(ri);
3604            }
3605            return list;
3606        }
3607
3608        // reader
3609        synchronized (mPackages) {
3610            String pkgName = intent.getPackage();
3611            if (pkgName == null) {
3612                return mServices.queryIntent(intent, resolvedType, flags, userId);
3613            }
3614            final PackageParser.Package pkg = mPackages.get(pkgName);
3615            if (pkg != null) {
3616                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3617                        userId);
3618            }
3619            return null;
3620        }
3621    }
3622
3623    @Override
3624    public List<ResolveInfo> queryIntentContentProviders(
3625            Intent intent, String resolvedType, int flags, int userId) {
3626        if (!sUserManager.exists(userId)) return Collections.emptyList();
3627        ComponentName comp = intent.getComponent();
3628        if (comp == null) {
3629            if (intent.getSelector() != null) {
3630                intent = intent.getSelector();
3631                comp = intent.getComponent();
3632            }
3633        }
3634        if (comp != null) {
3635            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3636            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3637            if (pi != null) {
3638                final ResolveInfo ri = new ResolveInfo();
3639                ri.providerInfo = pi;
3640                list.add(ri);
3641            }
3642            return list;
3643        }
3644
3645        // reader
3646        synchronized (mPackages) {
3647            String pkgName = intent.getPackage();
3648            if (pkgName == null) {
3649                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3650            }
3651            final PackageParser.Package pkg = mPackages.get(pkgName);
3652            if (pkg != null) {
3653                return mProviders.queryIntentForPackage(
3654                        intent, resolvedType, flags, pkg.providers, userId);
3655            }
3656            return null;
3657        }
3658    }
3659
3660    @Override
3661    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3662        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3663
3664        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3665
3666        // writer
3667        synchronized (mPackages) {
3668            ArrayList<PackageInfo> list;
3669            if (listUninstalled) {
3670                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3671                for (PackageSetting ps : mSettings.mPackages.values()) {
3672                    PackageInfo pi;
3673                    if (ps.pkg != null) {
3674                        pi = generatePackageInfo(ps.pkg, flags, userId);
3675                    } else {
3676                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3677                    }
3678                    if (pi != null) {
3679                        list.add(pi);
3680                    }
3681                }
3682            } else {
3683                list = new ArrayList<PackageInfo>(mPackages.size());
3684                for (PackageParser.Package p : mPackages.values()) {
3685                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3686                    if (pi != null) {
3687                        list.add(pi);
3688                    }
3689                }
3690            }
3691
3692            return new ParceledListSlice<PackageInfo>(list);
3693        }
3694    }
3695
3696    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3697            String[] permissions, boolean[] tmp, int flags, int userId) {
3698        int numMatch = 0;
3699        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3700        for (int i=0; i<permissions.length; i++) {
3701            if (gp.grantedPermissions.contains(permissions[i])) {
3702                tmp[i] = true;
3703                numMatch++;
3704            } else {
3705                tmp[i] = false;
3706            }
3707        }
3708        if (numMatch == 0) {
3709            return;
3710        }
3711        PackageInfo pi;
3712        if (ps.pkg != null) {
3713            pi = generatePackageInfo(ps.pkg, flags, userId);
3714        } else {
3715            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3716        }
3717        // The above might return null in cases of uninstalled apps or install-state
3718        // skew across users/profiles.
3719        if (pi != null) {
3720            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3721                if (numMatch == permissions.length) {
3722                    pi.requestedPermissions = permissions;
3723                } else {
3724                    pi.requestedPermissions = new String[numMatch];
3725                    numMatch = 0;
3726                    for (int i=0; i<permissions.length; i++) {
3727                        if (tmp[i]) {
3728                            pi.requestedPermissions[numMatch] = permissions[i];
3729                            numMatch++;
3730                        }
3731                    }
3732                }
3733            }
3734            list.add(pi);
3735        }
3736    }
3737
3738    @Override
3739    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3740            String[] permissions, int flags, int userId) {
3741        if (!sUserManager.exists(userId)) return null;
3742        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3743
3744        // writer
3745        synchronized (mPackages) {
3746            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3747            boolean[] tmpBools = new boolean[permissions.length];
3748            if (listUninstalled) {
3749                for (PackageSetting ps : mSettings.mPackages.values()) {
3750                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3751                }
3752            } else {
3753                for (PackageParser.Package pkg : mPackages.values()) {
3754                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3755                    if (ps != null) {
3756                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3757                                userId);
3758                    }
3759                }
3760            }
3761
3762            return new ParceledListSlice<PackageInfo>(list);
3763        }
3764    }
3765
3766    @Override
3767    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3768        if (!sUserManager.exists(userId)) return null;
3769        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3770
3771        // writer
3772        synchronized (mPackages) {
3773            ArrayList<ApplicationInfo> list;
3774            if (listUninstalled) {
3775                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3776                for (PackageSetting ps : mSettings.mPackages.values()) {
3777                    ApplicationInfo ai;
3778                    if (ps.pkg != null) {
3779                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3780                                ps.readUserState(userId), userId);
3781                    } else {
3782                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3783                    }
3784                    if (ai != null) {
3785                        list.add(ai);
3786                    }
3787                }
3788            } else {
3789                list = new ArrayList<ApplicationInfo>(mPackages.size());
3790                for (PackageParser.Package p : mPackages.values()) {
3791                    if (p.mExtras != null) {
3792                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3793                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3794                        if (ai != null) {
3795                            list.add(ai);
3796                        }
3797                    }
3798                }
3799            }
3800
3801            return new ParceledListSlice<ApplicationInfo>(list);
3802        }
3803    }
3804
3805    public List<ApplicationInfo> getPersistentApplications(int flags) {
3806        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3807
3808        // reader
3809        synchronized (mPackages) {
3810            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3811            final int userId = UserHandle.getCallingUserId();
3812            while (i.hasNext()) {
3813                final PackageParser.Package p = i.next();
3814                if (p.applicationInfo != null
3815                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3816                        && (!mSafeMode || isSystemApp(p))) {
3817                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3818                    if (ps != null) {
3819                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3820                                ps.readUserState(userId), userId);
3821                        if (ai != null) {
3822                            finalList.add(ai);
3823                        }
3824                    }
3825                }
3826            }
3827        }
3828
3829        return finalList;
3830    }
3831
3832    @Override
3833    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3834        if (!sUserManager.exists(userId)) return null;
3835        // reader
3836        synchronized (mPackages) {
3837            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3838            PackageSetting ps = provider != null
3839                    ? mSettings.mPackages.get(provider.owner.packageName)
3840                    : null;
3841            return ps != null
3842                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3843                    && (!mSafeMode || (provider.info.applicationInfo.flags
3844                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3845                    ? PackageParser.generateProviderInfo(provider, flags,
3846                            ps.readUserState(userId), userId)
3847                    : null;
3848        }
3849    }
3850
3851    /**
3852     * @deprecated
3853     */
3854    @Deprecated
3855    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3856        // reader
3857        synchronized (mPackages) {
3858            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3859                    .entrySet().iterator();
3860            final int userId = UserHandle.getCallingUserId();
3861            while (i.hasNext()) {
3862                Map.Entry<String, PackageParser.Provider> entry = i.next();
3863                PackageParser.Provider p = entry.getValue();
3864                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3865
3866                if (ps != null && p.syncable
3867                        && (!mSafeMode || (p.info.applicationInfo.flags
3868                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3869                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3870                            ps.readUserState(userId), userId);
3871                    if (info != null) {
3872                        outNames.add(entry.getKey());
3873                        outInfo.add(info);
3874                    }
3875                }
3876            }
3877        }
3878    }
3879
3880    @Override
3881    public List<ProviderInfo> queryContentProviders(String processName,
3882            int uid, int flags) {
3883        ArrayList<ProviderInfo> finalList = null;
3884        // reader
3885        synchronized (mPackages) {
3886            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3887            final int userId = processName != null ?
3888                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3889            while (i.hasNext()) {
3890                final PackageParser.Provider p = i.next();
3891                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3892                if (ps != null && p.info.authority != null
3893                        && (processName == null
3894                                || (p.info.processName.equals(processName)
3895                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3896                        && mSettings.isEnabledLPr(p.info, flags, userId)
3897                        && (!mSafeMode
3898                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3899                    if (finalList == null) {
3900                        finalList = new ArrayList<ProviderInfo>(3);
3901                    }
3902                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3903                            ps.readUserState(userId), userId);
3904                    if (info != null) {
3905                        finalList.add(info);
3906                    }
3907                }
3908            }
3909        }
3910
3911        if (finalList != null) {
3912            Collections.sort(finalList, mProviderInitOrderSorter);
3913        }
3914
3915        return finalList;
3916    }
3917
3918    @Override
3919    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3920            int flags) {
3921        // reader
3922        synchronized (mPackages) {
3923            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3924            return PackageParser.generateInstrumentationInfo(i, flags);
3925        }
3926    }
3927
3928    @Override
3929    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3930            int flags) {
3931        ArrayList<InstrumentationInfo> finalList =
3932            new ArrayList<InstrumentationInfo>();
3933
3934        // reader
3935        synchronized (mPackages) {
3936            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3937            while (i.hasNext()) {
3938                final PackageParser.Instrumentation p = i.next();
3939                if (targetPackage == null
3940                        || targetPackage.equals(p.info.targetPackage)) {
3941                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3942                            flags);
3943                    if (ii != null) {
3944                        finalList.add(ii);
3945                    }
3946                }
3947            }
3948        }
3949
3950        return finalList;
3951    }
3952
3953    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3954        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3955        if (overlays == null) {
3956            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3957            return;
3958        }
3959        for (PackageParser.Package opkg : overlays.values()) {
3960            // Not much to do if idmap fails: we already logged the error
3961            // and we certainly don't want to abort installation of pkg simply
3962            // because an overlay didn't fit properly. For these reasons,
3963            // ignore the return value of createIdmapForPackagePairLI.
3964            createIdmapForPackagePairLI(pkg, opkg);
3965        }
3966    }
3967
3968    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3969            PackageParser.Package opkg) {
3970        if (!opkg.mTrustedOverlay) {
3971            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3972                    opkg.baseCodePath + ": overlay not trusted");
3973            return false;
3974        }
3975        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3976        if (overlaySet == null) {
3977            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3978                    opkg.baseCodePath + " but target package has no known overlays");
3979            return false;
3980        }
3981        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3982        // TODO: generate idmap for split APKs
3983        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3984            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3985                    + opkg.baseCodePath);
3986            return false;
3987        }
3988        PackageParser.Package[] overlayArray =
3989            overlaySet.values().toArray(new PackageParser.Package[0]);
3990        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3991            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3992                return p1.mOverlayPriority - p2.mOverlayPriority;
3993            }
3994        };
3995        Arrays.sort(overlayArray, cmp);
3996
3997        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3998        int i = 0;
3999        for (PackageParser.Package p : overlayArray) {
4000            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4001        }
4002        return true;
4003    }
4004
4005    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4006        final File[] files = dir.listFiles();
4007        if (ArrayUtils.isEmpty(files)) {
4008            Log.d(TAG, "No files in app dir " + dir);
4009            return;
4010        }
4011
4012        if (DEBUG_PACKAGE_SCANNING) {
4013            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4014                    + " flags=0x" + Integer.toHexString(parseFlags));
4015        }
4016
4017        for (File file : files) {
4018            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4019                    && !PackageInstallerService.isStageName(file.getName());
4020            if (!isPackage) {
4021                // Ignore entries which are not packages
4022                continue;
4023            }
4024            try {
4025                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4026                        scanFlags, currentTime, null);
4027            } catch (PackageManagerException e) {
4028                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4029
4030                // Delete invalid userdata apps
4031                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4032                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4033                    Slog.w(TAG, "Deleting invalid package at " + file);
4034                    if (file.isDirectory()) {
4035                        FileUtils.deleteContents(file);
4036                    }
4037                    file.delete();
4038                }
4039            }
4040        }
4041    }
4042
4043    private static File getSettingsProblemFile() {
4044        File dataDir = Environment.getDataDirectory();
4045        File systemDir = new File(dataDir, "system");
4046        File fname = new File(systemDir, "uiderrors.txt");
4047        return fname;
4048    }
4049
4050    static void reportSettingsProblem(int priority, String msg) {
4051        try {
4052            File fname = getSettingsProblemFile();
4053            FileOutputStream out = new FileOutputStream(fname, true);
4054            PrintWriter pw = new FastPrintWriter(out);
4055            SimpleDateFormat formatter = new SimpleDateFormat();
4056            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4057            pw.println(dateString + ": " + msg);
4058            pw.close();
4059            FileUtils.setPermissions(
4060                    fname.toString(),
4061                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4062                    -1, -1);
4063        } catch (java.io.IOException e) {
4064        }
4065        Slog.println(priority, TAG, msg);
4066    }
4067
4068    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4069            PackageParser.Package pkg, File srcFile, int parseFlags)
4070            throws PackageManagerException {
4071        if (ps != null
4072                && ps.codePath.equals(srcFile)
4073                && ps.timeStamp == srcFile.lastModified()
4074                && !isCompatSignatureUpdateNeeded(pkg)) {
4075            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4076            if (ps.signatures.mSignatures != null
4077                    && ps.signatures.mSignatures.length != 0
4078                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4079                // Optimization: reuse the existing cached certificates
4080                // if the package appears to be unchanged.
4081                pkg.mSignatures = ps.signatures.mSignatures;
4082                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4083                synchronized (mPackages) {
4084                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4085                }
4086                return;
4087            }
4088
4089            Slog.w(TAG, "PackageSetting for " + ps.name
4090                    + " is missing signatures.  Collecting certs again to recover them.");
4091        } else {
4092            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4093        }
4094
4095        try {
4096            pp.collectCertificates(pkg, parseFlags);
4097            pp.collectManifestDigest(pkg);
4098        } catch (PackageParserException e) {
4099            throw PackageManagerException.from(e);
4100        }
4101    }
4102
4103    /*
4104     *  Scan a package and return the newly parsed package.
4105     *  Returns null in case of errors and the error code is stored in mLastScanError
4106     */
4107    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4108            long currentTime, UserHandle user) throws PackageManagerException {
4109        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4110        parseFlags |= mDefParseFlags;
4111        PackageParser pp = new PackageParser();
4112        pp.setSeparateProcesses(mSeparateProcesses);
4113        pp.setOnlyCoreApps(mOnlyCore);
4114        pp.setDisplayMetrics(mMetrics);
4115
4116        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4117            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4118        }
4119
4120        final PackageParser.Package pkg;
4121        try {
4122            pkg = pp.parsePackage(scanFile, parseFlags);
4123        } catch (PackageParserException e) {
4124            throw PackageManagerException.from(e);
4125        }
4126
4127        PackageSetting ps = null;
4128        PackageSetting updatedPkg;
4129        // reader
4130        synchronized (mPackages) {
4131            // Look to see if we already know about this package.
4132            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4133            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4134                // This package has been renamed to its original name.  Let's
4135                // use that.
4136                ps = mSettings.peekPackageLPr(oldName);
4137            }
4138            // If there was no original package, see one for the real package name.
4139            if (ps == null) {
4140                ps = mSettings.peekPackageLPr(pkg.packageName);
4141            }
4142            // Check to see if this package could be hiding/updating a system
4143            // package.  Must look for it either under the original or real
4144            // package name depending on our state.
4145            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4146            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4147        }
4148        boolean updatedPkgBetter = false;
4149        // First check if this is a system package that may involve an update
4150        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4151            if (ps != null && !ps.codePath.equals(scanFile)) {
4152                // The path has changed from what was last scanned...  check the
4153                // version of the new path against what we have stored to determine
4154                // what to do.
4155                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4156                if (pkg.mVersionCode < ps.versionCode) {
4157                    // The system package has been updated and the code path does not match
4158                    // Ignore entry. Skip it.
4159                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4160                            + " ignored: updated version " + ps.versionCode
4161                            + " better than this " + pkg.mVersionCode);
4162                    if (!updatedPkg.codePath.equals(scanFile)) {
4163                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4164                                + ps.name + " changing from " + updatedPkg.codePathString
4165                                + " to " + scanFile);
4166                        updatedPkg.codePath = scanFile;
4167                        updatedPkg.codePathString = scanFile.toString();
4168                        // This is the point at which we know that the system-disk APK
4169                        // for this package has moved during a reboot (e.g. due to an OTA),
4170                        // so we need to reevaluate it for privilege policy.
4171                        if (locationIsPrivileged(scanFile)) {
4172                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4173                        }
4174                    }
4175                    updatedPkg.pkg = pkg;
4176                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4177                } else {
4178                    // The current app on the system partition is better than
4179                    // what we have updated to on the data partition; switch
4180                    // back to the system partition version.
4181                    // At this point, its safely assumed that package installation for
4182                    // apps in system partition will go through. If not there won't be a working
4183                    // version of the app
4184                    // writer
4185                    synchronized (mPackages) {
4186                        // Just remove the loaded entries from package lists.
4187                        mPackages.remove(ps.name);
4188                    }
4189                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4190                            + "reverting from " + ps.codePathString
4191                            + ": new version " + pkg.mVersionCode
4192                            + " better than installed " + ps.versionCode);
4193
4194                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4195                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4196                            getAppDexInstructionSets(ps));
4197                    synchronized (mInstallLock) {
4198                        args.cleanUpResourcesLI();
4199                    }
4200                    synchronized (mPackages) {
4201                        mSettings.enableSystemPackageLPw(ps.name);
4202                    }
4203                    updatedPkgBetter = true;
4204                }
4205            }
4206        }
4207
4208        if (updatedPkg != null) {
4209            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4210            // initially
4211            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4212
4213            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4214            // flag set initially
4215            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4216                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4217            }
4218        }
4219
4220        // Verify certificates against what was last scanned
4221        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4222
4223        /*
4224         * A new system app appeared, but we already had a non-system one of the
4225         * same name installed earlier.
4226         */
4227        boolean shouldHideSystemApp = false;
4228        if (updatedPkg == null && ps != null
4229                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4230            /*
4231             * Check to make sure the signatures match first. If they don't,
4232             * wipe the installed application and its data.
4233             */
4234            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4235                    != PackageManager.SIGNATURE_MATCH) {
4236                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4237                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4238                ps = null;
4239            } else {
4240                /*
4241                 * If the newly-added system app is an older version than the
4242                 * already installed version, hide it. It will be scanned later
4243                 * and re-added like an update.
4244                 */
4245                if (pkg.mVersionCode < ps.versionCode) {
4246                    shouldHideSystemApp = true;
4247                } else {
4248                    /*
4249                     * The newly found system app is a newer version that the
4250                     * one previously installed. Simply remove the
4251                     * already-installed application and replace it with our own
4252                     * while keeping the application data.
4253                     */
4254                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4255                            + ps.codePathString + ": new version " + pkg.mVersionCode
4256                            + " better than installed " + ps.versionCode);
4257                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4258                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4259                            getAppDexInstructionSets(ps));
4260                    synchronized (mInstallLock) {
4261                        args.cleanUpResourcesLI();
4262                    }
4263                }
4264            }
4265        }
4266
4267        // The apk is forward locked (not public) if its code and resources
4268        // are kept in different files. (except for app in either system or
4269        // vendor path).
4270        // TODO grab this value from PackageSettings
4271        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4272            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4273                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4274            }
4275        }
4276
4277        // TODO: extend to support forward-locked splits
4278        String resourcePath = null;
4279        String baseResourcePath = null;
4280        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4281            if (ps != null && ps.resourcePathString != null) {
4282                resourcePath = ps.resourcePathString;
4283                baseResourcePath = ps.resourcePathString;
4284            } else {
4285                // Should not happen at all. Just log an error.
4286                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4287            }
4288        } else {
4289            resourcePath = pkg.codePath;
4290            baseResourcePath = pkg.baseCodePath;
4291        }
4292
4293        // Set application objects path explicitly.
4294        pkg.applicationInfo.setCodePath(pkg.codePath);
4295        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4296        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4297        pkg.applicationInfo.setResourcePath(resourcePath);
4298        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4299        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4300
4301        // Note that we invoke the following method only if we are about to unpack an application
4302        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4303                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4304
4305        /*
4306         * If the system app should be overridden by a previously installed
4307         * data, hide the system app now and let the /data/app scan pick it up
4308         * again.
4309         */
4310        if (shouldHideSystemApp) {
4311            synchronized (mPackages) {
4312                /*
4313                 * We have to grant systems permissions before we hide, because
4314                 * grantPermissions will assume the package update is trying to
4315                 * expand its permissions.
4316                 */
4317                grantPermissionsLPw(pkg, true, pkg.packageName);
4318                mSettings.disableSystemPackageLPw(pkg.packageName);
4319            }
4320        }
4321
4322        return scannedPkg;
4323    }
4324
4325    private static String fixProcessName(String defProcessName,
4326            String processName, int uid) {
4327        if (processName == null) {
4328            return defProcessName;
4329        }
4330        return processName;
4331    }
4332
4333    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4334            throws PackageManagerException {
4335        if (pkgSetting.signatures.mSignatures != null) {
4336            // Already existing package. Make sure signatures match
4337            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4338                    == PackageManager.SIGNATURE_MATCH;
4339            if (!match) {
4340                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4341                        == PackageManager.SIGNATURE_MATCH;
4342            }
4343            if (!match) {
4344                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4345                        + pkg.packageName + " signatures do not match the "
4346                        + "previously installed version; ignoring!");
4347            }
4348        }
4349
4350        // Check for shared user signatures
4351        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4352            // Already existing package. Make sure signatures match
4353            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4354                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4355            if (!match) {
4356                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4357                        == PackageManager.SIGNATURE_MATCH;
4358            }
4359            if (!match) {
4360                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4361                        "Package " + pkg.packageName
4362                        + " has no signatures that match those in shared user "
4363                        + pkgSetting.sharedUser.name + "; ignoring!");
4364            }
4365        }
4366    }
4367
4368    /**
4369     * Enforces that only the system UID or root's UID can call a method exposed
4370     * via Binder.
4371     *
4372     * @param message used as message if SecurityException is thrown
4373     * @throws SecurityException if the caller is not system or root
4374     */
4375    private static final void enforceSystemOrRoot(String message) {
4376        final int uid = Binder.getCallingUid();
4377        if (uid != Process.SYSTEM_UID && uid != 0) {
4378            throw new SecurityException(message);
4379        }
4380    }
4381
4382    @Override
4383    public void performBootDexOpt() {
4384        enforceSystemOrRoot("Only the system can request dexopt be performed");
4385
4386        final HashSet<PackageParser.Package> pkgs;
4387        synchronized (mPackages) {
4388            pkgs = mDeferredDexOpt;
4389            mDeferredDexOpt = null;
4390        }
4391
4392        if (pkgs != null) {
4393            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4394            // in case the device runs out of space.
4395            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4396            // Give priority to system apps that listen for pre boot complete.
4397            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4398            HashSet<String> pkgNames = getPackageNamesForIntent(intent);
4399            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4400                PackageParser.Package pkg = it.next();
4401                if (pkgNames.contains(pkg.packageName)) {
4402                    sortedPkgs.add(pkg);
4403                    it.remove();
4404                }
4405            }
4406            // Give priority to system apps.
4407            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4408                PackageParser.Package pkg = it.next();
4409                if (isSystemApp(pkg)) {
4410                    sortedPkgs.add(pkg);
4411                    it.remove();
4412                }
4413            }
4414            // Give priority to apps that listen for boot complete.
4415            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4416            pkgNames = getPackageNamesForIntent(intent);
4417            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4418                PackageParser.Package pkg = it.next();
4419                if (pkgNames.contains(pkg.packageName)) {
4420                    sortedPkgs.add(pkg);
4421                    it.remove();
4422                }
4423            }
4424            // Filter out packages that aren't recently used.
4425            filterRecentlyUsedApps(pkgs);
4426            // Add all remaining apps.
4427            for (PackageParser.Package pkg : pkgs) {
4428                sortedPkgs.add(pkg);
4429            }
4430
4431            int i = 0;
4432            int total = sortedPkgs.size();
4433            for (PackageParser.Package pkg : sortedPkgs) {
4434                performBootDexOpt(pkg, ++i, total);
4435            }
4436        }
4437    }
4438
4439    private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
4440        // Filter out packages that aren't recently used.
4441        //
4442        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4443        // should do a full dexopt.
4444        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4445            // TODO: add a property to control this?
4446            long dexOptLRUThresholdInMinutes;
4447            if (mLazyDexOpt) {
4448                dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4449            } else {
4450                dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4451            }
4452            long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4453
4454            int total = pkgs.size();
4455            int skipped = 0;
4456            long now = System.currentTimeMillis();
4457            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4458                PackageParser.Package pkg = i.next();
4459                long then = pkg.mLastPackageUsageTimeInMills;
4460                if (then + dexOptLRUThresholdInMills < now) {
4461                    if (DEBUG_DEXOPT) {
4462                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4463                              ((then == 0) ? "never" : new Date(then)));
4464                    }
4465                    i.remove();
4466                    skipped++;
4467                }
4468            }
4469            if (DEBUG_DEXOPT) {
4470                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4471            }
4472        }
4473    }
4474
4475    private HashSet<String> getPackageNamesForIntent(Intent intent) {
4476        List<ResolveInfo> ris = null;
4477        try {
4478            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4479                    intent, null, 0, UserHandle.USER_OWNER);
4480        } catch (RemoteException e) {
4481        }
4482        HashSet<String> pkgNames = new HashSet<String>();
4483        if (ris != null) {
4484            for (ResolveInfo ri : ris) {
4485                pkgNames.add(ri.activityInfo.packageName);
4486            }
4487        }
4488        return pkgNames;
4489    }
4490
4491    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4492        if (DEBUG_DEXOPT) {
4493            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4494        }
4495        if (!isFirstBoot()) {
4496            try {
4497                ActivityManagerNative.getDefault().showBootMessage(
4498                        mContext.getResources().getString(R.string.android_upgrading_apk,
4499                                curr, total), true);
4500            } catch (RemoteException e) {
4501            }
4502        }
4503        PackageParser.Package p = pkg;
4504        synchronized (mInstallLock) {
4505            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4506                            false /* defer */, true /* include dependencies */);
4507        }
4508    }
4509
4510    @Override
4511    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4512        return performDexOpt(packageName, instructionSet, false);
4513    }
4514
4515    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4516        if (info.primaryCpuAbi == null) {
4517            return getPreferredInstructionSet();
4518        }
4519
4520        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4521    }
4522
4523    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4524        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4525        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4526        if (!dexopt && !updateUsage) {
4527            // We aren't going to dexopt or update usage, so bail early.
4528            return false;
4529        }
4530        PackageParser.Package p;
4531        final String targetInstructionSet;
4532        synchronized (mPackages) {
4533            p = mPackages.get(packageName);
4534            if (p == null) {
4535                return false;
4536            }
4537            if (updateUsage) {
4538                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4539            }
4540            mPackageUsage.write(false);
4541            if (!dexopt) {
4542                // We aren't going to dexopt, so bail early.
4543                return false;
4544            }
4545
4546            targetInstructionSet = instructionSet != null ? instructionSet :
4547                    getPrimaryInstructionSet(p.applicationInfo);
4548            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4549                return false;
4550            }
4551        }
4552
4553        synchronized (mInstallLock) {
4554            final String[] instructionSets = new String[] { targetInstructionSet };
4555            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4556                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4557        }
4558    }
4559
4560    public HashSet<String> getPackagesThatNeedDexOpt() {
4561        HashSet<String> pkgs = null;
4562        synchronized (mPackages) {
4563            for (PackageParser.Package p : mPackages.values()) {
4564                if (DEBUG_DEXOPT) {
4565                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4566                }
4567                if (!p.mDexOptPerformed.isEmpty()) {
4568                    continue;
4569                }
4570                if (pkgs == null) {
4571                    pkgs = new HashSet<String>();
4572                }
4573                pkgs.add(p.packageName);
4574            }
4575        }
4576        return pkgs;
4577    }
4578
4579    public void shutdown() {
4580        mPackageUsage.write(true);
4581    }
4582
4583    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4584             boolean forceDex, boolean defer, HashSet<String> done) {
4585        for (int i=0; i<libs.size(); i++) {
4586            PackageParser.Package libPkg;
4587            String libName;
4588            synchronized (mPackages) {
4589                libName = libs.get(i);
4590                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4591                if (lib != null && lib.apk != null) {
4592                    libPkg = mPackages.get(lib.apk);
4593                } else {
4594                    libPkg = null;
4595                }
4596            }
4597            if (libPkg != null && !done.contains(libName)) {
4598                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4599            }
4600        }
4601    }
4602
4603    static final int DEX_OPT_SKIPPED = 0;
4604    static final int DEX_OPT_PERFORMED = 1;
4605    static final int DEX_OPT_DEFERRED = 2;
4606    static final int DEX_OPT_FAILED = -1;
4607
4608    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4609            boolean forceDex, boolean defer, HashSet<String> done) {
4610        final String[] instructionSets = targetInstructionSets != null ?
4611                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4612
4613        if (done != null) {
4614            done.add(pkg.packageName);
4615            if (pkg.usesLibraries != null) {
4616                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4617            }
4618            if (pkg.usesOptionalLibraries != null) {
4619                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4620            }
4621        }
4622
4623        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4624            return DEX_OPT_SKIPPED;
4625        }
4626
4627        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4628
4629        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4630        boolean performedDexOpt = false;
4631        // There are three basic cases here:
4632        // 1.) we need to dexopt, either because we are forced or it is needed
4633        // 2.) we are defering a needed dexopt
4634        // 3.) we are skipping an unneeded dexopt
4635        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4636        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4637            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4638                continue;
4639            }
4640
4641            for (String path : paths) {
4642                try {
4643                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4644                    // patckage or the one we find does not match the image checksum (i.e. it was
4645                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4646                    // odex file and it matches the checksum of the image but not its base address,
4647                    // meaning we need to move it.
4648                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4649                            pkg.packageName, dexCodeInstructionSet, defer);
4650                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4651                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4652                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4653                                + " vmSafeMode=" + vmSafeMode);
4654                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4655                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4656                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4657
4658                        if (ret < 0) {
4659                            // Don't bother running dexopt again if we failed, it will probably
4660                            // just result in an error again. Also, don't bother dexopting for other
4661                            // paths & ISAs.
4662                            return DEX_OPT_FAILED;
4663                        }
4664
4665                        performedDexOpt = true;
4666                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4667                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4668                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4669                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4670                                pkg.packageName, dexCodeInstructionSet);
4671
4672                        if (ret < 0) {
4673                            // Don't bother running patchoat again if we failed, it will probably
4674                            // just result in an error again. Also, don't bother dexopting for other
4675                            // paths & ISAs.
4676                            return DEX_OPT_FAILED;
4677                        }
4678
4679                        performedDexOpt = true;
4680                    }
4681
4682                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4683                    // paths and instruction sets. We'll deal with them all together when we process
4684                    // our list of deferred dexopts.
4685                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4686                        if (mDeferredDexOpt == null) {
4687                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4688                        }
4689                        mDeferredDexOpt.add(pkg);
4690                        return DEX_OPT_DEFERRED;
4691                    }
4692                } catch (FileNotFoundException e) {
4693                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4694                    return DEX_OPT_FAILED;
4695                } catch (IOException e) {
4696                    Slog.w(TAG, "IOException reading apk: " + path, e);
4697                    return DEX_OPT_FAILED;
4698                } catch (StaleDexCacheError e) {
4699                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4700                    return DEX_OPT_FAILED;
4701                } catch (Exception e) {
4702                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4703                    return DEX_OPT_FAILED;
4704                }
4705            }
4706
4707            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4708            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4709            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4710            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4711            // it.
4712            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4713        }
4714
4715        // If we've gotten here, we're sure that no error occurred and that we haven't
4716        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4717        // we've skipped all of them because they are up to date. In both cases this
4718        // package doesn't need dexopt any longer.
4719        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4720    }
4721
4722    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4723        if (info.primaryCpuAbi != null) {
4724            if (info.secondaryCpuAbi != null) {
4725                return new String[] {
4726                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4727                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4728            } else {
4729                return new String[] {
4730                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4731            }
4732        }
4733
4734        return new String[] { getPreferredInstructionSet() };
4735    }
4736
4737    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4738        if (ps.primaryCpuAbiString != null) {
4739            if (ps.secondaryCpuAbiString != null) {
4740                return new String[] {
4741                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4742                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4743            } else {
4744                return new String[] {
4745                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4746            }
4747        }
4748
4749        return new String[] { getPreferredInstructionSet() };
4750    }
4751
4752    private static String getPreferredInstructionSet() {
4753        if (sPreferredInstructionSet == null) {
4754            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4755        }
4756
4757        return sPreferredInstructionSet;
4758    }
4759
4760    private static List<String> getAllInstructionSets() {
4761        final String[] allAbis = Build.SUPPORTED_ABIS;
4762        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4763
4764        for (String abi : allAbis) {
4765            final String instructionSet = VMRuntime.getInstructionSet(abi);
4766            if (!allInstructionSets.contains(instructionSet)) {
4767                allInstructionSets.add(instructionSet);
4768            }
4769        }
4770
4771        return allInstructionSets;
4772    }
4773
4774    /**
4775     * Returns the instruction set that should be used to compile dex code. In the presence of
4776     * a native bridge this might be different than the one shared libraries use.
4777     */
4778    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4779        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4780        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4781    }
4782
4783    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4784        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4785        for (String instructionSet : instructionSets) {
4786            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4787        }
4788        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4789    }
4790
4791    /**
4792     * Returns deduplicated list of supported instructions for dex code.
4793     */
4794    public static String[] getAllDexCodeInstructionSets() {
4795        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4796        for (int i = 0; i < supportedInstructionSets.length; i++) {
4797            String abi = Build.SUPPORTED_ABIS[i];
4798            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4799        }
4800        return getDexCodeInstructionSets(supportedInstructionSets);
4801    }
4802
4803    @Override
4804    public void forceDexOpt(String packageName) {
4805        enforceSystemOrRoot("forceDexOpt");
4806
4807        PackageParser.Package pkg;
4808        synchronized (mPackages) {
4809            pkg = mPackages.get(packageName);
4810            if (pkg == null) {
4811                throw new IllegalArgumentException("Missing package: " + packageName);
4812            }
4813        }
4814
4815        synchronized (mInstallLock) {
4816            final String[] instructionSets = new String[] {
4817                    getPrimaryInstructionSet(pkg.applicationInfo) };
4818            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4819            if (res != DEX_OPT_PERFORMED) {
4820                throw new IllegalStateException("Failed to dexopt: " + res);
4821            }
4822        }
4823    }
4824
4825    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4826                                boolean forceDex, boolean defer, boolean inclDependencies) {
4827        HashSet<String> done;
4828        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4829            done = new HashSet<String>();
4830            done.add(pkg.packageName);
4831        } else {
4832            done = null;
4833        }
4834        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4835    }
4836
4837    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4838        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4839            Slog.w(TAG, "Unable to update from " + oldPkg.name
4840                    + " to " + newPkg.packageName
4841                    + ": old package not in system partition");
4842            return false;
4843        } else if (mPackages.get(oldPkg.name) != null) {
4844            Slog.w(TAG, "Unable to update from " + oldPkg.name
4845                    + " to " + newPkg.packageName
4846                    + ": old package still exists");
4847            return false;
4848        }
4849        return true;
4850    }
4851
4852    File getDataPathForUser(int userId) {
4853        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4854    }
4855
4856    private File getDataPathForPackage(String packageName, int userId) {
4857        /*
4858         * Until we fully support multiple users, return the directory we
4859         * previously would have. The PackageManagerTests will need to be
4860         * revised when this is changed back..
4861         */
4862        if (userId == 0) {
4863            return new File(mAppDataDir, packageName);
4864        } else {
4865            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4866                + File.separator + packageName);
4867        }
4868    }
4869
4870    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4871        int[] users = sUserManager.getUserIds();
4872        int res = mInstaller.install(packageName, uid, uid, seinfo);
4873        if (res < 0) {
4874            return res;
4875        }
4876        for (int user : users) {
4877            if (user != 0) {
4878                res = mInstaller.createUserData(packageName,
4879                        UserHandle.getUid(user, uid), user, seinfo);
4880                if (res < 0) {
4881                    return res;
4882                }
4883            }
4884        }
4885        return res;
4886    }
4887
4888    private int removeDataDirsLI(String packageName) {
4889        int[] users = sUserManager.getUserIds();
4890        int res = 0;
4891        for (int user : users) {
4892            int resInner = mInstaller.remove(packageName, user);
4893            if (resInner < 0) {
4894                res = resInner;
4895            }
4896        }
4897
4898        return res;
4899    }
4900
4901    private int deleteCodeCacheDirsLI(String packageName) {
4902        int[] users = sUserManager.getUserIds();
4903        int res = 0;
4904        for (int user : users) {
4905            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4906            if (resInner < 0) {
4907                res = resInner;
4908            }
4909        }
4910        return res;
4911    }
4912
4913    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4914            PackageParser.Package changingLib) {
4915        if (file.path != null) {
4916            usesLibraryFiles.add(file.path);
4917            return;
4918        }
4919        PackageParser.Package p = mPackages.get(file.apk);
4920        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4921            // If we are doing this while in the middle of updating a library apk,
4922            // then we need to make sure to use that new apk for determining the
4923            // dependencies here.  (We haven't yet finished committing the new apk
4924            // to the package manager state.)
4925            if (p == null || p.packageName.equals(changingLib.packageName)) {
4926                p = changingLib;
4927            }
4928        }
4929        if (p != null) {
4930            usesLibraryFiles.addAll(p.getAllCodePaths());
4931        }
4932    }
4933
4934    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4935            PackageParser.Package changingLib) throws PackageManagerException {
4936        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4937            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4938            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4939            for (int i=0; i<N; i++) {
4940                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4941                if (file == null) {
4942                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4943                            "Package " + pkg.packageName + " requires unavailable shared library "
4944                            + pkg.usesLibraries.get(i) + "; failing!");
4945                }
4946                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4947            }
4948            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4949            for (int i=0; i<N; i++) {
4950                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4951                if (file == null) {
4952                    Slog.w(TAG, "Package " + pkg.packageName
4953                            + " desires unavailable shared library "
4954                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4955                } else {
4956                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4957                }
4958            }
4959            N = usesLibraryFiles.size();
4960            if (N > 0) {
4961                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4962            } else {
4963                pkg.usesLibraryFiles = null;
4964            }
4965        }
4966    }
4967
4968    private static boolean hasString(List<String> list, List<String> which) {
4969        if (list == null) {
4970            return false;
4971        }
4972        for (int i=list.size()-1; i>=0; i--) {
4973            for (int j=which.size()-1; j>=0; j--) {
4974                if (which.get(j).equals(list.get(i))) {
4975                    return true;
4976                }
4977            }
4978        }
4979        return false;
4980    }
4981
4982    private void updateAllSharedLibrariesLPw() {
4983        for (PackageParser.Package pkg : mPackages.values()) {
4984            try {
4985                updateSharedLibrariesLPw(pkg, null);
4986            } catch (PackageManagerException e) {
4987                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4988            }
4989        }
4990    }
4991
4992    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4993            PackageParser.Package changingPkg) {
4994        ArrayList<PackageParser.Package> res = null;
4995        for (PackageParser.Package pkg : mPackages.values()) {
4996            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4997                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4998                if (res == null) {
4999                    res = new ArrayList<PackageParser.Package>();
5000                }
5001                res.add(pkg);
5002                try {
5003                    updateSharedLibrariesLPw(pkg, changingPkg);
5004                } catch (PackageManagerException e) {
5005                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5006                }
5007            }
5008        }
5009        return res;
5010    }
5011
5012    /**
5013     * Derive the value of the {@code cpuAbiOverride} based on the provided
5014     * value and an optional stored value from the package settings.
5015     */
5016    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5017        String cpuAbiOverride = null;
5018
5019        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5020            cpuAbiOverride = null;
5021        } else if (abiOverride != null) {
5022            cpuAbiOverride = abiOverride;
5023        } else if (settings != null) {
5024            cpuAbiOverride = settings.cpuAbiOverrideString;
5025        }
5026
5027        return cpuAbiOverride;
5028    }
5029
5030    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5031            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5032        boolean success = false;
5033        try {
5034            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5035                    currentTime, user);
5036            success = true;
5037            return res;
5038        } finally {
5039            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5040                removeDataDirsLI(pkg.packageName);
5041            }
5042        }
5043    }
5044
5045    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5046            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5047        final File scanFile = new File(pkg.codePath);
5048        if (pkg.applicationInfo.getCodePath() == null ||
5049                pkg.applicationInfo.getResourcePath() == null) {
5050            // Bail out. The resource and code paths haven't been set.
5051            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5052                    "Code and resource paths haven't been set correctly");
5053        }
5054
5055        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5056            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5057        }
5058
5059        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5060            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5061        }
5062
5063        if (mCustomResolverComponentName != null &&
5064                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5065            setUpCustomResolverActivity(pkg);
5066        }
5067
5068        if (pkg.packageName.equals("android")) {
5069            synchronized (mPackages) {
5070                if (mAndroidApplication != null) {
5071                    Slog.w(TAG, "*************************************************");
5072                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5073                    Slog.w(TAG, " file=" + scanFile);
5074                    Slog.w(TAG, "*************************************************");
5075                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5076                            "Core android package being redefined.  Skipping.");
5077                }
5078
5079                // Set up information for our fall-back user intent resolution activity.
5080                mPlatformPackage = pkg;
5081                pkg.mVersionCode = mSdkVersion;
5082                mAndroidApplication = pkg.applicationInfo;
5083
5084                if (!mResolverReplaced) {
5085                    mResolveActivity.applicationInfo = mAndroidApplication;
5086                    mResolveActivity.name = ResolverActivity.class.getName();
5087                    mResolveActivity.packageName = mAndroidApplication.packageName;
5088                    mResolveActivity.processName = "system:ui";
5089                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5090                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5091                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5092                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5093                    mResolveActivity.exported = true;
5094                    mResolveActivity.enabled = true;
5095                    mResolveInfo.activityInfo = mResolveActivity;
5096                    mResolveInfo.priority = 0;
5097                    mResolveInfo.preferredOrder = 0;
5098                    mResolveInfo.match = 0;
5099                    mResolveComponentName = new ComponentName(
5100                            mAndroidApplication.packageName, mResolveActivity.name);
5101                }
5102            }
5103        }
5104
5105        if (DEBUG_PACKAGE_SCANNING) {
5106            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5107                Log.d(TAG, "Scanning package " + pkg.packageName);
5108        }
5109
5110        if (mPackages.containsKey(pkg.packageName)
5111                || mSharedLibraries.containsKey(pkg.packageName)) {
5112            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5113                    "Application package " + pkg.packageName
5114                    + " already installed.  Skipping duplicate.");
5115        }
5116
5117        // Initialize package source and resource directories
5118        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5119        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5120
5121        SharedUserSetting suid = null;
5122        PackageSetting pkgSetting = null;
5123
5124        if (!isSystemApp(pkg)) {
5125            // Only system apps can use these features.
5126            pkg.mOriginalPackages = null;
5127            pkg.mRealPackage = null;
5128            pkg.mAdoptPermissions = null;
5129        }
5130
5131        // writer
5132        synchronized (mPackages) {
5133            if (pkg.mSharedUserId != null) {
5134                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5135                if (suid == null) {
5136                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5137                            "Creating application package " + pkg.packageName
5138                            + " for shared user failed");
5139                }
5140                if (DEBUG_PACKAGE_SCANNING) {
5141                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5142                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5143                                + "): packages=" + suid.packages);
5144                }
5145            }
5146
5147            // Check if we are renaming from an original package name.
5148            PackageSetting origPackage = null;
5149            String realName = null;
5150            if (pkg.mOriginalPackages != null) {
5151                // This package may need to be renamed to a previously
5152                // installed name.  Let's check on that...
5153                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5154                if (pkg.mOriginalPackages.contains(renamed)) {
5155                    // This package had originally been installed as the
5156                    // original name, and we have already taken care of
5157                    // transitioning to the new one.  Just update the new
5158                    // one to continue using the old name.
5159                    realName = pkg.mRealPackage;
5160                    if (!pkg.packageName.equals(renamed)) {
5161                        // Callers into this function may have already taken
5162                        // care of renaming the package; only do it here if
5163                        // it is not already done.
5164                        pkg.setPackageName(renamed);
5165                    }
5166
5167                } else {
5168                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5169                        if ((origPackage = mSettings.peekPackageLPr(
5170                                pkg.mOriginalPackages.get(i))) != null) {
5171                            // We do have the package already installed under its
5172                            // original name...  should we use it?
5173                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5174                                // New package is not compatible with original.
5175                                origPackage = null;
5176                                continue;
5177                            } else if (origPackage.sharedUser != null) {
5178                                // Make sure uid is compatible between packages.
5179                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5180                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5181                                            + " to " + pkg.packageName + ": old uid "
5182                                            + origPackage.sharedUser.name
5183                                            + " differs from " + pkg.mSharedUserId);
5184                                    origPackage = null;
5185                                    continue;
5186                                }
5187                            } else {
5188                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5189                                        + pkg.packageName + " to old name " + origPackage.name);
5190                            }
5191                            break;
5192                        }
5193                    }
5194                }
5195            }
5196
5197            if (mTransferedPackages.contains(pkg.packageName)) {
5198                Slog.w(TAG, "Package " + pkg.packageName
5199                        + " was transferred to another, but its .apk remains");
5200            }
5201
5202            // Just create the setting, don't add it yet. For already existing packages
5203            // the PkgSetting exists already and doesn't have to be created.
5204            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5205                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5206                    pkg.applicationInfo.primaryCpuAbi,
5207                    pkg.applicationInfo.secondaryCpuAbi,
5208                    pkg.applicationInfo.flags, user, false);
5209            if (pkgSetting == null) {
5210                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5211                        "Creating application package " + pkg.packageName + " failed");
5212            }
5213
5214            if (pkgSetting.origPackage != null) {
5215                // If we are first transitioning from an original package,
5216                // fix up the new package's name now.  We need to do this after
5217                // looking up the package under its new name, so getPackageLP
5218                // can take care of fiddling things correctly.
5219                pkg.setPackageName(origPackage.name);
5220
5221                // File a report about this.
5222                String msg = "New package " + pkgSetting.realName
5223                        + " renamed to replace old package " + pkgSetting.name;
5224                reportSettingsProblem(Log.WARN, msg);
5225
5226                // Make a note of it.
5227                mTransferedPackages.add(origPackage.name);
5228
5229                // No longer need to retain this.
5230                pkgSetting.origPackage = null;
5231            }
5232
5233            if (realName != null) {
5234                // Make a note of it.
5235                mTransferedPackages.add(pkg.packageName);
5236            }
5237
5238            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5239                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5240            }
5241
5242            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5243                // Check all shared libraries and map to their actual file path.
5244                // We only do this here for apps not on a system dir, because those
5245                // are the only ones that can fail an install due to this.  We
5246                // will take care of the system apps by updating all of their
5247                // library paths after the scan is done.
5248                updateSharedLibrariesLPw(pkg, null);
5249            }
5250
5251            if (mFoundPolicyFile) {
5252                SELinuxMMAC.assignSeinfoValue(pkg);
5253            }
5254
5255            pkg.applicationInfo.uid = pkgSetting.appId;
5256            pkg.mExtras = pkgSetting;
5257            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5258                try {
5259                    verifySignaturesLP(pkgSetting, pkg);
5260                } catch (PackageManagerException e) {
5261                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5262                        throw e;
5263                    }
5264                    // The signature has changed, but this package is in the system
5265                    // image...  let's recover!
5266                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5267                    // However...  if this package is part of a shared user, but it
5268                    // doesn't match the signature of the shared user, let's fail.
5269                    // What this means is that you can't change the signatures
5270                    // associated with an overall shared user, which doesn't seem all
5271                    // that unreasonable.
5272                    if (pkgSetting.sharedUser != null) {
5273                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5274                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5275                            throw new PackageManagerException(
5276                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5277                                            "Signature mismatch for shared user : "
5278                                            + pkgSetting.sharedUser);
5279                        }
5280                    }
5281                    // File a report about this.
5282                    String msg = "System package " + pkg.packageName
5283                        + " signature changed; retaining data.";
5284                    reportSettingsProblem(Log.WARN, msg);
5285                }
5286            } else {
5287                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5288                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5289                            + pkg.packageName + " upgrade keys do not match the "
5290                            + "previously installed version");
5291                } else {
5292                    // signatures may have changed as result of upgrade
5293                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5294                }
5295            }
5296            // Verify that this new package doesn't have any content providers
5297            // that conflict with existing packages.  Only do this if the
5298            // package isn't already installed, since we don't want to break
5299            // things that are installed.
5300            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5301                final int N = pkg.providers.size();
5302                int i;
5303                for (i=0; i<N; i++) {
5304                    PackageParser.Provider p = pkg.providers.get(i);
5305                    if (p.info.authority != null) {
5306                        String names[] = p.info.authority.split(";");
5307                        for (int j = 0; j < names.length; j++) {
5308                            if (mProvidersByAuthority.containsKey(names[j])) {
5309                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5310                                final String otherPackageName =
5311                                        ((other != null && other.getComponentName() != null) ?
5312                                                other.getComponentName().getPackageName() : "?");
5313                                throw new PackageManagerException(
5314                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5315                                                "Can't install because provider name " + names[j]
5316                                                + " (in package " + pkg.applicationInfo.packageName
5317                                                + ") is already used by " + otherPackageName);
5318                            }
5319                        }
5320                    }
5321                }
5322            }
5323
5324            if (pkg.mAdoptPermissions != null) {
5325                // This package wants to adopt ownership of permissions from
5326                // another package.
5327                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5328                    final String origName = pkg.mAdoptPermissions.get(i);
5329                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5330                    if (orig != null) {
5331                        if (verifyPackageUpdateLPr(orig, pkg)) {
5332                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5333                                    + pkg.packageName);
5334                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5335                        }
5336                    }
5337                }
5338            }
5339        }
5340
5341        final String pkgName = pkg.packageName;
5342
5343        final long scanFileTime = scanFile.lastModified();
5344        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5345        pkg.applicationInfo.processName = fixProcessName(
5346                pkg.applicationInfo.packageName,
5347                pkg.applicationInfo.processName,
5348                pkg.applicationInfo.uid);
5349
5350        File dataPath;
5351        if (mPlatformPackage == pkg) {
5352            // The system package is special.
5353            dataPath = new File(Environment.getDataDirectory(), "system");
5354
5355            pkg.applicationInfo.dataDir = dataPath.getPath();
5356
5357        } else {
5358            // This is a normal package, need to make its data directory.
5359            dataPath = getDataPathForPackage(pkg.packageName, 0);
5360
5361            boolean uidError = false;
5362            if (dataPath.exists()) {
5363                int currentUid = 0;
5364                try {
5365                    StructStat stat = Os.stat(dataPath.getPath());
5366                    currentUid = stat.st_uid;
5367                } catch (ErrnoException e) {
5368                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5369                }
5370
5371                // If we have mismatched owners for the data path, we have a problem.
5372                if (currentUid != pkg.applicationInfo.uid) {
5373                    boolean recovered = false;
5374                    if (currentUid == 0) {
5375                        // The directory somehow became owned by root.  Wow.
5376                        // This is probably because the system was stopped while
5377                        // installd was in the middle of messing with its libs
5378                        // directory.  Ask installd to fix that.
5379                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5380                                pkg.applicationInfo.uid);
5381                        if (ret >= 0) {
5382                            recovered = true;
5383                            String msg = "Package " + pkg.packageName
5384                                    + " unexpectedly changed to uid 0; recovered to " +
5385                                    + pkg.applicationInfo.uid;
5386                            reportSettingsProblem(Log.WARN, msg);
5387                        }
5388                    }
5389                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5390                            || (scanFlags&SCAN_BOOTING) != 0)) {
5391                        // If this is a system app, we can at least delete its
5392                        // current data so the application will still work.
5393                        int ret = removeDataDirsLI(pkgName);
5394                        if (ret >= 0) {
5395                            // TODO: Kill the processes first
5396                            // Old data gone!
5397                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5398                                    ? "System package " : "Third party package ";
5399                            String msg = prefix + pkg.packageName
5400                                    + " has changed from uid: "
5401                                    + currentUid + " to "
5402                                    + pkg.applicationInfo.uid + "; old data erased";
5403                            reportSettingsProblem(Log.WARN, msg);
5404                            recovered = true;
5405
5406                            // And now re-install the app.
5407                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5408                                                   pkg.applicationInfo.seinfo);
5409                            if (ret == -1) {
5410                                // Ack should not happen!
5411                                msg = prefix + pkg.packageName
5412                                        + " could not have data directory re-created after delete.";
5413                                reportSettingsProblem(Log.WARN, msg);
5414                                throw new PackageManagerException(
5415                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5416                            }
5417                        }
5418                        if (!recovered) {
5419                            mHasSystemUidErrors = true;
5420                        }
5421                    } else if (!recovered) {
5422                        // If we allow this install to proceed, we will be broken.
5423                        // Abort, abort!
5424                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5425                                "scanPackageLI");
5426                    }
5427                    if (!recovered) {
5428                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5429                            + pkg.applicationInfo.uid + "/fs_"
5430                            + currentUid;
5431                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5432                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5433                        String msg = "Package " + pkg.packageName
5434                                + " has mismatched uid: "
5435                                + currentUid + " on disk, "
5436                                + pkg.applicationInfo.uid + " in settings";
5437                        // writer
5438                        synchronized (mPackages) {
5439                            mSettings.mReadMessages.append(msg);
5440                            mSettings.mReadMessages.append('\n');
5441                            uidError = true;
5442                            if (!pkgSetting.uidError) {
5443                                reportSettingsProblem(Log.ERROR, msg);
5444                            }
5445                        }
5446                    }
5447                }
5448                pkg.applicationInfo.dataDir = dataPath.getPath();
5449                if (mShouldRestoreconData) {
5450                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5451                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5452                                pkg.applicationInfo.uid);
5453                }
5454            } else {
5455                if (DEBUG_PACKAGE_SCANNING) {
5456                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5457                        Log.v(TAG, "Want this data dir: " + dataPath);
5458                }
5459                //invoke installer to do the actual installation
5460                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5461                                           pkg.applicationInfo.seinfo);
5462                if (ret < 0) {
5463                    // Error from installer
5464                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5465                            "Unable to create data dirs [errorCode=" + ret + "]");
5466                }
5467
5468                if (dataPath.exists()) {
5469                    pkg.applicationInfo.dataDir = dataPath.getPath();
5470                } else {
5471                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5472                    pkg.applicationInfo.dataDir = null;
5473                }
5474            }
5475
5476            pkgSetting.uidError = uidError;
5477        }
5478
5479        final String path = scanFile.getPath();
5480        final String codePath = pkg.applicationInfo.getCodePath();
5481        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5482        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5483            setBundledAppAbisAndRoots(pkg, pkgSetting);
5484
5485            // If we haven't found any native libraries for the app, check if it has
5486            // renderscript code. We'll need to force the app to 32 bit if it has
5487            // renderscript bitcode.
5488            if (pkg.applicationInfo.primaryCpuAbi == null
5489                    && pkg.applicationInfo.secondaryCpuAbi == null
5490                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5491                NativeLibraryHelper.Handle handle = null;
5492                try {
5493                    handle = NativeLibraryHelper.Handle.create(scanFile);
5494                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5495                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5496                    }
5497                } catch (IOException ioe) {
5498                    Slog.w(TAG, "Error scanning system app : " + ioe);
5499                } finally {
5500                    IoUtils.closeQuietly(handle);
5501                }
5502            }
5503
5504            setNativeLibraryPaths(pkg);
5505        } else {
5506            // TODO: We can probably be smarter about this stuff. For installed apps,
5507            // we can calculate this information at install time once and for all. For
5508            // system apps, we can probably assume that this information doesn't change
5509            // after the first boot scan. As things stand, we do lots of unnecessary work.
5510
5511            // Give ourselves some initial paths; we'll come back for another
5512            // pass once we've determined ABI below.
5513            setNativeLibraryPaths(pkg);
5514
5515            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5516            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5517            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5518
5519            NativeLibraryHelper.Handle handle = null;
5520            try {
5521                handle = NativeLibraryHelper.Handle.create(scanFile);
5522                // TODO(multiArch): This can be null for apps that didn't go through the
5523                // usual installation process. We can calculate it again, like we
5524                // do during install time.
5525                //
5526                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5527                // unnecessary.
5528                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5529
5530                // Null out the abis so that they can be recalculated.
5531                pkg.applicationInfo.primaryCpuAbi = null;
5532                pkg.applicationInfo.secondaryCpuAbi = null;
5533                if (isMultiArch(pkg.applicationInfo)) {
5534                    // Warn if we've set an abiOverride for multi-lib packages..
5535                    // By definition, we need to copy both 32 and 64 bit libraries for
5536                    // such packages.
5537                    if (pkg.cpuAbiOverride != null
5538                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5539                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5540                    }
5541
5542                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5543                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5544                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5545                        if (isAsec) {
5546                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5547                        } else {
5548                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5549                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5550                                    useIsaSpecificSubdirs);
5551                        }
5552                    }
5553
5554                    maybeThrowExceptionForMultiArchCopy(
5555                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5556
5557                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5558                        if (isAsec) {
5559                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5560                        } else {
5561                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5562                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5563                                    useIsaSpecificSubdirs);
5564                        }
5565                    }
5566
5567                    maybeThrowExceptionForMultiArchCopy(
5568                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5569
5570                    if (abi64 >= 0) {
5571                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5572                    }
5573
5574                    if (abi32 >= 0) {
5575                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5576                        if (abi64 >= 0) {
5577                            pkg.applicationInfo.secondaryCpuAbi = abi;
5578                        } else {
5579                            pkg.applicationInfo.primaryCpuAbi = abi;
5580                        }
5581                    }
5582                } else {
5583                    String[] abiList = (cpuAbiOverride != null) ?
5584                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5585
5586                    // Enable gross and lame hacks for apps that are built with old
5587                    // SDK tools. We must scan their APKs for renderscript bitcode and
5588                    // not launch them if it's present. Don't bother checking on devices
5589                    // that don't have 64 bit support.
5590                    boolean needsRenderScriptOverride = false;
5591                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5592                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5593                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5594                        needsRenderScriptOverride = true;
5595                    }
5596
5597                    final int copyRet;
5598                    if (isAsec) {
5599                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5600                    } else {
5601                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5602                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5603                    }
5604
5605                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5606                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5607                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5608                    }
5609
5610                    if (copyRet >= 0) {
5611                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5612                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5613                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5614                    } else if (needsRenderScriptOverride) {
5615                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5616                    }
5617                }
5618            } catch (IOException ioe) {
5619                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5620            } finally {
5621                IoUtils.closeQuietly(handle);
5622            }
5623
5624            // Now that we've calculated the ABIs and determined if it's an internal app,
5625            // we will go ahead and populate the nativeLibraryPath.
5626            setNativeLibraryPaths(pkg);
5627
5628            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5629            final int[] userIds = sUserManager.getUserIds();
5630            synchronized (mInstallLock) {
5631                // Create a native library symlink only if we have native libraries
5632                // and if the native libraries are 32 bit libraries. We do not provide
5633                // this symlink for 64 bit libraries.
5634                if (pkg.applicationInfo.primaryCpuAbi != null &&
5635                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5636                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5637                    for (int userId : userIds) {
5638                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5639                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5640                                    "Failed linking native library dir (user=" + userId + ")");
5641                        }
5642                    }
5643                }
5644            }
5645        }
5646
5647        // This is a special case for the "system" package, where the ABI is
5648        // dictated by the zygote configuration (and init.rc). We should keep track
5649        // of this ABI so that we can deal with "normal" applications that run under
5650        // the same UID correctly.
5651        if (mPlatformPackage == pkg) {
5652            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5653                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5654        }
5655
5656        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5657        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5658        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5659        // Copy the derived override back to the parsed package, so that we can
5660        // update the package settings accordingly.
5661        pkg.cpuAbiOverride = cpuAbiOverride;
5662
5663        if (DEBUG_ABI_SELECTION) {
5664            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5665                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5666                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5667        }
5668
5669        // Push the derived path down into PackageSettings so we know what to
5670        // clean up at uninstall time.
5671        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5672
5673        if (DEBUG_ABI_SELECTION) {
5674            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5675                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5676                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5677        }
5678
5679        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5680            // We don't do this here during boot because we can do it all
5681            // at once after scanning all existing packages.
5682            //
5683            // We also do this *before* we perform dexopt on this package, so that
5684            // we can avoid redundant dexopts, and also to make sure we've got the
5685            // code and package path correct.
5686            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5687                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5688        }
5689
5690        if ((scanFlags & SCAN_NO_DEX) == 0) {
5691            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5692                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5693                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5694            }
5695        }
5696
5697        if (mFactoryTest && pkg.requestedPermissions.contains(
5698                android.Manifest.permission.FACTORY_TEST)) {
5699            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5700        }
5701
5702        ArrayList<PackageParser.Package> clientLibPkgs = null;
5703
5704        // writer
5705        synchronized (mPackages) {
5706            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5707                // Only system apps can add new shared libraries.
5708                if (pkg.libraryNames != null) {
5709                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5710                        String name = pkg.libraryNames.get(i);
5711                        boolean allowed = false;
5712                        if (isUpdatedSystemApp(pkg)) {
5713                            // New library entries can only be added through the
5714                            // system image.  This is important to get rid of a lot
5715                            // of nasty edge cases: for example if we allowed a non-
5716                            // system update of the app to add a library, then uninstalling
5717                            // the update would make the library go away, and assumptions
5718                            // we made such as through app install filtering would now
5719                            // have allowed apps on the device which aren't compatible
5720                            // with it.  Better to just have the restriction here, be
5721                            // conservative, and create many fewer cases that can negatively
5722                            // impact the user experience.
5723                            final PackageSetting sysPs = mSettings
5724                                    .getDisabledSystemPkgLPr(pkg.packageName);
5725                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5726                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5727                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5728                                        allowed = true;
5729                                        allowed = true;
5730                                        break;
5731                                    }
5732                                }
5733                            }
5734                        } else {
5735                            allowed = true;
5736                        }
5737                        if (allowed) {
5738                            if (!mSharedLibraries.containsKey(name)) {
5739                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5740                            } else if (!name.equals(pkg.packageName)) {
5741                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5742                                        + name + " already exists; skipping");
5743                            }
5744                        } else {
5745                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5746                                    + name + " that is not declared on system image; skipping");
5747                        }
5748                    }
5749                    if ((scanFlags&SCAN_BOOTING) == 0) {
5750                        // If we are not booting, we need to update any applications
5751                        // that are clients of our shared library.  If we are booting,
5752                        // this will all be done once the scan is complete.
5753                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5754                    }
5755                }
5756            }
5757        }
5758
5759        // We also need to dexopt any apps that are dependent on this library.  Note that
5760        // if these fail, we should abort the install since installing the library will
5761        // result in some apps being broken.
5762        if (clientLibPkgs != null) {
5763            if ((scanFlags & SCAN_NO_DEX) == 0) {
5764                for (int i = 0; i < clientLibPkgs.size(); i++) {
5765                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5766                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5767                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5768                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5769                                "scanPackageLI failed to dexopt clientLibPkgs");
5770                    }
5771                }
5772            }
5773        }
5774
5775        // Request the ActivityManager to kill the process(only for existing packages)
5776        // so that we do not end up in a confused state while the user is still using the older
5777        // version of the application while the new one gets installed.
5778        if ((scanFlags & SCAN_REPLACING) != 0) {
5779            killApplication(pkg.applicationInfo.packageName,
5780                        pkg.applicationInfo.uid, "update pkg");
5781        }
5782
5783        // Also need to kill any apps that are dependent on the library.
5784        if (clientLibPkgs != null) {
5785            for (int i=0; i<clientLibPkgs.size(); i++) {
5786                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5787                killApplication(clientPkg.applicationInfo.packageName,
5788                        clientPkg.applicationInfo.uid, "update lib");
5789            }
5790        }
5791
5792        // writer
5793        synchronized (mPackages) {
5794            // We don't expect installation to fail beyond this point
5795
5796            // Add the new setting to mSettings
5797            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5798            // Add the new setting to mPackages
5799            mPackages.put(pkg.applicationInfo.packageName, pkg);
5800            // Make sure we don't accidentally delete its data.
5801            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5802            while (iter.hasNext()) {
5803                PackageCleanItem item = iter.next();
5804                if (pkgName.equals(item.packageName)) {
5805                    iter.remove();
5806                }
5807            }
5808
5809            // Take care of first install / last update times.
5810            if (currentTime != 0) {
5811                if (pkgSetting.firstInstallTime == 0) {
5812                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5813                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5814                    pkgSetting.lastUpdateTime = currentTime;
5815                }
5816            } else if (pkgSetting.firstInstallTime == 0) {
5817                // We need *something*.  Take time time stamp of the file.
5818                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5819            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5820                if (scanFileTime != pkgSetting.timeStamp) {
5821                    // A package on the system image has changed; consider this
5822                    // to be an update.
5823                    pkgSetting.lastUpdateTime = scanFileTime;
5824                }
5825            }
5826
5827            // Add the package's KeySets to the global KeySetManagerService
5828            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5829            try {
5830                // Old KeySetData no longer valid.
5831                ksms.removeAppKeySetDataLPw(pkg.packageName);
5832                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5833                if (pkg.mKeySetMapping != null) {
5834                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5835                            pkg.mKeySetMapping.entrySet()) {
5836                        if (entry.getValue() != null) {
5837                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5838                                                          entry.getValue(), entry.getKey());
5839                        }
5840                    }
5841                    if (pkg.mUpgradeKeySets != null) {
5842                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5843                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5844                        }
5845                    }
5846                }
5847            } catch (NullPointerException e) {
5848                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5849            } catch (IllegalArgumentException e) {
5850                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5851            }
5852
5853            int N = pkg.providers.size();
5854            StringBuilder r = null;
5855            int i;
5856            for (i=0; i<N; i++) {
5857                PackageParser.Provider p = pkg.providers.get(i);
5858                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5859                        p.info.processName, pkg.applicationInfo.uid);
5860                mProviders.addProvider(p);
5861                p.syncable = p.info.isSyncable;
5862                if (p.info.authority != null) {
5863                    String names[] = p.info.authority.split(";");
5864                    p.info.authority = null;
5865                    for (int j = 0; j < names.length; j++) {
5866                        if (j == 1 && p.syncable) {
5867                            // We only want the first authority for a provider to possibly be
5868                            // syncable, so if we already added this provider using a different
5869                            // authority clear the syncable flag. We copy the provider before
5870                            // changing it because the mProviders object contains a reference
5871                            // to a provider that we don't want to change.
5872                            // Only do this for the second authority since the resulting provider
5873                            // object can be the same for all future authorities for this provider.
5874                            p = new PackageParser.Provider(p);
5875                            p.syncable = false;
5876                        }
5877                        if (!mProvidersByAuthority.containsKey(names[j])) {
5878                            mProvidersByAuthority.put(names[j], p);
5879                            if (p.info.authority == null) {
5880                                p.info.authority = names[j];
5881                            } else {
5882                                p.info.authority = p.info.authority + ";" + names[j];
5883                            }
5884                            if (DEBUG_PACKAGE_SCANNING) {
5885                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5886                                    Log.d(TAG, "Registered content provider: " + names[j]
5887                                            + ", className = " + p.info.name + ", isSyncable = "
5888                                            + p.info.isSyncable);
5889                            }
5890                        } else {
5891                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5892                            Slog.w(TAG, "Skipping provider name " + names[j] +
5893                                    " (in package " + pkg.applicationInfo.packageName +
5894                                    "): name already used by "
5895                                    + ((other != null && other.getComponentName() != null)
5896                                            ? other.getComponentName().getPackageName() : "?"));
5897                        }
5898                    }
5899                }
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(p.info.name);
5907                }
5908            }
5909            if (r != null) {
5910                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5911            }
5912
5913            N = pkg.services.size();
5914            r = null;
5915            for (i=0; i<N; i++) {
5916                PackageParser.Service s = pkg.services.get(i);
5917                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5918                        s.info.processName, pkg.applicationInfo.uid);
5919                mServices.addService(s);
5920                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5921                    if (r == null) {
5922                        r = new StringBuilder(256);
5923                    } else {
5924                        r.append(' ');
5925                    }
5926                    r.append(s.info.name);
5927                }
5928            }
5929            if (r != null) {
5930                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5931            }
5932
5933            N = pkg.receivers.size();
5934            r = null;
5935            for (i=0; i<N; i++) {
5936                PackageParser.Activity a = pkg.receivers.get(i);
5937                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5938                        a.info.processName, pkg.applicationInfo.uid);
5939                mReceivers.addActivity(a, "receiver");
5940                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5941                    if (r == null) {
5942                        r = new StringBuilder(256);
5943                    } else {
5944                        r.append(' ');
5945                    }
5946                    r.append(a.info.name);
5947                }
5948            }
5949            if (r != null) {
5950                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5951            }
5952
5953            N = pkg.activities.size();
5954            r = null;
5955            for (i=0; i<N; i++) {
5956                PackageParser.Activity a = pkg.activities.get(i);
5957                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5958                        a.info.processName, pkg.applicationInfo.uid);
5959                mActivities.addActivity(a, "activity");
5960                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5961                    if (r == null) {
5962                        r = new StringBuilder(256);
5963                    } else {
5964                        r.append(' ');
5965                    }
5966                    r.append(a.info.name);
5967                }
5968            }
5969            if (r != null) {
5970                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5971            }
5972
5973            N = pkg.permissionGroups.size();
5974            r = null;
5975            for (i=0; i<N; i++) {
5976                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5977                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5978                if (cur == null) {
5979                    mPermissionGroups.put(pg.info.name, pg);
5980                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5981                        if (r == null) {
5982                            r = new StringBuilder(256);
5983                        } else {
5984                            r.append(' ');
5985                        }
5986                        r.append(pg.info.name);
5987                    }
5988                } else {
5989                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5990                            + pg.info.packageName + " ignored: original from "
5991                            + cur.info.packageName);
5992                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5993                        if (r == null) {
5994                            r = new StringBuilder(256);
5995                        } else {
5996                            r.append(' ');
5997                        }
5998                        r.append("DUP:");
5999                        r.append(pg.info.name);
6000                    }
6001                }
6002            }
6003            if (r != null) {
6004                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6005            }
6006
6007            N = pkg.permissions.size();
6008            r = null;
6009            for (i=0; i<N; i++) {
6010                PackageParser.Permission p = pkg.permissions.get(i);
6011                HashMap<String, BasePermission> permissionMap =
6012                        p.tree ? mSettings.mPermissionTrees
6013                        : mSettings.mPermissions;
6014                p.group = mPermissionGroups.get(p.info.group);
6015                if (p.info.group == null || p.group != null) {
6016                    BasePermission bp = permissionMap.get(p.info.name);
6017
6018                    // Allow system apps to redefine non-system permissions
6019                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6020                        final boolean currentOwnerIsSystem = (bp.perm != null
6021                                && isSystemApp(bp.perm.owner));
6022                        if (isSystemApp(p.owner) && !currentOwnerIsSystem) {
6023                            String msg = "New decl " + p.owner + " of permission  "
6024                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6025                            reportSettingsProblem(Log.WARN, msg);
6026                            bp = null;
6027                        }
6028                    }
6029
6030                    if (bp == null) {
6031                        bp = new BasePermission(p.info.name, p.info.packageName,
6032                                BasePermission.TYPE_NORMAL);
6033                        permissionMap.put(p.info.name, bp);
6034                    }
6035
6036                    if (bp.perm == null) {
6037                        if (bp.sourcePackage == null
6038                                || bp.sourcePackage.equals(p.info.packageName)) {
6039                            BasePermission tree = findPermissionTreeLP(p.info.name);
6040                            if (tree == null
6041                                    || tree.sourcePackage.equals(p.info.packageName)) {
6042                                bp.packageSetting = pkgSetting;
6043                                bp.perm = p;
6044                                bp.uid = pkg.applicationInfo.uid;
6045                                bp.sourcePackage = p.info.packageName;
6046                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6047                                    if (r == null) {
6048                                        r = new StringBuilder(256);
6049                                    } else {
6050                                        r.append(' ');
6051                                    }
6052                                    r.append(p.info.name);
6053                                }
6054                            } else {
6055                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6056                                        + p.info.packageName + " ignored: base tree "
6057                                        + tree.name + " is from package "
6058                                        + tree.sourcePackage);
6059                            }
6060                        } else {
6061                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6062                                    + p.info.packageName + " ignored: original from "
6063                                    + bp.sourcePackage);
6064                        }
6065                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6066                        if (r == null) {
6067                            r = new StringBuilder(256);
6068                        } else {
6069                            r.append(' ');
6070                        }
6071                        r.append("DUP:");
6072                        r.append(p.info.name);
6073                    }
6074                    if (bp.perm == p) {
6075                        bp.protectionLevel = p.info.protectionLevel;
6076                    }
6077                } else {
6078                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6079                            + p.info.packageName + " ignored: no group "
6080                            + p.group);
6081                }
6082            }
6083            if (r != null) {
6084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6085            }
6086
6087            N = pkg.instrumentation.size();
6088            r = null;
6089            for (i=0; i<N; i++) {
6090                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6091                a.info.packageName = pkg.applicationInfo.packageName;
6092                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6093                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6094                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6095                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6096                a.info.dataDir = pkg.applicationInfo.dataDir;
6097
6098                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6099                // need other information about the application, like the ABI and what not ?
6100                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6101                mInstrumentation.put(a.getComponentName(), a);
6102                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6103                    if (r == null) {
6104                        r = new StringBuilder(256);
6105                    } else {
6106                        r.append(' ');
6107                    }
6108                    r.append(a.info.name);
6109                }
6110            }
6111            if (r != null) {
6112                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6113            }
6114
6115            if (pkg.protectedBroadcasts != null) {
6116                N = pkg.protectedBroadcasts.size();
6117                for (i=0; i<N; i++) {
6118                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6119                }
6120            }
6121
6122            pkgSetting.setTimeStamp(scanFileTime);
6123
6124            // Create idmap files for pairs of (packages, overlay packages).
6125            // Note: "android", ie framework-res.apk, is handled by native layers.
6126            if (pkg.mOverlayTarget != null) {
6127                // This is an overlay package.
6128                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6129                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6130                        mOverlays.put(pkg.mOverlayTarget,
6131                                new HashMap<String, PackageParser.Package>());
6132                    }
6133                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6134                    map.put(pkg.packageName, pkg);
6135                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6136                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6137                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6138                                "scanPackageLI failed to createIdmap");
6139                    }
6140                }
6141            } else if (mOverlays.containsKey(pkg.packageName) &&
6142                    !pkg.packageName.equals("android")) {
6143                // This is a regular package, with one or more known overlay packages.
6144                createIdmapsForPackageLI(pkg);
6145            }
6146        }
6147
6148        return pkg;
6149    }
6150
6151    /**
6152     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6153     * i.e, so that all packages can be run inside a single process if required.
6154     *
6155     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6156     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6157     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6158     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6159     * updating a package that belongs to a shared user.
6160     *
6161     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6162     * adds unnecessary complexity.
6163     */
6164    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6165            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6166        String requiredInstructionSet = null;
6167        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6168            requiredInstructionSet = VMRuntime.getInstructionSet(
6169                     scannedPackage.applicationInfo.primaryCpuAbi);
6170        }
6171
6172        PackageSetting requirer = null;
6173        for (PackageSetting ps : packagesForUser) {
6174            // If packagesForUser contains scannedPackage, we skip it. This will happen
6175            // when scannedPackage is an update of an existing package. Without this check,
6176            // we will never be able to change the ABI of any package belonging to a shared
6177            // user, even if it's compatible with other packages.
6178            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6179                if (ps.primaryCpuAbiString == null) {
6180                    continue;
6181                }
6182
6183                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6184                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6185                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6186                    // this but there's not much we can do.
6187                    String errorMessage = "Instruction set mismatch, "
6188                            + ((requirer == null) ? "[caller]" : requirer)
6189                            + " requires " + requiredInstructionSet + " whereas " + ps
6190                            + " requires " + instructionSet;
6191                    Slog.w(TAG, errorMessage);
6192                }
6193
6194                if (requiredInstructionSet == null) {
6195                    requiredInstructionSet = instructionSet;
6196                    requirer = ps;
6197                }
6198            }
6199        }
6200
6201        if (requiredInstructionSet != null) {
6202            String adjustedAbi;
6203            if (requirer != null) {
6204                // requirer != null implies that either scannedPackage was null or that scannedPackage
6205                // did not require an ABI, in which case we have to adjust scannedPackage to match
6206                // the ABI of the set (which is the same as requirer's ABI)
6207                adjustedAbi = requirer.primaryCpuAbiString;
6208                if (scannedPackage != null) {
6209                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6210                }
6211            } else {
6212                // requirer == null implies that we're updating all ABIs in the set to
6213                // match scannedPackage.
6214                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6215            }
6216
6217            for (PackageSetting ps : packagesForUser) {
6218                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6219                    if (ps.primaryCpuAbiString != null) {
6220                        continue;
6221                    }
6222
6223                    ps.primaryCpuAbiString = adjustedAbi;
6224                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6225                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6226                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6227
6228                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6229                                deferDexOpt, true) == DEX_OPT_FAILED) {
6230                            ps.primaryCpuAbiString = null;
6231                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6232                            return;
6233                        } else {
6234                            mInstaller.rmdex(ps.codePathString,
6235                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6236                        }
6237                    }
6238                }
6239            }
6240        }
6241    }
6242
6243    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6244        synchronized (mPackages) {
6245            mResolverReplaced = true;
6246            // Set up information for custom user intent resolution activity.
6247            mResolveActivity.applicationInfo = pkg.applicationInfo;
6248            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6249            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6250            mResolveActivity.processName = null;
6251            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6252            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6253                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6254            mResolveActivity.theme = 0;
6255            mResolveActivity.exported = true;
6256            mResolveActivity.enabled = true;
6257            mResolveInfo.activityInfo = mResolveActivity;
6258            mResolveInfo.priority = 0;
6259            mResolveInfo.preferredOrder = 0;
6260            mResolveInfo.match = 0;
6261            mResolveComponentName = mCustomResolverComponentName;
6262            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6263                    mResolveComponentName);
6264        }
6265    }
6266
6267    private static String calculateBundledApkRoot(final String codePathString) {
6268        final File codePath = new File(codePathString);
6269        final File codeRoot;
6270        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6271            codeRoot = Environment.getRootDirectory();
6272        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6273            codeRoot = Environment.getOemDirectory();
6274        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6275            codeRoot = Environment.getVendorDirectory();
6276        } else {
6277            // Unrecognized code path; take its top real segment as the apk root:
6278            // e.g. /something/app/blah.apk => /something
6279            try {
6280                File f = codePath.getCanonicalFile();
6281                File parent = f.getParentFile();    // non-null because codePath is a file
6282                File tmp;
6283                while ((tmp = parent.getParentFile()) != null) {
6284                    f = parent;
6285                    parent = tmp;
6286                }
6287                codeRoot = f;
6288                Slog.w(TAG, "Unrecognized code path "
6289                        + codePath + " - using " + codeRoot);
6290            } catch (IOException e) {
6291                // Can't canonicalize the code path -- shenanigans?
6292                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6293                return Environment.getRootDirectory().getPath();
6294            }
6295        }
6296        return codeRoot.getPath();
6297    }
6298
6299    /**
6300     * Derive and set the location of native libraries for the given package,
6301     * which varies depending on where and how the package was installed.
6302     */
6303    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6304        final ApplicationInfo info = pkg.applicationInfo;
6305        final String codePath = pkg.codePath;
6306        final File codeFile = new File(codePath);
6307        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6308        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6309
6310        info.nativeLibraryRootDir = null;
6311        info.nativeLibraryRootRequiresIsa = false;
6312        info.nativeLibraryDir = null;
6313        info.secondaryNativeLibraryDir = null;
6314
6315        if (isApkFile(codeFile)) {
6316            // Monolithic install
6317            if (bundledApp) {
6318                // If "/system/lib64/apkname" exists, assume that is the per-package
6319                // native library directory to use; otherwise use "/system/lib/apkname".
6320                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6321                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6322                        getPrimaryInstructionSet(info));
6323
6324                // This is a bundled system app so choose the path based on the ABI.
6325                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6326                // is just the default path.
6327                final String apkName = deriveCodePathName(codePath);
6328                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6329                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6330                        apkName).getAbsolutePath();
6331
6332                if (info.secondaryCpuAbi != null) {
6333                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6334                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6335                            secondaryLibDir, apkName).getAbsolutePath();
6336                }
6337            } else if (asecApp) {
6338                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6339                        .getAbsolutePath();
6340            } else {
6341                final String apkName = deriveCodePathName(codePath);
6342                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6343                        .getAbsolutePath();
6344            }
6345
6346            info.nativeLibraryRootRequiresIsa = false;
6347            info.nativeLibraryDir = info.nativeLibraryRootDir;
6348        } else {
6349            // Cluster install
6350            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6351            info.nativeLibraryRootRequiresIsa = true;
6352
6353            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6354                    getPrimaryInstructionSet(info)).getAbsolutePath();
6355
6356            if (info.secondaryCpuAbi != null) {
6357                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6358                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6359            }
6360        }
6361    }
6362
6363    /**
6364     * Calculate the abis and roots for a bundled app. These can uniquely
6365     * be determined from the contents of the system partition, i.e whether
6366     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6367     * of this information, and instead assume that the system was built
6368     * sensibly.
6369     */
6370    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6371                                           PackageSetting pkgSetting) {
6372        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6373
6374        // If "/system/lib64/apkname" exists, assume that is the per-package
6375        // native library directory to use; otherwise use "/system/lib/apkname".
6376        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6377        setBundledAppAbi(pkg, apkRoot, apkName);
6378        // pkgSetting might be null during rescan following uninstall of updates
6379        // to a bundled app, so accommodate that possibility.  The settings in
6380        // that case will be established later from the parsed package.
6381        //
6382        // If the settings aren't null, sync them up with what we've just derived.
6383        // note that apkRoot isn't stored in the package settings.
6384        if (pkgSetting != null) {
6385            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6386            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6387        }
6388    }
6389
6390    /**
6391     * Deduces the ABI of a bundled app and sets the relevant fields on the
6392     * parsed pkg object.
6393     *
6394     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6395     *        under which system libraries are installed.
6396     * @param apkName the name of the installed package.
6397     */
6398    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6399        final File codeFile = new File(pkg.codePath);
6400
6401        final boolean has64BitLibs;
6402        final boolean has32BitLibs;
6403        if (isApkFile(codeFile)) {
6404            // Monolithic install
6405            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6406            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6407        } else {
6408            // Cluster install
6409            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6410            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6411                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6412                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6413                has64BitLibs = (new File(rootDir, isa)).exists();
6414            } else {
6415                has64BitLibs = false;
6416            }
6417            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6418                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6419                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6420                has32BitLibs = (new File(rootDir, isa)).exists();
6421            } else {
6422                has32BitLibs = false;
6423            }
6424        }
6425
6426        if (has64BitLibs && !has32BitLibs) {
6427            // The package has 64 bit libs, but not 32 bit libs. Its primary
6428            // ABI should be 64 bit. We can safely assume here that the bundled
6429            // native libraries correspond to the most preferred ABI in the list.
6430
6431            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6432            pkg.applicationInfo.secondaryCpuAbi = null;
6433        } else if (has32BitLibs && !has64BitLibs) {
6434            // The package has 32 bit libs but not 64 bit libs. Its primary
6435            // ABI should be 32 bit.
6436
6437            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6438            pkg.applicationInfo.secondaryCpuAbi = null;
6439        } else if (has32BitLibs && has64BitLibs) {
6440            // The application has both 64 and 32 bit bundled libraries. We check
6441            // here that the app declares multiArch support, and warn if it doesn't.
6442            //
6443            // We will be lenient here and record both ABIs. The primary will be the
6444            // ABI that's higher on the list, i.e, a device that's configured to prefer
6445            // 64 bit apps will see a 64 bit primary ABI,
6446
6447            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6448                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6449            }
6450
6451            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6452                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6453                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6454            } else {
6455                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6456                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6457            }
6458        } else {
6459            pkg.applicationInfo.primaryCpuAbi = null;
6460            pkg.applicationInfo.secondaryCpuAbi = null;
6461        }
6462    }
6463
6464    private void killApplication(String pkgName, int appId, String reason) {
6465        // Request the ActivityManager to kill the process(only for existing packages)
6466        // so that we do not end up in a confused state while the user is still using the older
6467        // version of the application while the new one gets installed.
6468        IActivityManager am = ActivityManagerNative.getDefault();
6469        if (am != null) {
6470            try {
6471                am.killApplicationWithAppId(pkgName, appId, reason);
6472            } catch (RemoteException e) {
6473            }
6474        }
6475    }
6476
6477    void removePackageLI(PackageSetting ps, boolean chatty) {
6478        if (DEBUG_INSTALL) {
6479            if (chatty)
6480                Log.d(TAG, "Removing package " + ps.name);
6481        }
6482
6483        // writer
6484        synchronized (mPackages) {
6485            mPackages.remove(ps.name);
6486            final PackageParser.Package pkg = ps.pkg;
6487            if (pkg != null) {
6488                cleanPackageDataStructuresLILPw(pkg, chatty);
6489            }
6490        }
6491    }
6492
6493    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6494        if (DEBUG_INSTALL) {
6495            if (chatty)
6496                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6497        }
6498
6499        // writer
6500        synchronized (mPackages) {
6501            mPackages.remove(pkg.applicationInfo.packageName);
6502            cleanPackageDataStructuresLILPw(pkg, chatty);
6503        }
6504    }
6505
6506    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6507        int N = pkg.providers.size();
6508        StringBuilder r = null;
6509        int i;
6510        for (i=0; i<N; i++) {
6511            PackageParser.Provider p = pkg.providers.get(i);
6512            mProviders.removeProvider(p);
6513            if (p.info.authority == null) {
6514
6515                /* There was another ContentProvider with this authority when
6516                 * this app was installed so this authority is null,
6517                 * Ignore it as we don't have to unregister the provider.
6518                 */
6519                continue;
6520            }
6521            String names[] = p.info.authority.split(";");
6522            for (int j = 0; j < names.length; j++) {
6523                if (mProvidersByAuthority.get(names[j]) == p) {
6524                    mProvidersByAuthority.remove(names[j]);
6525                    if (DEBUG_REMOVE) {
6526                        if (chatty)
6527                            Log.d(TAG, "Unregistered content provider: " + names[j]
6528                                    + ", className = " + p.info.name + ", isSyncable = "
6529                                    + p.info.isSyncable);
6530                    }
6531                }
6532            }
6533            if (DEBUG_REMOVE && chatty) {
6534                if (r == null) {
6535                    r = new StringBuilder(256);
6536                } else {
6537                    r.append(' ');
6538                }
6539                r.append(p.info.name);
6540            }
6541        }
6542        if (r != null) {
6543            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6544        }
6545
6546        N = pkg.services.size();
6547        r = null;
6548        for (i=0; i<N; i++) {
6549            PackageParser.Service s = pkg.services.get(i);
6550            mServices.removeService(s);
6551            if (chatty) {
6552                if (r == null) {
6553                    r = new StringBuilder(256);
6554                } else {
6555                    r.append(' ');
6556                }
6557                r.append(s.info.name);
6558            }
6559        }
6560        if (r != null) {
6561            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6562        }
6563
6564        N = pkg.receivers.size();
6565        r = null;
6566        for (i=0; i<N; i++) {
6567            PackageParser.Activity a = pkg.receivers.get(i);
6568            mReceivers.removeActivity(a, "receiver");
6569            if (DEBUG_REMOVE && chatty) {
6570                if (r == null) {
6571                    r = new StringBuilder(256);
6572                } else {
6573                    r.append(' ');
6574                }
6575                r.append(a.info.name);
6576            }
6577        }
6578        if (r != null) {
6579            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6580        }
6581
6582        N = pkg.activities.size();
6583        r = null;
6584        for (i=0; i<N; i++) {
6585            PackageParser.Activity a = pkg.activities.get(i);
6586            mActivities.removeActivity(a, "activity");
6587            if (DEBUG_REMOVE && chatty) {
6588                if (r == null) {
6589                    r = new StringBuilder(256);
6590                } else {
6591                    r.append(' ');
6592                }
6593                r.append(a.info.name);
6594            }
6595        }
6596        if (r != null) {
6597            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6598        }
6599
6600        N = pkg.permissions.size();
6601        r = null;
6602        for (i=0; i<N; i++) {
6603            PackageParser.Permission p = pkg.permissions.get(i);
6604            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6605            if (bp == null) {
6606                bp = mSettings.mPermissionTrees.get(p.info.name);
6607            }
6608            if (bp != null && bp.perm == p) {
6609                bp.perm = null;
6610                if (DEBUG_REMOVE && chatty) {
6611                    if (r == null) {
6612                        r = new StringBuilder(256);
6613                    } else {
6614                        r.append(' ');
6615                    }
6616                    r.append(p.info.name);
6617                }
6618            }
6619            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6620                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6621                if (appOpPerms != null) {
6622                    appOpPerms.remove(pkg.packageName);
6623                }
6624            }
6625        }
6626        if (r != null) {
6627            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6628        }
6629
6630        N = pkg.requestedPermissions.size();
6631        r = null;
6632        for (i=0; i<N; i++) {
6633            String perm = pkg.requestedPermissions.get(i);
6634            BasePermission bp = mSettings.mPermissions.get(perm);
6635            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6636                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6637                if (appOpPerms != null) {
6638                    appOpPerms.remove(pkg.packageName);
6639                    if (appOpPerms.isEmpty()) {
6640                        mAppOpPermissionPackages.remove(perm);
6641                    }
6642                }
6643            }
6644        }
6645        if (r != null) {
6646            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6647        }
6648
6649        N = pkg.instrumentation.size();
6650        r = null;
6651        for (i=0; i<N; i++) {
6652            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6653            mInstrumentation.remove(a.getComponentName());
6654            if (DEBUG_REMOVE && chatty) {
6655                if (r == null) {
6656                    r = new StringBuilder(256);
6657                } else {
6658                    r.append(' ');
6659                }
6660                r.append(a.info.name);
6661            }
6662        }
6663        if (r != null) {
6664            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6665        }
6666
6667        r = null;
6668        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6669            // Only system apps can hold shared libraries.
6670            if (pkg.libraryNames != null) {
6671                for (i=0; i<pkg.libraryNames.size(); i++) {
6672                    String name = pkg.libraryNames.get(i);
6673                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6674                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6675                        mSharedLibraries.remove(name);
6676                        if (DEBUG_REMOVE && chatty) {
6677                            if (r == null) {
6678                                r = new StringBuilder(256);
6679                            } else {
6680                                r.append(' ');
6681                            }
6682                            r.append(name);
6683                        }
6684                    }
6685                }
6686            }
6687        }
6688        if (r != null) {
6689            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6690        }
6691    }
6692
6693    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6694        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6695            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6696                return true;
6697            }
6698        }
6699        return false;
6700    }
6701
6702    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6703    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6704    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6705
6706    private void updatePermissionsLPw(String changingPkg,
6707            PackageParser.Package pkgInfo, int flags) {
6708        // Make sure there are no dangling permission trees.
6709        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6710        while (it.hasNext()) {
6711            final BasePermission bp = it.next();
6712            if (bp.packageSetting == null) {
6713                // We may not yet have parsed the package, so just see if
6714                // we still know about its settings.
6715                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6716            }
6717            if (bp.packageSetting == null) {
6718                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6719                        + " from package " + bp.sourcePackage);
6720                it.remove();
6721            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6722                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6723                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6724                            + " from package " + bp.sourcePackage);
6725                    flags |= UPDATE_PERMISSIONS_ALL;
6726                    it.remove();
6727                }
6728            }
6729        }
6730
6731        // Make sure all dynamic permissions have been assigned to a package,
6732        // and make sure there are no dangling permissions.
6733        it = mSettings.mPermissions.values().iterator();
6734        while (it.hasNext()) {
6735            final BasePermission bp = it.next();
6736            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6737                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6738                        + bp.name + " pkg=" + bp.sourcePackage
6739                        + " info=" + bp.pendingInfo);
6740                if (bp.packageSetting == null && bp.pendingInfo != null) {
6741                    final BasePermission tree = findPermissionTreeLP(bp.name);
6742                    if (tree != null && tree.perm != null) {
6743                        bp.packageSetting = tree.packageSetting;
6744                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6745                                new PermissionInfo(bp.pendingInfo));
6746                        bp.perm.info.packageName = tree.perm.info.packageName;
6747                        bp.perm.info.name = bp.name;
6748                        bp.uid = tree.uid;
6749                    }
6750                }
6751            }
6752            if (bp.packageSetting == null) {
6753                // We may not yet have parsed the package, so just see if
6754                // we still know about its settings.
6755                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6756            }
6757            if (bp.packageSetting == null) {
6758                Slog.w(TAG, "Removing dangling permission: " + bp.name
6759                        + " from package " + bp.sourcePackage);
6760                it.remove();
6761            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6762                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6763                    Slog.i(TAG, "Removing old permission: " + bp.name
6764                            + " from package " + bp.sourcePackage);
6765                    flags |= UPDATE_PERMISSIONS_ALL;
6766                    it.remove();
6767                }
6768            }
6769        }
6770
6771        // Now update the permissions for all packages, in particular
6772        // replace the granted permissions of the system packages.
6773        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6774            for (PackageParser.Package pkg : mPackages.values()) {
6775                if (pkg != pkgInfo) {
6776                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6777                            changingPkg);
6778                }
6779            }
6780        }
6781
6782        if (pkgInfo != null) {
6783            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6784        }
6785    }
6786
6787    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6788            String packageOfInterest) {
6789        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6790        if (ps == null) {
6791            return;
6792        }
6793        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6794        HashSet<String> origPermissions = gp.grantedPermissions;
6795        boolean changedPermission = false;
6796
6797        if (replace) {
6798            ps.permissionsFixed = false;
6799            if (gp == ps) {
6800                origPermissions = new HashSet<String>(gp.grantedPermissions);
6801                gp.grantedPermissions.clear();
6802                gp.gids = mGlobalGids;
6803            }
6804        }
6805
6806        if (gp.gids == null) {
6807            gp.gids = mGlobalGids;
6808        }
6809
6810        final int N = pkg.requestedPermissions.size();
6811        for (int i=0; i<N; i++) {
6812            final String name = pkg.requestedPermissions.get(i);
6813            final boolean required = pkg.requestedPermissionsRequired.get(i);
6814            final BasePermission bp = mSettings.mPermissions.get(name);
6815            if (DEBUG_INSTALL) {
6816                if (gp != ps) {
6817                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6818                }
6819            }
6820
6821            if (bp == null || bp.packageSetting == null) {
6822                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6823                    Slog.w(TAG, "Unknown permission " + name
6824                            + " in package " + pkg.packageName);
6825                }
6826                continue;
6827            }
6828
6829            final String perm = bp.name;
6830            boolean allowed;
6831            boolean allowedSig = false;
6832            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6833                // Keep track of app op permissions.
6834                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6835                if (pkgs == null) {
6836                    pkgs = new ArraySet<>();
6837                    mAppOpPermissionPackages.put(bp.name, pkgs);
6838                }
6839                pkgs.add(pkg.packageName);
6840            }
6841            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6842            if (level == PermissionInfo.PROTECTION_NORMAL
6843                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6844                // We grant a normal or dangerous permission if any of the following
6845                // are true:
6846                // 1) The permission is required
6847                // 2) The permission is optional, but was granted in the past
6848                // 3) The permission is optional, but was requested by an
6849                //    app in /system (not /data)
6850                //
6851                // Otherwise, reject the permission.
6852                allowed = (required || origPermissions.contains(perm)
6853                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6854            } else if (bp.packageSetting == null) {
6855                // This permission is invalid; skip it.
6856                allowed = false;
6857            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6858                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6859                if (allowed) {
6860                    allowedSig = true;
6861                }
6862            } else {
6863                allowed = false;
6864            }
6865            if (DEBUG_INSTALL) {
6866                if (gp != ps) {
6867                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6868                }
6869            }
6870            if (allowed) {
6871                if (!isSystemApp(ps) && ps.permissionsFixed) {
6872                    // If this is an existing, non-system package, then
6873                    // we can't add any new permissions to it.
6874                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6875                        // Except...  if this is a permission that was added
6876                        // to the platform (note: need to only do this when
6877                        // updating the platform).
6878                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6879                    }
6880                }
6881                if (allowed) {
6882                    if (!gp.grantedPermissions.contains(perm)) {
6883                        changedPermission = true;
6884                        gp.grantedPermissions.add(perm);
6885                        gp.gids = appendInts(gp.gids, bp.gids);
6886                    } else if (!ps.haveGids) {
6887                        gp.gids = appendInts(gp.gids, bp.gids);
6888                    }
6889                } else {
6890                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6891                        Slog.w(TAG, "Not granting permission " + perm
6892                                + " to package " + pkg.packageName
6893                                + " because it was previously installed without");
6894                    }
6895                }
6896            } else {
6897                if (gp.grantedPermissions.remove(perm)) {
6898                    changedPermission = true;
6899                    gp.gids = removeInts(gp.gids, bp.gids);
6900                    Slog.i(TAG, "Un-granting permission " + perm
6901                            + " from package " + pkg.packageName
6902                            + " (protectionLevel=" + bp.protectionLevel
6903                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6904                            + ")");
6905                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6906                    // Don't print warning for app op permissions, since it is fine for them
6907                    // not to be granted, there is a UI for the user to decide.
6908                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6909                        Slog.w(TAG, "Not granting permission " + perm
6910                                + " to package " + pkg.packageName
6911                                + " (protectionLevel=" + bp.protectionLevel
6912                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6913                                + ")");
6914                    }
6915                }
6916            }
6917        }
6918
6919        if ((changedPermission || replace) && !ps.permissionsFixed &&
6920                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6921            // This is the first that we have heard about this package, so the
6922            // permissions we have now selected are fixed until explicitly
6923            // changed.
6924            ps.permissionsFixed = true;
6925        }
6926        ps.haveGids = true;
6927    }
6928
6929    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6930        boolean allowed = false;
6931        final int NP = PackageParser.NEW_PERMISSIONS.length;
6932        for (int ip=0; ip<NP; ip++) {
6933            final PackageParser.NewPermissionInfo npi
6934                    = PackageParser.NEW_PERMISSIONS[ip];
6935            if (npi.name.equals(perm)
6936                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6937                allowed = true;
6938                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6939                        + pkg.packageName);
6940                break;
6941            }
6942        }
6943        return allowed;
6944    }
6945
6946    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6947                                          BasePermission bp, HashSet<String> origPermissions) {
6948        boolean allowed;
6949        allowed = (compareSignatures(
6950                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6951                        == PackageManager.SIGNATURE_MATCH)
6952                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6953                        == PackageManager.SIGNATURE_MATCH);
6954        if (!allowed && (bp.protectionLevel
6955                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6956            if (isSystemApp(pkg)) {
6957                // For updated system applications, a system permission
6958                // is granted only if it had been defined by the original application.
6959                if (isUpdatedSystemApp(pkg)) {
6960                    final PackageSetting sysPs = mSettings
6961                            .getDisabledSystemPkgLPr(pkg.packageName);
6962                    final GrantedPermissions origGp = sysPs.sharedUser != null
6963                            ? sysPs.sharedUser : sysPs;
6964
6965                    if (origGp.grantedPermissions.contains(perm)) {
6966                        // If the original was granted this permission, we take
6967                        // that grant decision as read and propagate it to the
6968                        // update.
6969                        allowed = true;
6970                    } else {
6971                        // The system apk may have been updated with an older
6972                        // version of the one on the data partition, but which
6973                        // granted a new system permission that it didn't have
6974                        // before.  In this case we do want to allow the app to
6975                        // now get the new permission if the ancestral apk is
6976                        // privileged to get it.
6977                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6978                            for (int j=0;
6979                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6980                                if (perm.equals(
6981                                        sysPs.pkg.requestedPermissions.get(j))) {
6982                                    allowed = true;
6983                                    break;
6984                                }
6985                            }
6986                        }
6987                    }
6988                } else {
6989                    allowed = isPrivilegedApp(pkg);
6990                }
6991            }
6992        }
6993        if (!allowed && (bp.protectionLevel
6994                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6995            // For development permissions, a development permission
6996            // is granted only if it was already granted.
6997            allowed = origPermissions.contains(perm);
6998        }
6999        return allowed;
7000    }
7001
7002    final class ActivityIntentResolver
7003            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7004        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7005                boolean defaultOnly, int userId) {
7006            if (!sUserManager.exists(userId)) return null;
7007            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7008            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7009        }
7010
7011        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7012                int userId) {
7013            if (!sUserManager.exists(userId)) return null;
7014            mFlags = flags;
7015            return super.queryIntent(intent, resolvedType,
7016                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7017        }
7018
7019        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7020                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7021            if (!sUserManager.exists(userId)) return null;
7022            if (packageActivities == null) {
7023                return null;
7024            }
7025            mFlags = flags;
7026            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7027            final int N = packageActivities.size();
7028            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7029                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7030
7031            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7032            for (int i = 0; i < N; ++i) {
7033                intentFilters = packageActivities.get(i).intents;
7034                if (intentFilters != null && intentFilters.size() > 0) {
7035                    PackageParser.ActivityIntentInfo[] array =
7036                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7037                    intentFilters.toArray(array);
7038                    listCut.add(array);
7039                }
7040            }
7041            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7042        }
7043
7044        public final void addActivity(PackageParser.Activity a, String type) {
7045            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7046            mActivities.put(a.getComponentName(), a);
7047            if (DEBUG_SHOW_INFO)
7048                Log.v(
7049                TAG, "  " + type + " " +
7050                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7051            if (DEBUG_SHOW_INFO)
7052                Log.v(TAG, "    Class=" + a.info.name);
7053            final int NI = a.intents.size();
7054            for (int j=0; j<NI; j++) {
7055                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7056                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7057                    intent.setPriority(0);
7058                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7059                            + a.className + " with priority > 0, forcing to 0");
7060                }
7061                if (DEBUG_SHOW_INFO) {
7062                    Log.v(TAG, "    IntentFilter:");
7063                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7064                }
7065                if (!intent.debugCheck()) {
7066                    Log.w(TAG, "==> For Activity " + a.info.name);
7067                }
7068                addFilter(intent);
7069            }
7070        }
7071
7072        public final void removeActivity(PackageParser.Activity a, String type) {
7073            mActivities.remove(a.getComponentName());
7074            if (DEBUG_SHOW_INFO) {
7075                Log.v(TAG, "  " + type + " "
7076                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7077                                : a.info.name) + ":");
7078                Log.v(TAG, "    Class=" + a.info.name);
7079            }
7080            final int NI = a.intents.size();
7081            for (int j=0; j<NI; j++) {
7082                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7083                if (DEBUG_SHOW_INFO) {
7084                    Log.v(TAG, "    IntentFilter:");
7085                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7086                }
7087                removeFilter(intent);
7088            }
7089        }
7090
7091        @Override
7092        protected boolean allowFilterResult(
7093                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7094            ActivityInfo filterAi = filter.activity.info;
7095            for (int i=dest.size()-1; i>=0; i--) {
7096                ActivityInfo destAi = dest.get(i).activityInfo;
7097                if (destAi.name == filterAi.name
7098                        && destAi.packageName == filterAi.packageName) {
7099                    return false;
7100                }
7101            }
7102            return true;
7103        }
7104
7105        @Override
7106        protected ActivityIntentInfo[] newArray(int size) {
7107            return new ActivityIntentInfo[size];
7108        }
7109
7110        @Override
7111        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7112            if (!sUserManager.exists(userId)) return true;
7113            PackageParser.Package p = filter.activity.owner;
7114            if (p != null) {
7115                PackageSetting ps = (PackageSetting)p.mExtras;
7116                if (ps != null) {
7117                    // System apps are never considered stopped for purposes of
7118                    // filtering, because there may be no way for the user to
7119                    // actually re-launch them.
7120                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7121                            && ps.getStopped(userId);
7122                }
7123            }
7124            return false;
7125        }
7126
7127        @Override
7128        protected boolean isPackageForFilter(String packageName,
7129                PackageParser.ActivityIntentInfo info) {
7130            return packageName.equals(info.activity.owner.packageName);
7131        }
7132
7133        @Override
7134        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7135                int match, int userId) {
7136            if (!sUserManager.exists(userId)) return null;
7137            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7138                return null;
7139            }
7140            final PackageParser.Activity activity = info.activity;
7141            if (mSafeMode && (activity.info.applicationInfo.flags
7142                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7143                return null;
7144            }
7145            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7146            if (ps == null) {
7147                return null;
7148            }
7149            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7150                    ps.readUserState(userId), userId);
7151            if (ai == null) {
7152                return null;
7153            }
7154            final ResolveInfo res = new ResolveInfo();
7155            res.activityInfo = ai;
7156            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7157                res.filter = info;
7158            }
7159            res.priority = info.getPriority();
7160            res.preferredOrder = activity.owner.mPreferredOrder;
7161            //System.out.println("Result: " + res.activityInfo.className +
7162            //                   " = " + res.priority);
7163            res.match = match;
7164            res.isDefault = info.hasDefault;
7165            res.labelRes = info.labelRes;
7166            res.nonLocalizedLabel = info.nonLocalizedLabel;
7167            if (userNeedsBadging(userId)) {
7168                res.noResourceId = true;
7169            } else {
7170                res.icon = info.icon;
7171            }
7172            res.system = isSystemApp(res.activityInfo.applicationInfo);
7173            return res;
7174        }
7175
7176        @Override
7177        protected void sortResults(List<ResolveInfo> results) {
7178            Collections.sort(results, mResolvePrioritySorter);
7179        }
7180
7181        @Override
7182        protected void dumpFilter(PrintWriter out, String prefix,
7183                PackageParser.ActivityIntentInfo filter) {
7184            out.print(prefix); out.print(
7185                    Integer.toHexString(System.identityHashCode(filter.activity)));
7186                    out.print(' ');
7187                    filter.activity.printComponentShortName(out);
7188                    out.print(" filter ");
7189                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7190        }
7191
7192//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7193//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7194//            final List<ResolveInfo> retList = Lists.newArrayList();
7195//            while (i.hasNext()) {
7196//                final ResolveInfo resolveInfo = i.next();
7197//                if (isEnabledLP(resolveInfo.activityInfo)) {
7198//                    retList.add(resolveInfo);
7199//                }
7200//            }
7201//            return retList;
7202//        }
7203
7204        // Keys are String (activity class name), values are Activity.
7205        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7206                = new HashMap<ComponentName, PackageParser.Activity>();
7207        private int mFlags;
7208    }
7209
7210    private final class ServiceIntentResolver
7211            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7212        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7213                boolean defaultOnly, int userId) {
7214            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7215            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7216        }
7217
7218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7219                int userId) {
7220            if (!sUserManager.exists(userId)) return null;
7221            mFlags = flags;
7222            return super.queryIntent(intent, resolvedType,
7223                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7224        }
7225
7226        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7227                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7228            if (!sUserManager.exists(userId)) return null;
7229            if (packageServices == null) {
7230                return null;
7231            }
7232            mFlags = flags;
7233            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7234            final int N = packageServices.size();
7235            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7236                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7237
7238            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7239            for (int i = 0; i < N; ++i) {
7240                intentFilters = packageServices.get(i).intents;
7241                if (intentFilters != null && intentFilters.size() > 0) {
7242                    PackageParser.ServiceIntentInfo[] array =
7243                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7244                    intentFilters.toArray(array);
7245                    listCut.add(array);
7246                }
7247            }
7248            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7249        }
7250
7251        public final void addService(PackageParser.Service s) {
7252            mServices.put(s.getComponentName(), s);
7253            if (DEBUG_SHOW_INFO) {
7254                Log.v(TAG, "  "
7255                        + (s.info.nonLocalizedLabel != null
7256                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7257                Log.v(TAG, "    Class=" + s.info.name);
7258            }
7259            final int NI = s.intents.size();
7260            int j;
7261            for (j=0; j<NI; j++) {
7262                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7263                if (DEBUG_SHOW_INFO) {
7264                    Log.v(TAG, "    IntentFilter:");
7265                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7266                }
7267                if (!intent.debugCheck()) {
7268                    Log.w(TAG, "==> For Service " + s.info.name);
7269                }
7270                addFilter(intent);
7271            }
7272        }
7273
7274        public final void removeService(PackageParser.Service s) {
7275            mServices.remove(s.getComponentName());
7276            if (DEBUG_SHOW_INFO) {
7277                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7278                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7279                Log.v(TAG, "    Class=" + s.info.name);
7280            }
7281            final int NI = s.intents.size();
7282            int j;
7283            for (j=0; j<NI; j++) {
7284                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7285                if (DEBUG_SHOW_INFO) {
7286                    Log.v(TAG, "    IntentFilter:");
7287                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7288                }
7289                removeFilter(intent);
7290            }
7291        }
7292
7293        @Override
7294        protected boolean allowFilterResult(
7295                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7296            ServiceInfo filterSi = filter.service.info;
7297            for (int i=dest.size()-1; i>=0; i--) {
7298                ServiceInfo destAi = dest.get(i).serviceInfo;
7299                if (destAi.name == filterSi.name
7300                        && destAi.packageName == filterSi.packageName) {
7301                    return false;
7302                }
7303            }
7304            return true;
7305        }
7306
7307        @Override
7308        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7309            return new PackageParser.ServiceIntentInfo[size];
7310        }
7311
7312        @Override
7313        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7314            if (!sUserManager.exists(userId)) return true;
7315            PackageParser.Package p = filter.service.owner;
7316            if (p != null) {
7317                PackageSetting ps = (PackageSetting)p.mExtras;
7318                if (ps != null) {
7319                    // System apps are never considered stopped for purposes of
7320                    // filtering, because there may be no way for the user to
7321                    // actually re-launch them.
7322                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7323                            && ps.getStopped(userId);
7324                }
7325            }
7326            return false;
7327        }
7328
7329        @Override
7330        protected boolean isPackageForFilter(String packageName,
7331                PackageParser.ServiceIntentInfo info) {
7332            return packageName.equals(info.service.owner.packageName);
7333        }
7334
7335        @Override
7336        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7337                int match, int userId) {
7338            if (!sUserManager.exists(userId)) return null;
7339            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7340            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7341                return null;
7342            }
7343            final PackageParser.Service service = info.service;
7344            if (mSafeMode && (service.info.applicationInfo.flags
7345                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7346                return null;
7347            }
7348            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7349            if (ps == null) {
7350                return null;
7351            }
7352            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7353                    ps.readUserState(userId), userId);
7354            if (si == null) {
7355                return null;
7356            }
7357            final ResolveInfo res = new ResolveInfo();
7358            res.serviceInfo = si;
7359            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7360                res.filter = filter;
7361            }
7362            res.priority = info.getPriority();
7363            res.preferredOrder = service.owner.mPreferredOrder;
7364            //System.out.println("Result: " + res.activityInfo.className +
7365            //                   " = " + res.priority);
7366            res.match = match;
7367            res.isDefault = info.hasDefault;
7368            res.labelRes = info.labelRes;
7369            res.nonLocalizedLabel = info.nonLocalizedLabel;
7370            res.icon = info.icon;
7371            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7372            return res;
7373        }
7374
7375        @Override
7376        protected void sortResults(List<ResolveInfo> results) {
7377            Collections.sort(results, mResolvePrioritySorter);
7378        }
7379
7380        @Override
7381        protected void dumpFilter(PrintWriter out, String prefix,
7382                PackageParser.ServiceIntentInfo filter) {
7383            out.print(prefix); out.print(
7384                    Integer.toHexString(System.identityHashCode(filter.service)));
7385                    out.print(' ');
7386                    filter.service.printComponentShortName(out);
7387                    out.print(" filter ");
7388                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7389        }
7390
7391//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7392//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7393//            final List<ResolveInfo> retList = Lists.newArrayList();
7394//            while (i.hasNext()) {
7395//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7396//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7397//                    retList.add(resolveInfo);
7398//                }
7399//            }
7400//            return retList;
7401//        }
7402
7403        // Keys are String (activity class name), values are Activity.
7404        private final HashMap<ComponentName, PackageParser.Service> mServices
7405                = new HashMap<ComponentName, PackageParser.Service>();
7406        private int mFlags;
7407    };
7408
7409    private final class ProviderIntentResolver
7410            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7411        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7412                boolean defaultOnly, int userId) {
7413            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7414            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7415        }
7416
7417        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7418                int userId) {
7419            if (!sUserManager.exists(userId))
7420                return null;
7421            mFlags = flags;
7422            return super.queryIntent(intent, resolvedType,
7423                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7424        }
7425
7426        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7427                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7428            if (!sUserManager.exists(userId))
7429                return null;
7430            if (packageProviders == null) {
7431                return null;
7432            }
7433            mFlags = flags;
7434            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7435            final int N = packageProviders.size();
7436            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7437                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7438
7439            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7440            for (int i = 0; i < N; ++i) {
7441                intentFilters = packageProviders.get(i).intents;
7442                if (intentFilters != null && intentFilters.size() > 0) {
7443                    PackageParser.ProviderIntentInfo[] array =
7444                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7445                    intentFilters.toArray(array);
7446                    listCut.add(array);
7447                }
7448            }
7449            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7450        }
7451
7452        public final void addProvider(PackageParser.Provider p) {
7453            if (mProviders.containsKey(p.getComponentName())) {
7454                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7455                return;
7456            }
7457
7458            mProviders.put(p.getComponentName(), p);
7459            if (DEBUG_SHOW_INFO) {
7460                Log.v(TAG, "  "
7461                        + (p.info.nonLocalizedLabel != null
7462                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7463                Log.v(TAG, "    Class=" + p.info.name);
7464            }
7465            final int NI = p.intents.size();
7466            int j;
7467            for (j = 0; j < NI; j++) {
7468                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7469                if (DEBUG_SHOW_INFO) {
7470                    Log.v(TAG, "    IntentFilter:");
7471                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7472                }
7473                if (!intent.debugCheck()) {
7474                    Log.w(TAG, "==> For Provider " + p.info.name);
7475                }
7476                addFilter(intent);
7477            }
7478        }
7479
7480        public final void removeProvider(PackageParser.Provider p) {
7481            mProviders.remove(p.getComponentName());
7482            if (DEBUG_SHOW_INFO) {
7483                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7484                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7485                Log.v(TAG, "    Class=" + p.info.name);
7486            }
7487            final int NI = p.intents.size();
7488            int j;
7489            for (j = 0; j < NI; j++) {
7490                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7491                if (DEBUG_SHOW_INFO) {
7492                    Log.v(TAG, "    IntentFilter:");
7493                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7494                }
7495                removeFilter(intent);
7496            }
7497        }
7498
7499        @Override
7500        protected boolean allowFilterResult(
7501                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7502            ProviderInfo filterPi = filter.provider.info;
7503            for (int i = dest.size() - 1; i >= 0; i--) {
7504                ProviderInfo destPi = dest.get(i).providerInfo;
7505                if (destPi.name == filterPi.name
7506                        && destPi.packageName == filterPi.packageName) {
7507                    return false;
7508                }
7509            }
7510            return true;
7511        }
7512
7513        @Override
7514        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7515            return new PackageParser.ProviderIntentInfo[size];
7516        }
7517
7518        @Override
7519        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7520            if (!sUserManager.exists(userId))
7521                return true;
7522            PackageParser.Package p = filter.provider.owner;
7523            if (p != null) {
7524                PackageSetting ps = (PackageSetting) p.mExtras;
7525                if (ps != null) {
7526                    // System apps are never considered stopped for purposes of
7527                    // filtering, because there may be no way for the user to
7528                    // actually re-launch them.
7529                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7530                            && ps.getStopped(userId);
7531                }
7532            }
7533            return false;
7534        }
7535
7536        @Override
7537        protected boolean isPackageForFilter(String packageName,
7538                PackageParser.ProviderIntentInfo info) {
7539            return packageName.equals(info.provider.owner.packageName);
7540        }
7541
7542        @Override
7543        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7544                int match, int userId) {
7545            if (!sUserManager.exists(userId))
7546                return null;
7547            final PackageParser.ProviderIntentInfo info = filter;
7548            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7549                return null;
7550            }
7551            final PackageParser.Provider provider = info.provider;
7552            if (mSafeMode && (provider.info.applicationInfo.flags
7553                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7554                return null;
7555            }
7556            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7557            if (ps == null) {
7558                return null;
7559            }
7560            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7561                    ps.readUserState(userId), userId);
7562            if (pi == null) {
7563                return null;
7564            }
7565            final ResolveInfo res = new ResolveInfo();
7566            res.providerInfo = pi;
7567            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7568                res.filter = filter;
7569            }
7570            res.priority = info.getPriority();
7571            res.preferredOrder = provider.owner.mPreferredOrder;
7572            res.match = match;
7573            res.isDefault = info.hasDefault;
7574            res.labelRes = info.labelRes;
7575            res.nonLocalizedLabel = info.nonLocalizedLabel;
7576            res.icon = info.icon;
7577            res.system = isSystemApp(res.providerInfo.applicationInfo);
7578            return res;
7579        }
7580
7581        @Override
7582        protected void sortResults(List<ResolveInfo> results) {
7583            Collections.sort(results, mResolvePrioritySorter);
7584        }
7585
7586        @Override
7587        protected void dumpFilter(PrintWriter out, String prefix,
7588                PackageParser.ProviderIntentInfo filter) {
7589            out.print(prefix);
7590            out.print(
7591                    Integer.toHexString(System.identityHashCode(filter.provider)));
7592            out.print(' ');
7593            filter.provider.printComponentShortName(out);
7594            out.print(" filter ");
7595            out.println(Integer.toHexString(System.identityHashCode(filter)));
7596        }
7597
7598        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7599                = new HashMap<ComponentName, PackageParser.Provider>();
7600        private int mFlags;
7601    };
7602
7603    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7604            new Comparator<ResolveInfo>() {
7605        public int compare(ResolveInfo r1, ResolveInfo r2) {
7606            int v1 = r1.priority;
7607            int v2 = r2.priority;
7608            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7609            if (v1 != v2) {
7610                return (v1 > v2) ? -1 : 1;
7611            }
7612            v1 = r1.preferredOrder;
7613            v2 = r2.preferredOrder;
7614            if (v1 != v2) {
7615                return (v1 > v2) ? -1 : 1;
7616            }
7617            if (r1.isDefault != r2.isDefault) {
7618                return r1.isDefault ? -1 : 1;
7619            }
7620            v1 = r1.match;
7621            v2 = r2.match;
7622            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7623            if (v1 != v2) {
7624                return (v1 > v2) ? -1 : 1;
7625            }
7626            if (r1.system != r2.system) {
7627                return r1.system ? -1 : 1;
7628            }
7629            return 0;
7630        }
7631    };
7632
7633    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7634            new Comparator<ProviderInfo>() {
7635        public int compare(ProviderInfo p1, ProviderInfo p2) {
7636            final int v1 = p1.initOrder;
7637            final int v2 = p2.initOrder;
7638            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7639        }
7640    };
7641
7642    static final void sendPackageBroadcast(String action, String pkg,
7643            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7644            int[] userIds) {
7645        IActivityManager am = ActivityManagerNative.getDefault();
7646        if (am != null) {
7647            try {
7648                if (userIds == null) {
7649                    userIds = am.getRunningUserIds();
7650                }
7651                for (int id : userIds) {
7652                    final Intent intent = new Intent(action,
7653                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7654                    if (extras != null) {
7655                        intent.putExtras(extras);
7656                    }
7657                    if (targetPkg != null) {
7658                        intent.setPackage(targetPkg);
7659                    }
7660                    // Modify the UID when posting to other users
7661                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7662                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7663                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7664                        intent.putExtra(Intent.EXTRA_UID, uid);
7665                    }
7666                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7667                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7668                    if (DEBUG_BROADCASTS) {
7669                        RuntimeException here = new RuntimeException("here");
7670                        here.fillInStackTrace();
7671                        Slog.d(TAG, "Sending to user " + id + ": "
7672                                + intent.toShortString(false, true, false, false)
7673                                + " " + intent.getExtras(), here);
7674                    }
7675                    am.broadcastIntent(null, intent, null, finishedReceiver,
7676                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7677                            finishedReceiver != null, false, id);
7678                }
7679            } catch (RemoteException ex) {
7680            }
7681        }
7682    }
7683
7684    /**
7685     * Check if the external storage media is available. This is true if there
7686     * is a mounted external storage medium or if the external storage is
7687     * emulated.
7688     */
7689    private boolean isExternalMediaAvailable() {
7690        return mMediaMounted || Environment.isExternalStorageEmulated();
7691    }
7692
7693    @Override
7694    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7695        // writer
7696        synchronized (mPackages) {
7697            if (!isExternalMediaAvailable()) {
7698                // If the external storage is no longer mounted at this point,
7699                // the caller may not have been able to delete all of this
7700                // packages files and can not delete any more.  Bail.
7701                return null;
7702            }
7703            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7704            if (lastPackage != null) {
7705                pkgs.remove(lastPackage);
7706            }
7707            if (pkgs.size() > 0) {
7708                return pkgs.get(0);
7709            }
7710        }
7711        return null;
7712    }
7713
7714    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7715        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7716                userId, andCode ? 1 : 0, packageName);
7717        if (mSystemReady) {
7718            msg.sendToTarget();
7719        } else {
7720            if (mPostSystemReadyMessages == null) {
7721                mPostSystemReadyMessages = new ArrayList<>();
7722            }
7723            mPostSystemReadyMessages.add(msg);
7724        }
7725    }
7726
7727    void startCleaningPackages() {
7728        // reader
7729        synchronized (mPackages) {
7730            if (!isExternalMediaAvailable()) {
7731                return;
7732            }
7733            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7734                return;
7735            }
7736        }
7737        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7738        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7739        IActivityManager am = ActivityManagerNative.getDefault();
7740        if (am != null) {
7741            try {
7742                am.startService(null, intent, null, UserHandle.USER_OWNER);
7743            } catch (RemoteException e) {
7744            }
7745        }
7746    }
7747
7748    @Override
7749    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7750            int installFlags, String installerPackageName, VerificationParams verificationParams,
7751            String packageAbiOverride) {
7752        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7753                packageAbiOverride, UserHandle.getCallingUserId());
7754    }
7755
7756    @Override
7757    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7758            int installFlags, String installerPackageName, VerificationParams verificationParams,
7759            String packageAbiOverride, int userId) {
7760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7761
7762        final int callingUid = Binder.getCallingUid();
7763        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7764
7765        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7766            try {
7767                if (observer != null) {
7768                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7769                }
7770            } catch (RemoteException re) {
7771            }
7772            return;
7773        }
7774
7775        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7776            installFlags |= PackageManager.INSTALL_FROM_ADB;
7777
7778        } else {
7779            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7780            // about installerPackageName.
7781
7782            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7783            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7784        }
7785
7786        UserHandle user;
7787        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7788            user = UserHandle.ALL;
7789        } else {
7790            user = new UserHandle(userId);
7791        }
7792
7793        verificationParams.setInstallerUid(callingUid);
7794
7795        final File originFile = new File(originPath);
7796        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7797
7798        final Message msg = mHandler.obtainMessage(INIT_COPY);
7799        msg.obj = new InstallParams(origin, observer, installFlags,
7800                installerPackageName, verificationParams, user, packageAbiOverride);
7801        mHandler.sendMessage(msg);
7802    }
7803
7804    void installStage(String packageName, File stagedDir, String stagedCid,
7805            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7806            String installerPackageName, int installerUid, UserHandle user) {
7807        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7808                params.referrerUri, installerUid, null);
7809
7810        final OriginInfo origin;
7811        if (stagedDir != null) {
7812            origin = OriginInfo.fromStagedFile(stagedDir);
7813        } else {
7814            origin = OriginInfo.fromStagedContainer(stagedCid);
7815        }
7816
7817        final Message msg = mHandler.obtainMessage(INIT_COPY);
7818        msg.obj = new InstallParams(origin, observer, params.installFlags,
7819                installerPackageName, verifParams, user, params.abiOverride);
7820        mHandler.sendMessage(msg);
7821    }
7822
7823    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7824        Bundle extras = new Bundle(1);
7825        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7826
7827        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7828                packageName, extras, null, null, new int[] {userId});
7829        try {
7830            IActivityManager am = ActivityManagerNative.getDefault();
7831            final boolean isSystem =
7832                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7833            if (isSystem && am.isUserRunning(userId, false)) {
7834                // The just-installed/enabled app is bundled on the system, so presumed
7835                // to be able to run automatically without needing an explicit launch.
7836                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7837                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7838                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7839                        .setPackage(packageName);
7840                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7841                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7842            }
7843        } catch (RemoteException e) {
7844            // shouldn't happen
7845            Slog.w(TAG, "Unable to bootstrap installed package", e);
7846        }
7847    }
7848
7849    @Override
7850    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7851            int userId) {
7852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7853        PackageSetting pkgSetting;
7854        final int uid = Binder.getCallingUid();
7855        enforceCrossUserPermission(uid, userId, true, true,
7856                "setApplicationHiddenSetting for user " + userId);
7857
7858        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7859            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7860            return false;
7861        }
7862
7863        long callingId = Binder.clearCallingIdentity();
7864        try {
7865            boolean sendAdded = false;
7866            boolean sendRemoved = false;
7867            // writer
7868            synchronized (mPackages) {
7869                pkgSetting = mSettings.mPackages.get(packageName);
7870                if (pkgSetting == null) {
7871                    return false;
7872                }
7873                if (pkgSetting.getHidden(userId) != hidden) {
7874                    pkgSetting.setHidden(hidden, userId);
7875                    mSettings.writePackageRestrictionsLPr(userId);
7876                    if (hidden) {
7877                        sendRemoved = true;
7878                    } else {
7879                        sendAdded = true;
7880                    }
7881                }
7882            }
7883            if (sendAdded) {
7884                sendPackageAddedForUser(packageName, pkgSetting, userId);
7885                return true;
7886            }
7887            if (sendRemoved) {
7888                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7889                        "hiding pkg");
7890                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7891            }
7892        } finally {
7893            Binder.restoreCallingIdentity(callingId);
7894        }
7895        return false;
7896    }
7897
7898    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7899            int userId) {
7900        final PackageRemovedInfo info = new PackageRemovedInfo();
7901        info.removedPackage = packageName;
7902        info.removedUsers = new int[] {userId};
7903        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7904        info.sendBroadcast(false, false, false);
7905    }
7906
7907    /**
7908     * Returns true if application is not found or there was an error. Otherwise it returns
7909     * the hidden state of the package for the given user.
7910     */
7911    @Override
7912    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7913        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7914        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7915                false, "getApplicationHidden for user " + userId);
7916        PackageSetting pkgSetting;
7917        long callingId = Binder.clearCallingIdentity();
7918        try {
7919            // writer
7920            synchronized (mPackages) {
7921                pkgSetting = mSettings.mPackages.get(packageName);
7922                if (pkgSetting == null) {
7923                    return true;
7924                }
7925                return pkgSetting.getHidden(userId);
7926            }
7927        } finally {
7928            Binder.restoreCallingIdentity(callingId);
7929        }
7930    }
7931
7932    /**
7933     * @hide
7934     */
7935    @Override
7936    public int installExistingPackageAsUser(String packageName, int userId) {
7937        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7938                null);
7939        PackageSetting pkgSetting;
7940        final int uid = Binder.getCallingUid();
7941        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7942                + userId);
7943        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7944            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7945        }
7946
7947        long callingId = Binder.clearCallingIdentity();
7948        try {
7949            boolean sendAdded = false;
7950            Bundle extras = new Bundle(1);
7951
7952            // writer
7953            synchronized (mPackages) {
7954                pkgSetting = mSettings.mPackages.get(packageName);
7955                if (pkgSetting == null) {
7956                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7957                }
7958                if (!pkgSetting.getInstalled(userId)) {
7959                    pkgSetting.setInstalled(true, userId);
7960                    pkgSetting.setHidden(false, userId);
7961                    mSettings.writePackageRestrictionsLPr(userId);
7962                    sendAdded = true;
7963                }
7964            }
7965
7966            if (sendAdded) {
7967                sendPackageAddedForUser(packageName, pkgSetting, userId);
7968            }
7969        } finally {
7970            Binder.restoreCallingIdentity(callingId);
7971        }
7972
7973        return PackageManager.INSTALL_SUCCEEDED;
7974    }
7975
7976    boolean isUserRestricted(int userId, String restrictionKey) {
7977        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7978        if (restrictions.getBoolean(restrictionKey, false)) {
7979            Log.w(TAG, "User is restricted: " + restrictionKey);
7980            return true;
7981        }
7982        return false;
7983    }
7984
7985    @Override
7986    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7987        mContext.enforceCallingOrSelfPermission(
7988                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7989                "Only package verification agents can verify applications");
7990
7991        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7992        final PackageVerificationResponse response = new PackageVerificationResponse(
7993                verificationCode, Binder.getCallingUid());
7994        msg.arg1 = id;
7995        msg.obj = response;
7996        mHandler.sendMessage(msg);
7997    }
7998
7999    @Override
8000    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8001            long millisecondsToDelay) {
8002        mContext.enforceCallingOrSelfPermission(
8003                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8004                "Only package verification agents can extend verification timeouts");
8005
8006        final PackageVerificationState state = mPendingVerification.get(id);
8007        final PackageVerificationResponse response = new PackageVerificationResponse(
8008                verificationCodeAtTimeout, Binder.getCallingUid());
8009
8010        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8011            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8012        }
8013        if (millisecondsToDelay < 0) {
8014            millisecondsToDelay = 0;
8015        }
8016        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8017                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8018            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8019        }
8020
8021        if ((state != null) && !state.timeoutExtended()) {
8022            state.extendTimeout();
8023
8024            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8025            msg.arg1 = id;
8026            msg.obj = response;
8027            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8028        }
8029    }
8030
8031    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8032            int verificationCode, UserHandle user) {
8033        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8034        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8035        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8036        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8037        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8038
8039        mContext.sendBroadcastAsUser(intent, user,
8040                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8041    }
8042
8043    private ComponentName matchComponentForVerifier(String packageName,
8044            List<ResolveInfo> receivers) {
8045        ActivityInfo targetReceiver = null;
8046
8047        final int NR = receivers.size();
8048        for (int i = 0; i < NR; i++) {
8049            final ResolveInfo info = receivers.get(i);
8050            if (info.activityInfo == null) {
8051                continue;
8052            }
8053
8054            if (packageName.equals(info.activityInfo.packageName)) {
8055                targetReceiver = info.activityInfo;
8056                break;
8057            }
8058        }
8059
8060        if (targetReceiver == null) {
8061            return null;
8062        }
8063
8064        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8065    }
8066
8067    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8068            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8069        if (pkgInfo.verifiers.length == 0) {
8070            return null;
8071        }
8072
8073        final int N = pkgInfo.verifiers.length;
8074        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8075        for (int i = 0; i < N; i++) {
8076            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8077
8078            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8079                    receivers);
8080            if (comp == null) {
8081                continue;
8082            }
8083
8084            final int verifierUid = getUidForVerifier(verifierInfo);
8085            if (verifierUid == -1) {
8086                continue;
8087            }
8088
8089            if (DEBUG_VERIFY) {
8090                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8091                        + " with the correct signature");
8092            }
8093            sufficientVerifiers.add(comp);
8094            verificationState.addSufficientVerifier(verifierUid);
8095        }
8096
8097        return sufficientVerifiers;
8098    }
8099
8100    private int getUidForVerifier(VerifierInfo verifierInfo) {
8101        synchronized (mPackages) {
8102            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8103            if (pkg == null) {
8104                return -1;
8105            } else if (pkg.mSignatures.length != 1) {
8106                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8107                        + " has more than one signature; ignoring");
8108                return -1;
8109            }
8110
8111            /*
8112             * If the public key of the package's signature does not match
8113             * our expected public key, then this is a different package and
8114             * we should skip.
8115             */
8116
8117            final byte[] expectedPublicKey;
8118            try {
8119                final Signature verifierSig = pkg.mSignatures[0];
8120                final PublicKey publicKey = verifierSig.getPublicKey();
8121                expectedPublicKey = publicKey.getEncoded();
8122            } catch (CertificateException e) {
8123                return -1;
8124            }
8125
8126            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8127
8128            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8129                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8130                        + " does not have the expected public key; ignoring");
8131                return -1;
8132            }
8133
8134            return pkg.applicationInfo.uid;
8135        }
8136    }
8137
8138    @Override
8139    public void finishPackageInstall(int token) {
8140        enforceSystemOrRoot("Only the system is allowed to finish installs");
8141
8142        if (DEBUG_INSTALL) {
8143            Slog.v(TAG, "BM finishing package install for " + token);
8144        }
8145
8146        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8147        mHandler.sendMessage(msg);
8148    }
8149
8150    /**
8151     * Get the verification agent timeout.
8152     *
8153     * @return verification timeout in milliseconds
8154     */
8155    private long getVerificationTimeout() {
8156        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8157                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8158                DEFAULT_VERIFICATION_TIMEOUT);
8159    }
8160
8161    /**
8162     * Get the default verification agent response code.
8163     *
8164     * @return default verification response code
8165     */
8166    private int getDefaultVerificationResponse() {
8167        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8168                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8169                DEFAULT_VERIFICATION_RESPONSE);
8170    }
8171
8172    /**
8173     * Check whether or not package verification has been enabled.
8174     *
8175     * @return true if verification should be performed
8176     */
8177    private boolean isVerificationEnabled(int userId, int installFlags) {
8178        if (!DEFAULT_VERIFY_ENABLE) {
8179            return false;
8180        }
8181
8182        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8183
8184        // Check if installing from ADB
8185        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8186            // Do not run verification in a test harness environment
8187            if (ActivityManager.isRunningInTestHarness()) {
8188                return false;
8189            }
8190            if (ensureVerifyAppsEnabled) {
8191                return true;
8192            }
8193            // Check if the developer does not want package verification for ADB installs
8194            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8195                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8196                return false;
8197            }
8198        }
8199
8200        if (ensureVerifyAppsEnabled) {
8201            return true;
8202        }
8203
8204        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8205                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8206    }
8207
8208    /**
8209     * Get the "allow unknown sources" setting.
8210     *
8211     * @return the current "allow unknown sources" setting
8212     */
8213    private int getUnknownSourcesSettings() {
8214        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8215                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8216                -1);
8217    }
8218
8219    @Override
8220    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8221        final int uid = Binder.getCallingUid();
8222        // writer
8223        synchronized (mPackages) {
8224            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8225            if (targetPackageSetting == null) {
8226                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8227            }
8228
8229            PackageSetting installerPackageSetting;
8230            if (installerPackageName != null) {
8231                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8232                if (installerPackageSetting == null) {
8233                    throw new IllegalArgumentException("Unknown installer package: "
8234                            + installerPackageName);
8235                }
8236            } else {
8237                installerPackageSetting = null;
8238            }
8239
8240            Signature[] callerSignature;
8241            Object obj = mSettings.getUserIdLPr(uid);
8242            if (obj != null) {
8243                if (obj instanceof SharedUserSetting) {
8244                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8245                } else if (obj instanceof PackageSetting) {
8246                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8247                } else {
8248                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8249                }
8250            } else {
8251                throw new SecurityException("Unknown calling uid " + uid);
8252            }
8253
8254            // Verify: can't set installerPackageName to a package that is
8255            // not signed with the same cert as the caller.
8256            if (installerPackageSetting != null) {
8257                if (compareSignatures(callerSignature,
8258                        installerPackageSetting.signatures.mSignatures)
8259                        != PackageManager.SIGNATURE_MATCH) {
8260                    throw new SecurityException(
8261                            "Caller does not have same cert as new installer package "
8262                            + installerPackageName);
8263                }
8264            }
8265
8266            // Verify: if target already has an installer package, it must
8267            // be signed with the same cert as the caller.
8268            if (targetPackageSetting.installerPackageName != null) {
8269                PackageSetting setting = mSettings.mPackages.get(
8270                        targetPackageSetting.installerPackageName);
8271                // If the currently set package isn't valid, then it's always
8272                // okay to change it.
8273                if (setting != null) {
8274                    if (compareSignatures(callerSignature,
8275                            setting.signatures.mSignatures)
8276                            != PackageManager.SIGNATURE_MATCH) {
8277                        throw new SecurityException(
8278                                "Caller does not have same cert as old installer package "
8279                                + targetPackageSetting.installerPackageName);
8280                    }
8281                }
8282            }
8283
8284            // Okay!
8285            targetPackageSetting.installerPackageName = installerPackageName;
8286            scheduleWriteSettingsLocked();
8287        }
8288    }
8289
8290    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8291        // Queue up an async operation since the package installation may take a little while.
8292        mHandler.post(new Runnable() {
8293            public void run() {
8294                mHandler.removeCallbacks(this);
8295                 // Result object to be returned
8296                PackageInstalledInfo res = new PackageInstalledInfo();
8297                res.returnCode = currentStatus;
8298                res.uid = -1;
8299                res.pkg = null;
8300                res.removedInfo = new PackageRemovedInfo();
8301                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8302                    args.doPreInstall(res.returnCode);
8303                    synchronized (mInstallLock) {
8304                        installPackageLI(args, res);
8305                    }
8306                    args.doPostInstall(res.returnCode, res.uid);
8307                }
8308
8309                // A restore should be performed at this point if (a) the install
8310                // succeeded, (b) the operation is not an update, and (c) the new
8311                // package has not opted out of backup participation.
8312                final boolean update = res.removedInfo.removedPackage != null;
8313                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8314                boolean doRestore = !update
8315                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8316
8317                // Set up the post-install work request bookkeeping.  This will be used
8318                // and cleaned up by the post-install event handling regardless of whether
8319                // there's a restore pass performed.  Token values are >= 1.
8320                int token;
8321                if (mNextInstallToken < 0) mNextInstallToken = 1;
8322                token = mNextInstallToken++;
8323
8324                PostInstallData data = new PostInstallData(args, res);
8325                mRunningInstalls.put(token, data);
8326                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8327
8328                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8329                    // Pass responsibility to the Backup Manager.  It will perform a
8330                    // restore if appropriate, then pass responsibility back to the
8331                    // Package Manager to run the post-install observer callbacks
8332                    // and broadcasts.
8333                    IBackupManager bm = IBackupManager.Stub.asInterface(
8334                            ServiceManager.getService(Context.BACKUP_SERVICE));
8335                    if (bm != null) {
8336                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8337                                + " to BM for possible restore");
8338                        try {
8339                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8340                        } catch (RemoteException e) {
8341                            // can't happen; the backup manager is local
8342                        } catch (Exception e) {
8343                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8344                            doRestore = false;
8345                        }
8346                    } else {
8347                        Slog.e(TAG, "Backup Manager not found!");
8348                        doRestore = false;
8349                    }
8350                }
8351
8352                if (!doRestore) {
8353                    // No restore possible, or the Backup Manager was mysteriously not
8354                    // available -- just fire the post-install work request directly.
8355                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8356                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8357                    mHandler.sendMessage(msg);
8358                }
8359            }
8360        });
8361    }
8362
8363    private abstract class HandlerParams {
8364        private static final int MAX_RETRIES = 4;
8365
8366        /**
8367         * Number of times startCopy() has been attempted and had a non-fatal
8368         * error.
8369         */
8370        private int mRetries = 0;
8371
8372        /** User handle for the user requesting the information or installation. */
8373        private final UserHandle mUser;
8374
8375        HandlerParams(UserHandle user) {
8376            mUser = user;
8377        }
8378
8379        UserHandle getUser() {
8380            return mUser;
8381        }
8382
8383        final boolean startCopy() {
8384            boolean res;
8385            try {
8386                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8387
8388                if (++mRetries > MAX_RETRIES) {
8389                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8390                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8391                    handleServiceError();
8392                    return false;
8393                } else {
8394                    handleStartCopy();
8395                    res = true;
8396                }
8397            } catch (RemoteException e) {
8398                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8399                mHandler.sendEmptyMessage(MCS_RECONNECT);
8400                res = false;
8401            }
8402            handleReturnCode();
8403            return res;
8404        }
8405
8406        final void serviceError() {
8407            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8408            handleServiceError();
8409            handleReturnCode();
8410        }
8411
8412        abstract void handleStartCopy() throws RemoteException;
8413        abstract void handleServiceError();
8414        abstract void handleReturnCode();
8415    }
8416
8417    class MeasureParams extends HandlerParams {
8418        private final PackageStats mStats;
8419        private boolean mSuccess;
8420
8421        private final IPackageStatsObserver mObserver;
8422
8423        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8424            super(new UserHandle(stats.userHandle));
8425            mObserver = observer;
8426            mStats = stats;
8427        }
8428
8429        @Override
8430        public String toString() {
8431            return "MeasureParams{"
8432                + Integer.toHexString(System.identityHashCode(this))
8433                + " " + mStats.packageName + "}";
8434        }
8435
8436        @Override
8437        void handleStartCopy() throws RemoteException {
8438            synchronized (mInstallLock) {
8439                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8440            }
8441
8442            if (mSuccess) {
8443                final boolean mounted;
8444                if (Environment.isExternalStorageEmulated()) {
8445                    mounted = true;
8446                } else {
8447                    final String status = Environment.getExternalStorageState();
8448                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8449                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8450                }
8451
8452                if (mounted) {
8453                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8454
8455                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8456                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8457
8458                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8459                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8460
8461                    // Always subtract cache size, since it's a subdirectory
8462                    mStats.externalDataSize -= mStats.externalCacheSize;
8463
8464                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8465                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8466
8467                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8468                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8469                }
8470            }
8471        }
8472
8473        @Override
8474        void handleReturnCode() {
8475            if (mObserver != null) {
8476                try {
8477                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8478                } catch (RemoteException e) {
8479                    Slog.i(TAG, "Observer no longer exists.");
8480                }
8481            }
8482        }
8483
8484        @Override
8485        void handleServiceError() {
8486            Slog.e(TAG, "Could not measure application " + mStats.packageName
8487                            + " external storage");
8488        }
8489    }
8490
8491    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8492            throws RemoteException {
8493        long result = 0;
8494        for (File path : paths) {
8495            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8496        }
8497        return result;
8498    }
8499
8500    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8501        for (File path : paths) {
8502            try {
8503                mcs.clearDirectory(path.getAbsolutePath());
8504            } catch (RemoteException e) {
8505            }
8506        }
8507    }
8508
8509    static class OriginInfo {
8510        /**
8511         * Location where install is coming from, before it has been
8512         * copied/renamed into place. This could be a single monolithic APK
8513         * file, or a cluster directory. This location may be untrusted.
8514         */
8515        final File file;
8516        final String cid;
8517
8518        /**
8519         * Flag indicating that {@link #file} or {@link #cid} has already been
8520         * staged, meaning downstream users don't need to defensively copy the
8521         * contents.
8522         */
8523        final boolean staged;
8524
8525        /**
8526         * Flag indicating that {@link #file} or {@link #cid} is an already
8527         * installed app that is being moved.
8528         */
8529        final boolean existing;
8530
8531        final String resolvedPath;
8532        final File resolvedFile;
8533
8534        static OriginInfo fromNothing() {
8535            return new OriginInfo(null, null, false, false);
8536        }
8537
8538        static OriginInfo fromUntrustedFile(File file) {
8539            return new OriginInfo(file, null, false, false);
8540        }
8541
8542        static OriginInfo fromExistingFile(File file) {
8543            return new OriginInfo(file, null, false, true);
8544        }
8545
8546        static OriginInfo fromStagedFile(File file) {
8547            return new OriginInfo(file, null, true, false);
8548        }
8549
8550        static OriginInfo fromStagedContainer(String cid) {
8551            return new OriginInfo(null, cid, true, false);
8552        }
8553
8554        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8555            this.file = file;
8556            this.cid = cid;
8557            this.staged = staged;
8558            this.existing = existing;
8559
8560            if (cid != null) {
8561                resolvedPath = PackageHelper.getSdDir(cid);
8562                resolvedFile = new File(resolvedPath);
8563            } else if (file != null) {
8564                resolvedPath = file.getAbsolutePath();
8565                resolvedFile = file;
8566            } else {
8567                resolvedPath = null;
8568                resolvedFile = null;
8569            }
8570        }
8571    }
8572
8573    class InstallParams extends HandlerParams {
8574        final OriginInfo origin;
8575        final IPackageInstallObserver2 observer;
8576        int installFlags;
8577        final String installerPackageName;
8578        final VerificationParams verificationParams;
8579        private InstallArgs mArgs;
8580        private int mRet;
8581        final String packageAbiOverride;
8582
8583        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8584                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8585                String packageAbiOverride) {
8586            super(user);
8587            this.origin = origin;
8588            this.observer = observer;
8589            this.installFlags = installFlags;
8590            this.installerPackageName = installerPackageName;
8591            this.verificationParams = verificationParams;
8592            this.packageAbiOverride = packageAbiOverride;
8593        }
8594
8595        @Override
8596        public String toString() {
8597            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8598                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8599        }
8600
8601        public ManifestDigest getManifestDigest() {
8602            if (verificationParams == null) {
8603                return null;
8604            }
8605            return verificationParams.getManifestDigest();
8606        }
8607
8608        private int installLocationPolicy(PackageInfoLite pkgLite) {
8609            String packageName = pkgLite.packageName;
8610            int installLocation = pkgLite.installLocation;
8611            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8612            // reader
8613            synchronized (mPackages) {
8614                PackageParser.Package pkg = mPackages.get(packageName);
8615                if (pkg != null) {
8616                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8617                        // Check for downgrading.
8618                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8619                            if (pkgLite.versionCode < pkg.mVersionCode) {
8620                                Slog.w(TAG, "Can't install update of " + packageName
8621                                        + " update version " + pkgLite.versionCode
8622                                        + " is older than installed version "
8623                                        + pkg.mVersionCode);
8624                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8625                            }
8626                        }
8627                        // Check for updated system application.
8628                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8629                            if (onSd) {
8630                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8631                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8632                            }
8633                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8634                        } else {
8635                            if (onSd) {
8636                                // Install flag overrides everything.
8637                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8638                            }
8639                            // If current upgrade specifies particular preference
8640                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8641                                // Application explicitly specified internal.
8642                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8643                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8644                                // App explictly prefers external. Let policy decide
8645                            } else {
8646                                // Prefer previous location
8647                                if (isExternal(pkg)) {
8648                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8649                                }
8650                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8651                            }
8652                        }
8653                    } else {
8654                        // Invalid install. Return error code
8655                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8656                    }
8657                }
8658            }
8659            // All the special cases have been taken care of.
8660            // Return result based on recommended install location.
8661            if (onSd) {
8662                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8663            }
8664            return pkgLite.recommendedInstallLocation;
8665        }
8666
8667        /*
8668         * Invoke remote method to get package information and install
8669         * location values. Override install location based on default
8670         * policy if needed and then create install arguments based
8671         * on the install location.
8672         */
8673        public void handleStartCopy() throws RemoteException {
8674            int ret = PackageManager.INSTALL_SUCCEEDED;
8675
8676            // If we're already staged, we've firmly committed to an install location
8677            if (origin.staged) {
8678                if (origin.file != null) {
8679                    installFlags |= PackageManager.INSTALL_INTERNAL;
8680                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8681                } else if (origin.cid != null) {
8682                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8683                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8684                } else {
8685                    throw new IllegalStateException("Invalid stage location");
8686                }
8687            }
8688
8689            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8690            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8691
8692            PackageInfoLite pkgLite = null;
8693
8694            if (onInt && onSd) {
8695                // Check if both bits are set.
8696                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8697                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8698            } else {
8699                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8700                        packageAbiOverride);
8701
8702                /*
8703                 * If we have too little free space, try to free cache
8704                 * before giving up.
8705                 */
8706                if (!origin.staged && pkgLite.recommendedInstallLocation
8707                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8708                    // TODO: focus freeing disk space on the target device
8709                    final StorageManager storage = StorageManager.from(mContext);
8710                    final long lowThreshold = storage.getStorageLowBytes(
8711                            Environment.getDataDirectory());
8712
8713                    final long sizeBytes = mContainerService.calculateInstalledSize(
8714                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8715
8716                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8717                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8718                                installFlags, packageAbiOverride);
8719                    }
8720
8721                    /*
8722                     * The cache free must have deleted the file we
8723                     * downloaded to install.
8724                     *
8725                     * TODO: fix the "freeCache" call to not delete
8726                     *       the file we care about.
8727                     */
8728                    if (pkgLite.recommendedInstallLocation
8729                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8730                        pkgLite.recommendedInstallLocation
8731                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8732                    }
8733                }
8734            }
8735
8736            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8737                int loc = pkgLite.recommendedInstallLocation;
8738                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8739                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8740                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8741                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8742                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8743                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8744                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8745                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8746                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8747                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8748                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8749                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8750                } else {
8751                    // Override with defaults if needed.
8752                    loc = installLocationPolicy(pkgLite);
8753                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8754                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8755                    } else if (!onSd && !onInt) {
8756                        // Override install location with flags
8757                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8758                            // Set the flag to install on external media.
8759                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8760                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8761                        } else {
8762                            // Make sure the flag for installing on external
8763                            // media is unset
8764                            installFlags |= PackageManager.INSTALL_INTERNAL;
8765                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8766                        }
8767                    }
8768                }
8769            }
8770
8771            final InstallArgs args = createInstallArgs(this);
8772            mArgs = args;
8773
8774            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8775                 /*
8776                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8777                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8778                 */
8779                int userIdentifier = getUser().getIdentifier();
8780                if (userIdentifier == UserHandle.USER_ALL
8781                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8782                    userIdentifier = UserHandle.USER_OWNER;
8783                }
8784
8785                /*
8786                 * Determine if we have any installed package verifiers. If we
8787                 * do, then we'll defer to them to verify the packages.
8788                 */
8789                final int requiredUid = mRequiredVerifierPackage == null ? -1
8790                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8791                if (!origin.existing && requiredUid != -1
8792                        && isVerificationEnabled(userIdentifier, installFlags)) {
8793                    final Intent verification = new Intent(
8794                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8795                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8796                            PACKAGE_MIME_TYPE);
8797                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8798
8799                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8800                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8801                            0 /* TODO: Which userId? */);
8802
8803                    if (DEBUG_VERIFY) {
8804                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8805                                + verification.toString() + " with " + pkgLite.verifiers.length
8806                                + " optional verifiers");
8807                    }
8808
8809                    final int verificationId = mPendingVerificationToken++;
8810
8811                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8812
8813                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8814                            installerPackageName);
8815
8816                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8817                            installFlags);
8818
8819                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8820                            pkgLite.packageName);
8821
8822                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8823                            pkgLite.versionCode);
8824
8825                    if (verificationParams != null) {
8826                        if (verificationParams.getVerificationURI() != null) {
8827                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8828                                 verificationParams.getVerificationURI());
8829                        }
8830                        if (verificationParams.getOriginatingURI() != null) {
8831                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8832                                  verificationParams.getOriginatingURI());
8833                        }
8834                        if (verificationParams.getReferrer() != null) {
8835                            verification.putExtra(Intent.EXTRA_REFERRER,
8836                                  verificationParams.getReferrer());
8837                        }
8838                        if (verificationParams.getOriginatingUid() >= 0) {
8839                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8840                                  verificationParams.getOriginatingUid());
8841                        }
8842                        if (verificationParams.getInstallerUid() >= 0) {
8843                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8844                                  verificationParams.getInstallerUid());
8845                        }
8846                    }
8847
8848                    final PackageVerificationState verificationState = new PackageVerificationState(
8849                            requiredUid, args);
8850
8851                    mPendingVerification.append(verificationId, verificationState);
8852
8853                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8854                            receivers, verificationState);
8855
8856                    /*
8857                     * If any sufficient verifiers were listed in the package
8858                     * manifest, attempt to ask them.
8859                     */
8860                    if (sufficientVerifiers != null) {
8861                        final int N = sufficientVerifiers.size();
8862                        if (N == 0) {
8863                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8864                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8865                        } else {
8866                            for (int i = 0; i < N; i++) {
8867                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8868
8869                                final Intent sufficientIntent = new Intent(verification);
8870                                sufficientIntent.setComponent(verifierComponent);
8871
8872                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8873                            }
8874                        }
8875                    }
8876
8877                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8878                            mRequiredVerifierPackage, receivers);
8879                    if (ret == PackageManager.INSTALL_SUCCEEDED
8880                            && mRequiredVerifierPackage != null) {
8881                        /*
8882                         * Send the intent to the required verification agent,
8883                         * but only start the verification timeout after the
8884                         * target BroadcastReceivers have run.
8885                         */
8886                        verification.setComponent(requiredVerifierComponent);
8887                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8888                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8889                                new BroadcastReceiver() {
8890                                    @Override
8891                                    public void onReceive(Context context, Intent intent) {
8892                                        final Message msg = mHandler
8893                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8894                                        msg.arg1 = verificationId;
8895                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8896                                    }
8897                                }, null, 0, null, null);
8898
8899                        /*
8900                         * We don't want the copy to proceed until verification
8901                         * succeeds, so null out this field.
8902                         */
8903                        mArgs = null;
8904                    }
8905                } else {
8906                    /*
8907                     * No package verification is enabled, so immediately start
8908                     * the remote call to initiate copy using temporary file.
8909                     */
8910                    ret = args.copyApk(mContainerService, true);
8911                }
8912            }
8913
8914            mRet = ret;
8915        }
8916
8917        @Override
8918        void handleReturnCode() {
8919            // If mArgs is null, then MCS couldn't be reached. When it
8920            // reconnects, it will try again to install. At that point, this
8921            // will succeed.
8922            if (mArgs != null) {
8923                processPendingInstall(mArgs, mRet);
8924            }
8925        }
8926
8927        @Override
8928        void handleServiceError() {
8929            mArgs = createInstallArgs(this);
8930            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8931        }
8932
8933        public boolean isForwardLocked() {
8934            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8935        }
8936    }
8937
8938    /**
8939     * Used during creation of InstallArgs
8940     *
8941     * @param installFlags package installation flags
8942     * @return true if should be installed on external storage
8943     */
8944    private static boolean installOnSd(int installFlags) {
8945        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8946            return false;
8947        }
8948        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8949            return true;
8950        }
8951        return false;
8952    }
8953
8954    /**
8955     * Used during creation of InstallArgs
8956     *
8957     * @param installFlags package installation flags
8958     * @return true if should be installed as forward locked
8959     */
8960    private static boolean installForwardLocked(int installFlags) {
8961        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8962    }
8963
8964    private InstallArgs createInstallArgs(InstallParams params) {
8965        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8966            return new AsecInstallArgs(params);
8967        } else {
8968            return new FileInstallArgs(params);
8969        }
8970    }
8971
8972    /**
8973     * Create args that describe an existing installed package. Typically used
8974     * when cleaning up old installs, or used as a move source.
8975     */
8976    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8977            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8978        final boolean isInAsec;
8979        if (installOnSd(installFlags)) {
8980            /* Apps on SD card are always in ASEC containers. */
8981            isInAsec = true;
8982        } else if (installForwardLocked(installFlags)
8983                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8984            /*
8985             * Forward-locked apps are only in ASEC containers if they're the
8986             * new style
8987             */
8988            isInAsec = true;
8989        } else {
8990            isInAsec = false;
8991        }
8992
8993        if (isInAsec) {
8994            return new AsecInstallArgs(codePath, instructionSets,
8995                    installOnSd(installFlags), installForwardLocked(installFlags));
8996        } else {
8997            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8998                    instructionSets);
8999        }
9000    }
9001
9002    static abstract class InstallArgs {
9003        /** @see InstallParams#origin */
9004        final OriginInfo origin;
9005
9006        final IPackageInstallObserver2 observer;
9007        // Always refers to PackageManager flags only
9008        final int installFlags;
9009        final String installerPackageName;
9010        final ManifestDigest manifestDigest;
9011        final UserHandle user;
9012        final String abiOverride;
9013
9014        // The list of instruction sets supported by this app. This is currently
9015        // only used during the rmdex() phase to clean up resources. We can get rid of this
9016        // if we move dex files under the common app path.
9017        /* nullable */ String[] instructionSets;
9018
9019        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9020                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9021                String[] instructionSets, String abiOverride) {
9022            this.origin = origin;
9023            this.installFlags = installFlags;
9024            this.observer = observer;
9025            this.installerPackageName = installerPackageName;
9026            this.manifestDigest = manifestDigest;
9027            this.user = user;
9028            this.instructionSets = instructionSets;
9029            this.abiOverride = abiOverride;
9030        }
9031
9032        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9033        abstract int doPreInstall(int status);
9034
9035        /**
9036         * Rename package into final resting place. All paths on the given
9037         * scanned package should be updated to reflect the rename.
9038         */
9039        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9040        abstract int doPostInstall(int status, int uid);
9041
9042        /** @see PackageSettingBase#codePathString */
9043        abstract String getCodePath();
9044        /** @see PackageSettingBase#resourcePathString */
9045        abstract String getResourcePath();
9046        abstract String getLegacyNativeLibraryPath();
9047
9048        // Need installer lock especially for dex file removal.
9049        abstract void cleanUpResourcesLI();
9050        abstract boolean doPostDeleteLI(boolean delete);
9051        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9052
9053        /**
9054         * Called before the source arguments are copied. This is used mostly
9055         * for MoveParams when it needs to read the source file to put it in the
9056         * destination.
9057         */
9058        int doPreCopy() {
9059            return PackageManager.INSTALL_SUCCEEDED;
9060        }
9061
9062        /**
9063         * Called after the source arguments are copied. This is used mostly for
9064         * MoveParams when it needs to read the source file to put it in the
9065         * destination.
9066         *
9067         * @return
9068         */
9069        int doPostCopy(int uid) {
9070            return PackageManager.INSTALL_SUCCEEDED;
9071        }
9072
9073        protected boolean isFwdLocked() {
9074            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9075        }
9076
9077        protected boolean isExternal() {
9078            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9079        }
9080
9081        UserHandle getUser() {
9082            return user;
9083        }
9084    }
9085
9086    /**
9087     * Logic to handle installation of non-ASEC applications, including copying
9088     * and renaming logic.
9089     */
9090    class FileInstallArgs extends InstallArgs {
9091        private File codeFile;
9092        private File resourceFile;
9093        private File legacyNativeLibraryPath;
9094
9095        // Example topology:
9096        // /data/app/com.example/base.apk
9097        // /data/app/com.example/split_foo.apk
9098        // /data/app/com.example/lib/arm/libfoo.so
9099        // /data/app/com.example/lib/arm64/libfoo.so
9100        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9101
9102        /** New install */
9103        FileInstallArgs(InstallParams params) {
9104            super(params.origin, params.observer, params.installFlags,
9105                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9106                    null /* instruction sets */, params.packageAbiOverride);
9107            if (isFwdLocked()) {
9108                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9109            }
9110        }
9111
9112        /** Existing install */
9113        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9114                String[] instructionSets) {
9115            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9116            this.codeFile = (codePath != null) ? new File(codePath) : null;
9117            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9118            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9119                    new File(legacyNativeLibraryPath) : null;
9120        }
9121
9122        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9123            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9124                    isFwdLocked(), abiOverride);
9125
9126            final StorageManager storage = StorageManager.from(mContext);
9127            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9128        }
9129
9130        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9131            if (origin.staged) {
9132                Slog.d(TAG, origin.file + " already staged; skipping copy");
9133                codeFile = origin.file;
9134                resourceFile = origin.file;
9135                return PackageManager.INSTALL_SUCCEEDED;
9136            }
9137
9138            try {
9139                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9140                codeFile = tempDir;
9141                resourceFile = tempDir;
9142            } catch (IOException e) {
9143                Slog.w(TAG, "Failed to create copy file: " + e);
9144                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9145            }
9146
9147            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9148                @Override
9149                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9150                    if (!FileUtils.isValidExtFilename(name)) {
9151                        throw new IllegalArgumentException("Invalid filename: " + name);
9152                    }
9153                    try {
9154                        final File file = new File(codeFile, name);
9155                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9156                                O_RDWR | O_CREAT, 0644);
9157                        Os.chmod(file.getAbsolutePath(), 0644);
9158                        return new ParcelFileDescriptor(fd);
9159                    } catch (ErrnoException e) {
9160                        throw new RemoteException("Failed to open: " + e.getMessage());
9161                    }
9162                }
9163            };
9164
9165            int ret = PackageManager.INSTALL_SUCCEEDED;
9166            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9167            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9168                Slog.e(TAG, "Failed to copy package");
9169                return ret;
9170            }
9171
9172            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9173            NativeLibraryHelper.Handle handle = null;
9174            try {
9175                handle = NativeLibraryHelper.Handle.create(codeFile);
9176                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9177                        abiOverride);
9178            } catch (IOException e) {
9179                Slog.e(TAG, "Copying native libraries failed", e);
9180                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9181            } finally {
9182                IoUtils.closeQuietly(handle);
9183            }
9184
9185            return ret;
9186        }
9187
9188        int doPreInstall(int status) {
9189            if (status != PackageManager.INSTALL_SUCCEEDED) {
9190                cleanUp();
9191            }
9192            return status;
9193        }
9194
9195        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9196            if (status != PackageManager.INSTALL_SUCCEEDED) {
9197                cleanUp();
9198                return false;
9199            } else {
9200                final File beforeCodeFile = codeFile;
9201                final File afterCodeFile = getNextCodePath(pkg.packageName);
9202
9203                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9204                try {
9205                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9206                } catch (ErrnoException e) {
9207                    Slog.d(TAG, "Failed to rename", e);
9208                    return false;
9209                }
9210
9211                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9212                    Slog.d(TAG, "Failed to restorecon");
9213                    return false;
9214                }
9215
9216                // Reflect the rename internally
9217                codeFile = afterCodeFile;
9218                resourceFile = afterCodeFile;
9219
9220                // Reflect the rename in scanned details
9221                pkg.codePath = afterCodeFile.getAbsolutePath();
9222                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9223                        pkg.baseCodePath);
9224                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9225                        pkg.splitCodePaths);
9226
9227                // Reflect the rename in app info
9228                pkg.applicationInfo.setCodePath(pkg.codePath);
9229                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9230                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9231                pkg.applicationInfo.setResourcePath(pkg.codePath);
9232                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9233                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9234
9235                return true;
9236            }
9237        }
9238
9239        int doPostInstall(int status, int uid) {
9240            if (status != PackageManager.INSTALL_SUCCEEDED) {
9241                cleanUp();
9242            }
9243            return status;
9244        }
9245
9246        @Override
9247        String getCodePath() {
9248            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9249        }
9250
9251        @Override
9252        String getResourcePath() {
9253            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9254        }
9255
9256        @Override
9257        String getLegacyNativeLibraryPath() {
9258            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9259        }
9260
9261        private boolean cleanUp() {
9262            if (codeFile == null || !codeFile.exists()) {
9263                return false;
9264            }
9265
9266            if (codeFile.isDirectory()) {
9267                FileUtils.deleteContents(codeFile);
9268            }
9269            codeFile.delete();
9270
9271            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9272                resourceFile.delete();
9273            }
9274
9275            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9276                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9277                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9278                }
9279                legacyNativeLibraryPath.delete();
9280            }
9281
9282            return true;
9283        }
9284
9285        void cleanUpResourcesLI() {
9286            // Try enumerating all code paths before deleting
9287            List<String> allCodePaths = Collections.EMPTY_LIST;
9288            if (codeFile != null && codeFile.exists()) {
9289                try {
9290                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9291                    allCodePaths = pkg.getAllCodePaths();
9292                } catch (PackageParserException e) {
9293                    // Ignored; we tried our best
9294                }
9295            }
9296
9297            cleanUp();
9298
9299            if (!allCodePaths.isEmpty()) {
9300                if (instructionSets == null) {
9301                    throw new IllegalStateException("instructionSet == null");
9302                }
9303                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9304                for (String codePath : allCodePaths) {
9305                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9306                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9307                        if (retCode < 0) {
9308                            Slog.w(TAG, "Couldn't remove dex file for package: "
9309                                    + " at location " + codePath + ", retcode=" + retCode);
9310                            // we don't consider this to be a failure of the core package deletion
9311                        }
9312                    }
9313                }
9314            }
9315        }
9316
9317        boolean doPostDeleteLI(boolean delete) {
9318            // XXX err, shouldn't we respect the delete flag?
9319            cleanUpResourcesLI();
9320            return true;
9321        }
9322    }
9323
9324    private boolean isAsecExternal(String cid) {
9325        final String asecPath = PackageHelper.getSdFilesystem(cid);
9326        return !asecPath.startsWith(mAsecInternalPath);
9327    }
9328
9329    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9330            PackageManagerException {
9331        if (copyRet < 0) {
9332            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9333                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9334                throw new PackageManagerException(copyRet, message);
9335            }
9336        }
9337    }
9338
9339    /**
9340     * Extract the MountService "container ID" from the full code path of an
9341     * .apk.
9342     */
9343    static String cidFromCodePath(String fullCodePath) {
9344        int eidx = fullCodePath.lastIndexOf("/");
9345        String subStr1 = fullCodePath.substring(0, eidx);
9346        int sidx = subStr1.lastIndexOf("/");
9347        return subStr1.substring(sidx+1, eidx);
9348    }
9349
9350    /**
9351     * Logic to handle installation of ASEC applications, including copying and
9352     * renaming logic.
9353     */
9354    class AsecInstallArgs extends InstallArgs {
9355        static final String RES_FILE_NAME = "pkg.apk";
9356        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9357
9358        String cid;
9359        String packagePath;
9360        String resourcePath;
9361        String legacyNativeLibraryDir;
9362
9363        /** New install */
9364        AsecInstallArgs(InstallParams params) {
9365            super(params.origin, params.observer, params.installFlags,
9366                    params.installerPackageName, params.getManifestDigest(),
9367                    params.getUser(), null /* instruction sets */,
9368                    params.packageAbiOverride);
9369        }
9370
9371        /** Existing install */
9372        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9373                        boolean isExternal, boolean isForwardLocked) {
9374            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9375                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9376                    instructionSets, null);
9377            // Hackily pretend we're still looking at a full code path
9378            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9379                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9380            }
9381
9382            // Extract cid from fullCodePath
9383            int eidx = fullCodePath.lastIndexOf("/");
9384            String subStr1 = fullCodePath.substring(0, eidx);
9385            int sidx = subStr1.lastIndexOf("/");
9386            cid = subStr1.substring(sidx+1, eidx);
9387            setMountPath(subStr1);
9388        }
9389
9390        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9391            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9392                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9393                    instructionSets, null);
9394            this.cid = cid;
9395            setMountPath(PackageHelper.getSdDir(cid));
9396        }
9397
9398        void createCopyFile() {
9399            cid = mInstallerService.allocateExternalStageCidLegacy();
9400        }
9401
9402        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9403            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9404                    abiOverride);
9405
9406            final File target;
9407            if (isExternal()) {
9408                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9409            } else {
9410                target = Environment.getDataDirectory();
9411            }
9412
9413            final StorageManager storage = StorageManager.from(mContext);
9414            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9415        }
9416
9417        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9418            if (origin.staged) {
9419                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9420                cid = origin.cid;
9421                setMountPath(PackageHelper.getSdDir(cid));
9422                return PackageManager.INSTALL_SUCCEEDED;
9423            }
9424
9425            if (temp) {
9426                createCopyFile();
9427            } else {
9428                /*
9429                 * Pre-emptively destroy the container since it's destroyed if
9430                 * copying fails due to it existing anyway.
9431                 */
9432                PackageHelper.destroySdDir(cid);
9433            }
9434
9435            final String newMountPath = imcs.copyPackageToContainer(
9436                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9437                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9438
9439            if (newMountPath != null) {
9440                setMountPath(newMountPath);
9441                return PackageManager.INSTALL_SUCCEEDED;
9442            } else {
9443                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9444            }
9445        }
9446
9447        @Override
9448        String getCodePath() {
9449            return packagePath;
9450        }
9451
9452        @Override
9453        String getResourcePath() {
9454            return resourcePath;
9455        }
9456
9457        @Override
9458        String getLegacyNativeLibraryPath() {
9459            return legacyNativeLibraryDir;
9460        }
9461
9462        int doPreInstall(int status) {
9463            if (status != PackageManager.INSTALL_SUCCEEDED) {
9464                // Destroy container
9465                PackageHelper.destroySdDir(cid);
9466            } else {
9467                boolean mounted = PackageHelper.isContainerMounted(cid);
9468                if (!mounted) {
9469                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9470                            Process.SYSTEM_UID);
9471                    if (newMountPath != null) {
9472                        setMountPath(newMountPath);
9473                    } else {
9474                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9475                    }
9476                }
9477            }
9478            return status;
9479        }
9480
9481        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9482            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9483            String newMountPath = null;
9484            if (PackageHelper.isContainerMounted(cid)) {
9485                // Unmount the container
9486                if (!PackageHelper.unMountSdDir(cid)) {
9487                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9488                    return false;
9489                }
9490            }
9491            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9492                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9493                        " which might be stale. Will try to clean up.");
9494                // Clean up the stale container and proceed to recreate.
9495                if (!PackageHelper.destroySdDir(newCacheId)) {
9496                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9497                    return false;
9498                }
9499                // Successfully cleaned up stale container. Try to rename again.
9500                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9501                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9502                            + " inspite of cleaning it up.");
9503                    return false;
9504                }
9505            }
9506            if (!PackageHelper.isContainerMounted(newCacheId)) {
9507                Slog.w(TAG, "Mounting container " + newCacheId);
9508                newMountPath = PackageHelper.mountSdDir(newCacheId,
9509                        getEncryptKey(), Process.SYSTEM_UID);
9510            } else {
9511                newMountPath = PackageHelper.getSdDir(newCacheId);
9512            }
9513            if (newMountPath == null) {
9514                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9515                return false;
9516            }
9517            Log.i(TAG, "Succesfully renamed " + cid +
9518                    " to " + newCacheId +
9519                    " at new path: " + newMountPath);
9520            cid = newCacheId;
9521
9522            final File beforeCodeFile = new File(packagePath);
9523            setMountPath(newMountPath);
9524            final File afterCodeFile = new File(packagePath);
9525
9526            // Reflect the rename in scanned details
9527            pkg.codePath = afterCodeFile.getAbsolutePath();
9528            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9529                    pkg.baseCodePath);
9530            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9531                    pkg.splitCodePaths);
9532
9533            // Reflect the rename in app info
9534            pkg.applicationInfo.setCodePath(pkg.codePath);
9535            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9536            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9537            pkg.applicationInfo.setResourcePath(pkg.codePath);
9538            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9539            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9540
9541            return true;
9542        }
9543
9544        private void setMountPath(String mountPath) {
9545            final File mountFile = new File(mountPath);
9546
9547            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9548            if (monolithicFile.exists()) {
9549                packagePath = monolithicFile.getAbsolutePath();
9550                if (isFwdLocked()) {
9551                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9552                } else {
9553                    resourcePath = packagePath;
9554                }
9555            } else {
9556                packagePath = mountFile.getAbsolutePath();
9557                resourcePath = packagePath;
9558            }
9559
9560            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9561        }
9562
9563        int doPostInstall(int status, int uid) {
9564            if (status != PackageManager.INSTALL_SUCCEEDED) {
9565                cleanUp();
9566            } else {
9567                final int groupOwner;
9568                final String protectedFile;
9569                if (isFwdLocked()) {
9570                    groupOwner = UserHandle.getSharedAppGid(uid);
9571                    protectedFile = RES_FILE_NAME;
9572                } else {
9573                    groupOwner = -1;
9574                    protectedFile = null;
9575                }
9576
9577                if (uid < Process.FIRST_APPLICATION_UID
9578                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9579                    Slog.e(TAG, "Failed to finalize " + cid);
9580                    PackageHelper.destroySdDir(cid);
9581                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9582                }
9583
9584                boolean mounted = PackageHelper.isContainerMounted(cid);
9585                if (!mounted) {
9586                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9587                }
9588            }
9589            return status;
9590        }
9591
9592        private void cleanUp() {
9593            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9594
9595            // Destroy secure container
9596            PackageHelper.destroySdDir(cid);
9597        }
9598
9599        private List<String> getAllCodePaths() {
9600            final File codeFile = new File(getCodePath());
9601            if (codeFile != null && codeFile.exists()) {
9602                try {
9603                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9604                    return pkg.getAllCodePaths();
9605                } catch (PackageParserException e) {
9606                    // Ignored; we tried our best
9607                }
9608            }
9609            return Collections.EMPTY_LIST;
9610        }
9611
9612        void cleanUpResourcesLI() {
9613            // Enumerate all code paths before deleting
9614            cleanUpResourcesLI(getAllCodePaths());
9615        }
9616
9617        private void cleanUpResourcesLI(List<String> allCodePaths) {
9618            cleanUp();
9619
9620            if (!allCodePaths.isEmpty()) {
9621                if (instructionSets == null) {
9622                    throw new IllegalStateException("instructionSet == null");
9623                }
9624                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9625                for (String codePath : allCodePaths) {
9626                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9627                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9628                        if (retCode < 0) {
9629                            Slog.w(TAG, "Couldn't remove dex file for package: "
9630                                    + " at location " + codePath + ", retcode=" + retCode);
9631                            // we don't consider this to be a failure of the core package deletion
9632                        }
9633                    }
9634                }
9635            }
9636        }
9637
9638        boolean matchContainer(String app) {
9639            if (cid.startsWith(app)) {
9640                return true;
9641            }
9642            return false;
9643        }
9644
9645        String getPackageName() {
9646            return getAsecPackageName(cid);
9647        }
9648
9649        boolean doPostDeleteLI(boolean delete) {
9650            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9651            final List<String> allCodePaths = getAllCodePaths();
9652            boolean mounted = PackageHelper.isContainerMounted(cid);
9653            if (mounted) {
9654                // Unmount first
9655                if (PackageHelper.unMountSdDir(cid)) {
9656                    mounted = false;
9657                }
9658            }
9659            if (!mounted && delete) {
9660                cleanUpResourcesLI(allCodePaths);
9661            }
9662            return !mounted;
9663        }
9664
9665        @Override
9666        int doPreCopy() {
9667            if (isFwdLocked()) {
9668                if (!PackageHelper.fixSdPermissions(cid,
9669                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9670                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9671                }
9672            }
9673
9674            return PackageManager.INSTALL_SUCCEEDED;
9675        }
9676
9677        @Override
9678        int doPostCopy(int uid) {
9679            if (isFwdLocked()) {
9680                if (uid < Process.FIRST_APPLICATION_UID
9681                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9682                                RES_FILE_NAME)) {
9683                    Slog.e(TAG, "Failed to finalize " + cid);
9684                    PackageHelper.destroySdDir(cid);
9685                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9686                }
9687            }
9688
9689            return PackageManager.INSTALL_SUCCEEDED;
9690        }
9691    }
9692
9693    static String getAsecPackageName(String packageCid) {
9694        int idx = packageCid.lastIndexOf("-");
9695        if (idx == -1) {
9696            return packageCid;
9697        }
9698        return packageCid.substring(0, idx);
9699    }
9700
9701    // Utility method used to create code paths based on package name and available index.
9702    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9703        String idxStr = "";
9704        int idx = 1;
9705        // Fall back to default value of idx=1 if prefix is not
9706        // part of oldCodePath
9707        if (oldCodePath != null) {
9708            String subStr = oldCodePath;
9709            // Drop the suffix right away
9710            if (suffix != null && subStr.endsWith(suffix)) {
9711                subStr = subStr.substring(0, subStr.length() - suffix.length());
9712            }
9713            // If oldCodePath already contains prefix find out the
9714            // ending index to either increment or decrement.
9715            int sidx = subStr.lastIndexOf(prefix);
9716            if (sidx != -1) {
9717                subStr = subStr.substring(sidx + prefix.length());
9718                if (subStr != null) {
9719                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9720                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9721                    }
9722                    try {
9723                        idx = Integer.parseInt(subStr);
9724                        if (idx <= 1) {
9725                            idx++;
9726                        } else {
9727                            idx--;
9728                        }
9729                    } catch(NumberFormatException e) {
9730                    }
9731                }
9732            }
9733        }
9734        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9735        return prefix + idxStr;
9736    }
9737
9738    private File getNextCodePath(String packageName) {
9739        int suffix = 1;
9740        File result;
9741        do {
9742            result = new File(mAppInstallDir, packageName + "-" + suffix);
9743            suffix++;
9744        } while (result.exists());
9745        return result;
9746    }
9747
9748    // Utility method used to ignore ADD/REMOVE events
9749    // by directory observer.
9750    private static boolean ignoreCodePath(String fullPathStr) {
9751        String apkName = deriveCodePathName(fullPathStr);
9752        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9753        if (idx != -1 && ((idx+1) < apkName.length())) {
9754            // Make sure the package ends with a numeral
9755            String version = apkName.substring(idx+1);
9756            try {
9757                Integer.parseInt(version);
9758                return true;
9759            } catch (NumberFormatException e) {}
9760        }
9761        return false;
9762    }
9763
9764    // Utility method that returns the relative package path with respect
9765    // to the installation directory. Like say for /data/data/com.test-1.apk
9766    // string com.test-1 is returned.
9767    static String deriveCodePathName(String codePath) {
9768        if (codePath == null) {
9769            return null;
9770        }
9771        final File codeFile = new File(codePath);
9772        final String name = codeFile.getName();
9773        if (codeFile.isDirectory()) {
9774            return name;
9775        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9776            final int lastDot = name.lastIndexOf('.');
9777            return name.substring(0, lastDot);
9778        } else {
9779            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9780            return null;
9781        }
9782    }
9783
9784    class PackageInstalledInfo {
9785        String name;
9786        int uid;
9787        // The set of users that originally had this package installed.
9788        int[] origUsers;
9789        // The set of users that now have this package installed.
9790        int[] newUsers;
9791        PackageParser.Package pkg;
9792        int returnCode;
9793        String returnMsg;
9794        PackageRemovedInfo removedInfo;
9795
9796        public void setError(int code, String msg) {
9797            returnCode = code;
9798            returnMsg = msg;
9799            Slog.w(TAG, msg);
9800        }
9801
9802        public void setError(String msg, PackageParserException e) {
9803            returnCode = e.error;
9804            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9805            Slog.w(TAG, msg, e);
9806        }
9807
9808        public void setError(String msg, PackageManagerException e) {
9809            returnCode = e.error;
9810            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9811            Slog.w(TAG, msg, e);
9812        }
9813
9814        // In some error cases we want to convey more info back to the observer
9815        String origPackage;
9816        String origPermission;
9817    }
9818
9819    /*
9820     * Install a non-existing package.
9821     */
9822    private void installNewPackageLI(PackageParser.Package pkg,
9823            int parseFlags, int scanFlags, UserHandle user,
9824            String installerPackageName, PackageInstalledInfo res) {
9825        // Remember this for later, in case we need to rollback this install
9826        String pkgName = pkg.packageName;
9827
9828        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9829        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9830        synchronized(mPackages) {
9831            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9832                // A package with the same name is already installed, though
9833                // it has been renamed to an older name.  The package we
9834                // are trying to install should be installed as an update to
9835                // the existing one, but that has not been requested, so bail.
9836                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9837                        + " without first uninstalling package running as "
9838                        + mSettings.mRenamedPackages.get(pkgName));
9839                return;
9840            }
9841            if (mPackages.containsKey(pkgName)) {
9842                // Don't allow installation over an existing package with the same name.
9843                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9844                        + " without first uninstalling.");
9845                return;
9846            }
9847        }
9848
9849        try {
9850            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9851                    System.currentTimeMillis(), user);
9852
9853            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9854            // delete the partially installed application. the data directory will have to be
9855            // restored if it was already existing
9856            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9857                // remove package from internal structures.  Note that we want deletePackageX to
9858                // delete the package data and cache directories that it created in
9859                // scanPackageLocked, unless those directories existed before we even tried to
9860                // install.
9861                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9862                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9863                                res.removedInfo, true);
9864            }
9865
9866        } catch (PackageManagerException e) {
9867            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9868        }
9869    }
9870
9871    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9872        // Upgrade keysets are being used.  Determine if new package has a superset of the
9873        // required keys.
9874        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9875        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9876        for (int i = 0; i < upgradeKeySets.length; i++) {
9877            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9878            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9879                return true;
9880            }
9881        }
9882        return false;
9883    }
9884
9885    private void replacePackageLI(PackageParser.Package pkg,
9886            int parseFlags, int scanFlags, UserHandle user,
9887            String installerPackageName, PackageInstalledInfo res) {
9888        PackageParser.Package oldPackage;
9889        String pkgName = pkg.packageName;
9890        int[] allUsers;
9891        boolean[] perUserInstalled;
9892
9893        // First find the old package info and check signatures
9894        synchronized(mPackages) {
9895            oldPackage = mPackages.get(pkgName);
9896            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9897            PackageSetting ps = mSettings.mPackages.get(pkgName);
9898            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9899                // default to original signature matching
9900                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9901                    != PackageManager.SIGNATURE_MATCH) {
9902                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9903                            "New package has a different signature: " + pkgName);
9904                    return;
9905                }
9906            } else {
9907                if(!checkUpgradeKeySetLP(ps, pkg)) {
9908                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9909                            "New package not signed by keys specified by upgrade-keysets: "
9910                            + pkgName);
9911                    return;
9912                }
9913            }
9914
9915            // In case of rollback, remember per-user/profile install state
9916            allUsers = sUserManager.getUserIds();
9917            perUserInstalled = new boolean[allUsers.length];
9918            for (int i = 0; i < allUsers.length; i++) {
9919                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9920            }
9921        }
9922
9923        boolean sysPkg = (isSystemApp(oldPackage));
9924        if (sysPkg) {
9925            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9926                    user, allUsers, perUserInstalled, installerPackageName, res);
9927        } else {
9928            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9929                    user, allUsers, perUserInstalled, installerPackageName, res);
9930        }
9931    }
9932
9933    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9934            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9935            int[] allUsers, boolean[] perUserInstalled,
9936            String installerPackageName, PackageInstalledInfo res) {
9937        String pkgName = deletedPackage.packageName;
9938        boolean deletedPkg = true;
9939        boolean updatedSettings = false;
9940
9941        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9942                + deletedPackage);
9943        long origUpdateTime;
9944        if (pkg.mExtras != null) {
9945            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9946        } else {
9947            origUpdateTime = 0;
9948        }
9949
9950        // First delete the existing package while retaining the data directory
9951        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9952                res.removedInfo, true)) {
9953            // If the existing package wasn't successfully deleted
9954            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9955            deletedPkg = false;
9956        } else {
9957            // Successfully deleted the old package; proceed with replace.
9958
9959            // If deleted package lived in a container, give users a chance to
9960            // relinquish resources before killing.
9961            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9962                if (DEBUG_INSTALL) {
9963                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9964                }
9965                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9966                final ArrayList<String> pkgList = new ArrayList<String>(1);
9967                pkgList.add(deletedPackage.applicationInfo.packageName);
9968                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9969            }
9970
9971            deleteCodeCacheDirsLI(pkgName);
9972            try {
9973                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9974                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9975                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9976                updatedSettings = true;
9977            } catch (PackageManagerException e) {
9978                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9979            }
9980        }
9981
9982        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9983            // remove package from internal structures.  Note that we want deletePackageX to
9984            // delete the package data and cache directories that it created in
9985            // scanPackageLocked, unless those directories existed before we even tried to
9986            // install.
9987            if(updatedSettings) {
9988                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9989                deletePackageLI(
9990                        pkgName, null, true, allUsers, perUserInstalled,
9991                        PackageManager.DELETE_KEEP_DATA,
9992                                res.removedInfo, true);
9993            }
9994            // Since we failed to install the new package we need to restore the old
9995            // package that we deleted.
9996            if (deletedPkg) {
9997                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9998                File restoreFile = new File(deletedPackage.codePath);
9999                // Parse old package
10000                boolean oldOnSd = isExternal(deletedPackage);
10001                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10002                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10003                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10004                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10005                try {
10006                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10007                } catch (PackageManagerException e) {
10008                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10009                            + e.getMessage());
10010                    return;
10011                }
10012                // Restore of old package succeeded. Update permissions.
10013                // writer
10014                synchronized (mPackages) {
10015                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10016                            UPDATE_PERMISSIONS_ALL);
10017                    // can downgrade to reader
10018                    mSettings.writeLPr();
10019                }
10020                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10021            }
10022        }
10023    }
10024
10025    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10026            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10027            int[] allUsers, boolean[] perUserInstalled,
10028            String installerPackageName, PackageInstalledInfo res) {
10029        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10030                + ", old=" + deletedPackage);
10031        boolean updatedSettings = false;
10032        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10033        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10034            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10035        }
10036        String packageName = deletedPackage.packageName;
10037        if (packageName == null) {
10038            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10039                    "Attempt to delete null packageName.");
10040            return;
10041        }
10042        PackageParser.Package oldPkg;
10043        PackageSetting oldPkgSetting;
10044        // reader
10045        synchronized (mPackages) {
10046            oldPkg = mPackages.get(packageName);
10047            oldPkgSetting = mSettings.mPackages.get(packageName);
10048            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10049                    (oldPkgSetting == null)) {
10050                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10051                        "Couldn't find package:" + packageName + " information");
10052                return;
10053            }
10054        }
10055
10056        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10057
10058        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10059        res.removedInfo.removedPackage = packageName;
10060        // Remove existing system package
10061        removePackageLI(oldPkgSetting, true);
10062        // writer
10063        synchronized (mPackages) {
10064            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10065                // We didn't need to disable the .apk as a current system package,
10066                // which means we are replacing another update that is already
10067                // installed.  We need to make sure to delete the older one's .apk.
10068                res.removedInfo.args = createInstallArgsForExisting(0,
10069                        deletedPackage.applicationInfo.getCodePath(),
10070                        deletedPackage.applicationInfo.getResourcePath(),
10071                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10072                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10073            } else {
10074                res.removedInfo.args = null;
10075            }
10076        }
10077
10078        // Successfully disabled the old package. Now proceed with re-installation
10079        deleteCodeCacheDirsLI(packageName);
10080
10081        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10082        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10083
10084        PackageParser.Package newPackage = null;
10085        try {
10086            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10087            if (newPackage.mExtras != null) {
10088                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10089                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10090                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10091
10092                // is the update attempting to change shared user? that isn't going to work...
10093                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10094                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10095                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10096                            + " to " + newPkgSetting.sharedUser);
10097                    updatedSettings = true;
10098                }
10099            }
10100
10101            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10102                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10103                updatedSettings = true;
10104            }
10105
10106        } catch (PackageManagerException e) {
10107            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10108        }
10109
10110        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10111            // Re installation failed. Restore old information
10112            // Remove new pkg information
10113            if (newPackage != null) {
10114                removeInstalledPackageLI(newPackage, true);
10115            }
10116            // Add back the old system package
10117            try {
10118                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10119            } catch (PackageManagerException e) {
10120                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10121            }
10122            // Restore the old system information in Settings
10123            synchronized(mPackages) {
10124                if (updatedSettings) {
10125                    mSettings.enableSystemPackageLPw(packageName);
10126                    mSettings.setInstallerPackageName(packageName,
10127                            oldPkgSetting.installerPackageName);
10128                }
10129                mSettings.writeLPr();
10130            }
10131        }
10132    }
10133
10134    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10135            int[] allUsers, boolean[] perUserInstalled,
10136            PackageInstalledInfo res) {
10137        String pkgName = newPackage.packageName;
10138        synchronized (mPackages) {
10139            //write settings. the installStatus will be incomplete at this stage.
10140            //note that the new package setting would have already been
10141            //added to mPackages. It hasn't been persisted yet.
10142            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10143            mSettings.writeLPr();
10144        }
10145
10146        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10147
10148        synchronized (mPackages) {
10149            updatePermissionsLPw(newPackage.packageName, newPackage,
10150                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10151                            ? UPDATE_PERMISSIONS_ALL : 0));
10152            // For system-bundled packages, we assume that installing an upgraded version
10153            // of the package implies that the user actually wants to run that new code,
10154            // so we enable the package.
10155            if (isSystemApp(newPackage)) {
10156                // NB: implicit assumption that system package upgrades apply to all users
10157                if (DEBUG_INSTALL) {
10158                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10159                }
10160                PackageSetting ps = mSettings.mPackages.get(pkgName);
10161                if (ps != null) {
10162                    if (res.origUsers != null) {
10163                        for (int userHandle : res.origUsers) {
10164                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10165                                    userHandle, installerPackageName);
10166                        }
10167                    }
10168                    // Also convey the prior install/uninstall state
10169                    if (allUsers != null && perUserInstalled != null) {
10170                        for (int i = 0; i < allUsers.length; i++) {
10171                            if (DEBUG_INSTALL) {
10172                                Slog.d(TAG, "    user " + allUsers[i]
10173                                        + " => " + perUserInstalled[i]);
10174                            }
10175                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10176                        }
10177                        // these install state changes will be persisted in the
10178                        // upcoming call to mSettings.writeLPr().
10179                    }
10180                }
10181            }
10182            res.name = pkgName;
10183            res.uid = newPackage.applicationInfo.uid;
10184            res.pkg = newPackage;
10185            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10186            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10187            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10188            //to update install status
10189            mSettings.writeLPr();
10190        }
10191    }
10192
10193    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10194        final int installFlags = args.installFlags;
10195        String installerPackageName = args.installerPackageName;
10196        File tmpPackageFile = new File(args.getCodePath());
10197        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10198        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10199        boolean replace = false;
10200        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10201        // Result object to be returned
10202        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10203
10204        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10205        // Retrieve PackageSettings and parse package
10206        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10207                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10208                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10209        PackageParser pp = new PackageParser();
10210        pp.setSeparateProcesses(mSeparateProcesses);
10211        pp.setDisplayMetrics(mMetrics);
10212
10213        final PackageParser.Package pkg;
10214        try {
10215            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10216        } catch (PackageParserException e) {
10217            res.setError("Failed parse during installPackageLI", e);
10218            return;
10219        }
10220
10221        // Mark that we have an install time CPU ABI override.
10222        pkg.cpuAbiOverride = args.abiOverride;
10223
10224        String pkgName = res.name = pkg.packageName;
10225        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10226            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10227                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10228                return;
10229            }
10230        }
10231
10232        try {
10233            pp.collectCertificates(pkg, parseFlags);
10234            pp.collectManifestDigest(pkg);
10235        } catch (PackageParserException e) {
10236            res.setError("Failed collect during installPackageLI", e);
10237            return;
10238        }
10239
10240        /* If the installer passed in a manifest digest, compare it now. */
10241        if (args.manifestDigest != null) {
10242            if (DEBUG_INSTALL) {
10243                final String parsedManifest = pkg.manifestDigest == null ? "null"
10244                        : pkg.manifestDigest.toString();
10245                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10246                        + parsedManifest);
10247            }
10248
10249            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10250                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10251                return;
10252            }
10253        } else if (DEBUG_INSTALL) {
10254            final String parsedManifest = pkg.manifestDigest == null
10255                    ? "null" : pkg.manifestDigest.toString();
10256            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10257        }
10258
10259        // Get rid of all references to package scan path via parser.
10260        pp = null;
10261        String oldCodePath = null;
10262        boolean systemApp = false;
10263        synchronized (mPackages) {
10264            // Check whether the newly-scanned package wants to define an already-defined perm
10265            int N = pkg.permissions.size();
10266            for (int i = N-1; i >= 0; i--) {
10267                PackageParser.Permission perm = pkg.permissions.get(i);
10268                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10269                if (bp != null) {
10270                    // If the defining package is signed with our cert, it's okay.  This
10271                    // also includes the "updating the same package" case, of course.
10272                    // "updating same package" could also involve key-rotation.
10273                    final boolean sigsOk;
10274                    if (!bp.sourcePackage.equals(pkg.packageName)
10275                            || !(bp.packageSetting instanceof PackageSetting)
10276                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10277                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10278                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10279                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10280                    } else {
10281                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10282                    }
10283                    if (!sigsOk) {
10284                        // If the owning package is the system itself, we log but allow
10285                        // install to proceed; we fail the install on all other permission
10286                        // redefinitions.
10287                        if (!bp.sourcePackage.equals("android")) {
10288                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10289                                    + pkg.packageName + " attempting to redeclare permission "
10290                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10291                            res.origPermission = perm.info.name;
10292                            res.origPackage = bp.sourcePackage;
10293                            return;
10294                        } else {
10295                            Slog.w(TAG, "Package " + pkg.packageName
10296                                    + " attempting to redeclare system permission "
10297                                    + perm.info.name + "; ignoring new declaration");
10298                            pkg.permissions.remove(i);
10299                        }
10300                    }
10301                }
10302            }
10303
10304            // Check if installing already existing package
10305            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10306                String oldName = mSettings.mRenamedPackages.get(pkgName);
10307                if (pkg.mOriginalPackages != null
10308                        && pkg.mOriginalPackages.contains(oldName)
10309                        && mPackages.containsKey(oldName)) {
10310                    // This package is derived from an original package,
10311                    // and this device has been updating from that original
10312                    // name.  We must continue using the original name, so
10313                    // rename the new package here.
10314                    pkg.setPackageName(oldName);
10315                    pkgName = pkg.packageName;
10316                    replace = true;
10317                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10318                            + oldName + " pkgName=" + pkgName);
10319                } else if (mPackages.containsKey(pkgName)) {
10320                    // This package, under its official name, already exists
10321                    // on the device; we should replace it.
10322                    replace = true;
10323                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10324                }
10325            }
10326            PackageSetting ps = mSettings.mPackages.get(pkgName);
10327            if (ps != null) {
10328                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10329                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10330                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10331                    systemApp = (ps.pkg.applicationInfo.flags &
10332                            ApplicationInfo.FLAG_SYSTEM) != 0;
10333                }
10334                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10335            }
10336        }
10337
10338        if (systemApp && onSd) {
10339            // Disable updates to system apps on sdcard
10340            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10341                    "Cannot install updates to system apps on sdcard");
10342            return;
10343        }
10344
10345        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10346            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10347            return;
10348        }
10349
10350        if (replace) {
10351            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10352                    installerPackageName, res);
10353        } else {
10354            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10355                    args.user, installerPackageName, res);
10356        }
10357        synchronized (mPackages) {
10358            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10359            if (ps != null) {
10360                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10361            }
10362        }
10363    }
10364
10365    private static boolean isForwardLocked(PackageParser.Package pkg) {
10366        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10367    }
10368
10369    private static boolean isForwardLocked(ApplicationInfo info) {
10370        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10371    }
10372
10373    private boolean isForwardLocked(PackageSetting ps) {
10374        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10375    }
10376
10377    private static boolean isMultiArch(PackageSetting ps) {
10378        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10379    }
10380
10381    private static boolean isMultiArch(ApplicationInfo info) {
10382        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10383    }
10384
10385    private static boolean isExternal(PackageParser.Package pkg) {
10386        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10387    }
10388
10389    private static boolean isExternal(PackageSetting ps) {
10390        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10391    }
10392
10393    private static boolean isExternal(ApplicationInfo info) {
10394        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10395    }
10396
10397    private static boolean isSystemApp(PackageParser.Package pkg) {
10398        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10399    }
10400
10401    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10402        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10403    }
10404
10405    private static boolean isSystemApp(ApplicationInfo info) {
10406        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10407    }
10408
10409    private static boolean isSystemApp(PackageSetting ps) {
10410        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10411    }
10412
10413    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10414        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10415    }
10416
10417    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10418        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10419    }
10420
10421    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10422        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10423    }
10424
10425    private int packageFlagsToInstallFlags(PackageSetting ps) {
10426        int installFlags = 0;
10427        if (isExternal(ps)) {
10428            installFlags |= PackageManager.INSTALL_EXTERNAL;
10429        }
10430        if (isForwardLocked(ps)) {
10431            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10432        }
10433        return installFlags;
10434    }
10435
10436    private void deleteTempPackageFiles() {
10437        final FilenameFilter filter = new FilenameFilter() {
10438            public boolean accept(File dir, String name) {
10439                return name.startsWith("vmdl") && name.endsWith(".tmp");
10440            }
10441        };
10442        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10443            file.delete();
10444        }
10445    }
10446
10447    @Override
10448    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10449            int flags) {
10450        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10451                flags);
10452    }
10453
10454    @Override
10455    public void deletePackage(final String packageName,
10456            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10457        mContext.enforceCallingOrSelfPermission(
10458                android.Manifest.permission.DELETE_PACKAGES, null);
10459        final int uid = Binder.getCallingUid();
10460        if (UserHandle.getUserId(uid) != userId) {
10461            mContext.enforceCallingPermission(
10462                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10463                    "deletePackage for user " + userId);
10464        }
10465        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10466            try {
10467                observer.onPackageDeleted(packageName,
10468                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10469            } catch (RemoteException re) {
10470            }
10471            return;
10472        }
10473
10474        boolean uninstallBlocked = false;
10475        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10476            int[] users = sUserManager.getUserIds();
10477            for (int i = 0; i < users.length; ++i) {
10478                if (getBlockUninstallForUser(packageName, users[i])) {
10479                    uninstallBlocked = true;
10480                    break;
10481                }
10482            }
10483        } else {
10484            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10485        }
10486        if (uninstallBlocked) {
10487            try {
10488                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10489                        null);
10490            } catch (RemoteException re) {
10491            }
10492            return;
10493        }
10494
10495        if (DEBUG_REMOVE) {
10496            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10497        }
10498        // Queue up an async operation since the package deletion may take a little while.
10499        mHandler.post(new Runnable() {
10500            public void run() {
10501                mHandler.removeCallbacks(this);
10502                final int returnCode = deletePackageX(packageName, userId, flags);
10503                if (observer != null) {
10504                    try {
10505                        observer.onPackageDeleted(packageName, returnCode, null);
10506                    } catch (RemoteException e) {
10507                        Log.i(TAG, "Observer no longer exists.");
10508                    } //end catch
10509                } //end if
10510            } //end run
10511        });
10512    }
10513
10514    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10515        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10516                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10517        try {
10518            if (dpm != null) {
10519                if (dpm.isDeviceOwner(packageName)) {
10520                    return true;
10521                }
10522                int[] users;
10523                if (userId == UserHandle.USER_ALL) {
10524                    users = sUserManager.getUserIds();
10525                } else {
10526                    users = new int[]{userId};
10527                }
10528                for (int i = 0; i < users.length; ++i) {
10529                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10530                        return true;
10531                    }
10532                }
10533            }
10534        } catch (RemoteException e) {
10535        }
10536        return false;
10537    }
10538
10539    /**
10540     *  This method is an internal method that could be get invoked either
10541     *  to delete an installed package or to clean up a failed installation.
10542     *  After deleting an installed package, a broadcast is sent to notify any
10543     *  listeners that the package has been installed. For cleaning up a failed
10544     *  installation, the broadcast is not necessary since the package's
10545     *  installation wouldn't have sent the initial broadcast either
10546     *  The key steps in deleting a package are
10547     *  deleting the package information in internal structures like mPackages,
10548     *  deleting the packages base directories through installd
10549     *  updating mSettings to reflect current status
10550     *  persisting settings for later use
10551     *  sending a broadcast if necessary
10552     */
10553    private int deletePackageX(String packageName, int userId, int flags) {
10554        final PackageRemovedInfo info = new PackageRemovedInfo();
10555        final boolean res;
10556
10557        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10558                ? UserHandle.ALL : new UserHandle(userId);
10559
10560        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10561            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10562            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10563        }
10564
10565        boolean removedForAllUsers = false;
10566        boolean systemUpdate = false;
10567
10568        // for the uninstall-updates case and restricted profiles, remember the per-
10569        // userhandle installed state
10570        int[] allUsers;
10571        boolean[] perUserInstalled;
10572        synchronized (mPackages) {
10573            PackageSetting ps = mSettings.mPackages.get(packageName);
10574            allUsers = sUserManager.getUserIds();
10575            perUserInstalled = new boolean[allUsers.length];
10576            for (int i = 0; i < allUsers.length; i++) {
10577                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10578            }
10579        }
10580
10581        synchronized (mInstallLock) {
10582            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10583            res = deletePackageLI(packageName, removeForUser,
10584                    true, allUsers, perUserInstalled,
10585                    flags | REMOVE_CHATTY, info, true);
10586            systemUpdate = info.isRemovedPackageSystemUpdate;
10587            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10588                removedForAllUsers = true;
10589            }
10590            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10591                    + " removedForAllUsers=" + removedForAllUsers);
10592        }
10593
10594        if (res) {
10595            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10596
10597            // If the removed package was a system update, the old system package
10598            // was re-enabled; we need to broadcast this information
10599            if (systemUpdate) {
10600                Bundle extras = new Bundle(1);
10601                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10602                        ? info.removedAppId : info.uid);
10603                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10604
10605                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10606                        extras, null, null, null);
10607                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10608                        extras, null, null, null);
10609                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10610                        null, packageName, null, null);
10611            }
10612        }
10613        // Force a gc here.
10614        Runtime.getRuntime().gc();
10615        // Delete the resources here after sending the broadcast to let
10616        // other processes clean up before deleting resources.
10617        if (info.args != null) {
10618            synchronized (mInstallLock) {
10619                info.args.doPostDeleteLI(true);
10620            }
10621        }
10622
10623        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10624    }
10625
10626    static class PackageRemovedInfo {
10627        String removedPackage;
10628        int uid = -1;
10629        int removedAppId = -1;
10630        int[] removedUsers = null;
10631        boolean isRemovedPackageSystemUpdate = false;
10632        // Clean up resources deleted packages.
10633        InstallArgs args = null;
10634
10635        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10636            Bundle extras = new Bundle(1);
10637            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10638            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10639            if (replacing) {
10640                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10641            }
10642            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10643            if (removedPackage != null) {
10644                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10645                        extras, null, null, removedUsers);
10646                if (fullRemove && !replacing) {
10647                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10648                            extras, null, null, removedUsers);
10649                }
10650            }
10651            if (removedAppId >= 0) {
10652                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10653                        removedUsers);
10654            }
10655        }
10656    }
10657
10658    /*
10659     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10660     * flag is not set, the data directory is removed as well.
10661     * make sure this flag is set for partially installed apps. If not its meaningless to
10662     * delete a partially installed application.
10663     */
10664    private void removePackageDataLI(PackageSetting ps,
10665            int[] allUserHandles, boolean[] perUserInstalled,
10666            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10667        String packageName = ps.name;
10668        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10669        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10670        // Retrieve object to delete permissions for shared user later on
10671        final PackageSetting deletedPs;
10672        // reader
10673        synchronized (mPackages) {
10674            deletedPs = mSettings.mPackages.get(packageName);
10675            if (outInfo != null) {
10676                outInfo.removedPackage = packageName;
10677                outInfo.removedUsers = deletedPs != null
10678                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10679                        : null;
10680            }
10681        }
10682        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10683            removeDataDirsLI(packageName);
10684            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10685        }
10686        // writer
10687        synchronized (mPackages) {
10688            if (deletedPs != null) {
10689                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10690                    if (outInfo != null) {
10691                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10692                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10693                    }
10694                    if (deletedPs != null) {
10695                        updatePermissionsLPw(deletedPs.name, null, 0);
10696                        if (deletedPs.sharedUser != null) {
10697                            // remove permissions associated with package
10698                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10699                        }
10700                    }
10701                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10702                }
10703                // make sure to preserve per-user disabled state if this removal was just
10704                // a downgrade of a system app to the factory package
10705                if (allUserHandles != null && perUserInstalled != null) {
10706                    if (DEBUG_REMOVE) {
10707                        Slog.d(TAG, "Propagating install state across downgrade");
10708                    }
10709                    for (int i = 0; i < allUserHandles.length; i++) {
10710                        if (DEBUG_REMOVE) {
10711                            Slog.d(TAG, "    user " + allUserHandles[i]
10712                                    + " => " + perUserInstalled[i]);
10713                        }
10714                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10715                    }
10716                }
10717            }
10718            // can downgrade to reader
10719            if (writeSettings) {
10720                // Save settings now
10721                mSettings.writeLPr();
10722            }
10723        }
10724        if (outInfo != null) {
10725            // A user ID was deleted here. Go through all users and remove it
10726            // from KeyStore.
10727            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10728        }
10729    }
10730
10731    static boolean locationIsPrivileged(File path) {
10732        try {
10733            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10734                    .getCanonicalPath();
10735            return path.getCanonicalPath().startsWith(privilegedAppDir);
10736        } catch (IOException e) {
10737            Slog.e(TAG, "Unable to access code path " + path);
10738        }
10739        return false;
10740    }
10741
10742    /*
10743     * Tries to delete system package.
10744     */
10745    private boolean deleteSystemPackageLI(PackageSetting newPs,
10746            int[] allUserHandles, boolean[] perUserInstalled,
10747            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10748        final boolean applyUserRestrictions
10749                = (allUserHandles != null) && (perUserInstalled != null);
10750        PackageSetting disabledPs = null;
10751        // Confirm if the system package has been updated
10752        // An updated system app can be deleted. This will also have to restore
10753        // the system pkg from system partition
10754        // reader
10755        synchronized (mPackages) {
10756            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10757        }
10758        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10759                + " disabledPs=" + disabledPs);
10760        if (disabledPs == null) {
10761            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10762            return false;
10763        } else if (DEBUG_REMOVE) {
10764            Slog.d(TAG, "Deleting system pkg from data partition");
10765        }
10766        if (DEBUG_REMOVE) {
10767            if (applyUserRestrictions) {
10768                Slog.d(TAG, "Remembering install states:");
10769                for (int i = 0; i < allUserHandles.length; i++) {
10770                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10771                }
10772            }
10773        }
10774        // Delete the updated package
10775        outInfo.isRemovedPackageSystemUpdate = true;
10776        if (disabledPs.versionCode < newPs.versionCode) {
10777            // Delete data for downgrades
10778            flags &= ~PackageManager.DELETE_KEEP_DATA;
10779        } else {
10780            // Preserve data by setting flag
10781            flags |= PackageManager.DELETE_KEEP_DATA;
10782        }
10783        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10784                allUserHandles, perUserInstalled, outInfo, writeSettings);
10785        if (!ret) {
10786            return false;
10787        }
10788        // writer
10789        synchronized (mPackages) {
10790            // Reinstate the old system package
10791            mSettings.enableSystemPackageLPw(newPs.name);
10792            // Remove any native libraries from the upgraded package.
10793            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10794        }
10795        // Install the system package
10796        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10797        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10798        if (locationIsPrivileged(disabledPs.codePath)) {
10799            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10800        }
10801
10802        final PackageParser.Package newPkg;
10803        try {
10804            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10805        } catch (PackageManagerException e) {
10806            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10807            return false;
10808        }
10809
10810        // writer
10811        synchronized (mPackages) {
10812            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10813            updatePermissionsLPw(newPkg.packageName, newPkg,
10814                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10815            if (applyUserRestrictions) {
10816                if (DEBUG_REMOVE) {
10817                    Slog.d(TAG, "Propagating install state across reinstall");
10818                }
10819                for (int i = 0; i < allUserHandles.length; i++) {
10820                    if (DEBUG_REMOVE) {
10821                        Slog.d(TAG, "    user " + allUserHandles[i]
10822                                + " => " + perUserInstalled[i]);
10823                    }
10824                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10825                }
10826                // Regardless of writeSettings we need to ensure that this restriction
10827                // state propagation is persisted
10828                mSettings.writeAllUsersPackageRestrictionsLPr();
10829            }
10830            // can downgrade to reader here
10831            if (writeSettings) {
10832                mSettings.writeLPr();
10833            }
10834        }
10835        return true;
10836    }
10837
10838    private boolean deleteInstalledPackageLI(PackageSetting ps,
10839            boolean deleteCodeAndResources, int flags,
10840            int[] allUserHandles, boolean[] perUserInstalled,
10841            PackageRemovedInfo outInfo, boolean writeSettings) {
10842        if (outInfo != null) {
10843            outInfo.uid = ps.appId;
10844        }
10845
10846        // Delete package data from internal structures and also remove data if flag is set
10847        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10848
10849        // Delete application code and resources
10850        if (deleteCodeAndResources && (outInfo != null)) {
10851            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10852                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10853                    getAppDexInstructionSets(ps));
10854            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10855        }
10856        return true;
10857    }
10858
10859    @Override
10860    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10861            int userId) {
10862        mContext.enforceCallingOrSelfPermission(
10863                android.Manifest.permission.DELETE_PACKAGES, null);
10864        synchronized (mPackages) {
10865            PackageSetting ps = mSettings.mPackages.get(packageName);
10866            if (ps == null) {
10867                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10868                return false;
10869            }
10870            if (!ps.getInstalled(userId)) {
10871                // Can't block uninstall for an app that is not installed or enabled.
10872                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10873                return false;
10874            }
10875            ps.setBlockUninstall(blockUninstall, userId);
10876            mSettings.writePackageRestrictionsLPr(userId);
10877        }
10878        return true;
10879    }
10880
10881    @Override
10882    public boolean getBlockUninstallForUser(String packageName, int userId) {
10883        synchronized (mPackages) {
10884            PackageSetting ps = mSettings.mPackages.get(packageName);
10885            if (ps == null) {
10886                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10887                return false;
10888            }
10889            return ps.getBlockUninstall(userId);
10890        }
10891    }
10892
10893    /*
10894     * This method handles package deletion in general
10895     */
10896    private boolean deletePackageLI(String packageName, UserHandle user,
10897            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10898            int flags, PackageRemovedInfo outInfo,
10899            boolean writeSettings) {
10900        if (packageName == null) {
10901            Slog.w(TAG, "Attempt to delete null packageName.");
10902            return false;
10903        }
10904        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10905        PackageSetting ps;
10906        boolean dataOnly = false;
10907        int removeUser = -1;
10908        int appId = -1;
10909        synchronized (mPackages) {
10910            ps = mSettings.mPackages.get(packageName);
10911            if (ps == null) {
10912                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10913                return false;
10914            }
10915            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10916                    && user.getIdentifier() != UserHandle.USER_ALL) {
10917                // The caller is asking that the package only be deleted for a single
10918                // user.  To do this, we just mark its uninstalled state and delete
10919                // its data.  If this is a system app, we only allow this to happen if
10920                // they have set the special DELETE_SYSTEM_APP which requests different
10921                // semantics than normal for uninstalling system apps.
10922                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10923                ps.setUserState(user.getIdentifier(),
10924                        COMPONENT_ENABLED_STATE_DEFAULT,
10925                        false, //installed
10926                        true,  //stopped
10927                        true,  //notLaunched
10928                        false, //hidden
10929                        null, null, null,
10930                        false // blockUninstall
10931                        );
10932                if (!isSystemApp(ps)) {
10933                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10934                        // Other user still have this package installed, so all
10935                        // we need to do is clear this user's data and save that
10936                        // it is uninstalled.
10937                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10938                        removeUser = user.getIdentifier();
10939                        appId = ps.appId;
10940                        mSettings.writePackageRestrictionsLPr(removeUser);
10941                    } else {
10942                        // We need to set it back to 'installed' so the uninstall
10943                        // broadcasts will be sent correctly.
10944                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10945                        ps.setInstalled(true, user.getIdentifier());
10946                    }
10947                } else {
10948                    // This is a system app, so we assume that the
10949                    // other users still have this package installed, so all
10950                    // we need to do is clear this user's data and save that
10951                    // it is uninstalled.
10952                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10953                    removeUser = user.getIdentifier();
10954                    appId = ps.appId;
10955                    mSettings.writePackageRestrictionsLPr(removeUser);
10956                }
10957            }
10958        }
10959
10960        if (removeUser >= 0) {
10961            // From above, we determined that we are deleting this only
10962            // for a single user.  Continue the work here.
10963            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10964            if (outInfo != null) {
10965                outInfo.removedPackage = packageName;
10966                outInfo.removedAppId = appId;
10967                outInfo.removedUsers = new int[] {removeUser};
10968            }
10969            mInstaller.clearUserData(packageName, removeUser);
10970            removeKeystoreDataIfNeeded(removeUser, appId);
10971            schedulePackageCleaning(packageName, removeUser, false);
10972            return true;
10973        }
10974
10975        if (dataOnly) {
10976            // Delete application data first
10977            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10978            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10979            return true;
10980        }
10981
10982        boolean ret = false;
10983        if (isSystemApp(ps)) {
10984            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10985            // When an updated system application is deleted we delete the existing resources as well and
10986            // fall back to existing code in system partition
10987            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10988                    flags, outInfo, writeSettings);
10989        } else {
10990            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10991            // Kill application pre-emptively especially for apps on sd.
10992            killApplication(packageName, ps.appId, "uninstall pkg");
10993            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10994                    allUserHandles, perUserInstalled,
10995                    outInfo, writeSettings);
10996        }
10997
10998        return ret;
10999    }
11000
11001    private final class ClearStorageConnection implements ServiceConnection {
11002        IMediaContainerService mContainerService;
11003
11004        @Override
11005        public void onServiceConnected(ComponentName name, IBinder service) {
11006            synchronized (this) {
11007                mContainerService = IMediaContainerService.Stub.asInterface(service);
11008                notifyAll();
11009            }
11010        }
11011
11012        @Override
11013        public void onServiceDisconnected(ComponentName name) {
11014        }
11015    }
11016
11017    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11018        final boolean mounted;
11019        if (Environment.isExternalStorageEmulated()) {
11020            mounted = true;
11021        } else {
11022            final String status = Environment.getExternalStorageState();
11023
11024            mounted = status.equals(Environment.MEDIA_MOUNTED)
11025                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11026        }
11027
11028        if (!mounted) {
11029            return;
11030        }
11031
11032        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11033        int[] users;
11034        if (userId == UserHandle.USER_ALL) {
11035            users = sUserManager.getUserIds();
11036        } else {
11037            users = new int[] { userId };
11038        }
11039        final ClearStorageConnection conn = new ClearStorageConnection();
11040        if (mContext.bindServiceAsUser(
11041                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11042            try {
11043                for (int curUser : users) {
11044                    long timeout = SystemClock.uptimeMillis() + 5000;
11045                    synchronized (conn) {
11046                        long now = SystemClock.uptimeMillis();
11047                        while (conn.mContainerService == null && now < timeout) {
11048                            try {
11049                                conn.wait(timeout - now);
11050                            } catch (InterruptedException e) {
11051                            }
11052                        }
11053                    }
11054                    if (conn.mContainerService == null) {
11055                        return;
11056                    }
11057
11058                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11059                    clearDirectory(conn.mContainerService,
11060                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11061                    if (allData) {
11062                        clearDirectory(conn.mContainerService,
11063                                userEnv.buildExternalStorageAppDataDirs(packageName));
11064                        clearDirectory(conn.mContainerService,
11065                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11066                    }
11067                }
11068            } finally {
11069                mContext.unbindService(conn);
11070            }
11071        }
11072    }
11073
11074    @Override
11075    public void clearApplicationUserData(final String packageName,
11076            final IPackageDataObserver observer, final int userId) {
11077        mContext.enforceCallingOrSelfPermission(
11078                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11079        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11080        // Queue up an async operation since the package deletion may take a little while.
11081        mHandler.post(new Runnable() {
11082            public void run() {
11083                mHandler.removeCallbacks(this);
11084                final boolean succeeded;
11085                synchronized (mInstallLock) {
11086                    succeeded = clearApplicationUserDataLI(packageName, userId);
11087                }
11088                clearExternalStorageDataSync(packageName, userId, true);
11089                if (succeeded) {
11090                    // invoke DeviceStorageMonitor's update method to clear any notifications
11091                    DeviceStorageMonitorInternal
11092                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11093                    if (dsm != null) {
11094                        dsm.checkMemory();
11095                    }
11096                }
11097                if(observer != null) {
11098                    try {
11099                        observer.onRemoveCompleted(packageName, succeeded);
11100                    } catch (RemoteException e) {
11101                        Log.i(TAG, "Observer no longer exists.");
11102                    }
11103                } //end if observer
11104            } //end run
11105        });
11106    }
11107
11108    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11109        if (packageName == null) {
11110            Slog.w(TAG, "Attempt to delete null packageName.");
11111            return false;
11112        }
11113
11114        // Try finding details about the requested package
11115        PackageParser.Package pkg;
11116        synchronized (mPackages) {
11117            pkg = mPackages.get(packageName);
11118            if (pkg == null) {
11119                final PackageSetting ps = mSettings.mPackages.get(packageName);
11120                if (ps != null) {
11121                    pkg = ps.pkg;
11122                }
11123            }
11124        }
11125
11126        if (pkg == null) {
11127            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11128        }
11129
11130        // Always delete data directories for package, even if we found no other
11131        // record of app. This helps users recover from UID mismatches without
11132        // resorting to a full data wipe.
11133        int retCode = mInstaller.clearUserData(packageName, userId);
11134        if (retCode < 0) {
11135            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11136            return false;
11137        }
11138
11139        if (pkg == null) {
11140            return false;
11141        }
11142
11143        if (pkg != null && pkg.applicationInfo != null) {
11144            final int appId = pkg.applicationInfo.uid;
11145            removeKeystoreDataIfNeeded(userId, appId);
11146        }
11147
11148        // Create a native library symlink only if we have native libraries
11149        // and if the native libraries are 32 bit libraries. We do not provide
11150        // this symlink for 64 bit libraries.
11151        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11152                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11153            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11154            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11155                Slog.w(TAG, "Failed linking native library dir");
11156                return false;
11157            }
11158        }
11159
11160        return true;
11161    }
11162
11163    /**
11164     * Remove entries from the keystore daemon. Will only remove it if the
11165     * {@code appId} is valid.
11166     */
11167    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11168        if (appId < 0) {
11169            return;
11170        }
11171
11172        final KeyStore keyStore = KeyStore.getInstance();
11173        if (keyStore != null) {
11174            if (userId == UserHandle.USER_ALL) {
11175                for (final int individual : sUserManager.getUserIds()) {
11176                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11177                }
11178            } else {
11179                keyStore.clearUid(UserHandle.getUid(userId, appId));
11180            }
11181        } else {
11182            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11183        }
11184    }
11185
11186    @Override
11187    public void deleteApplicationCacheFiles(final String packageName,
11188            final IPackageDataObserver observer) {
11189        mContext.enforceCallingOrSelfPermission(
11190                android.Manifest.permission.DELETE_CACHE_FILES, null);
11191        // Queue up an async operation since the package deletion may take a little while.
11192        final int userId = UserHandle.getCallingUserId();
11193        mHandler.post(new Runnable() {
11194            public void run() {
11195                mHandler.removeCallbacks(this);
11196                final boolean succeded;
11197                synchronized (mInstallLock) {
11198                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11199                }
11200                clearExternalStorageDataSync(packageName, userId, false);
11201                if(observer != null) {
11202                    try {
11203                        observer.onRemoveCompleted(packageName, succeded);
11204                    } catch (RemoteException e) {
11205                        Log.i(TAG, "Observer no longer exists.");
11206                    }
11207                } //end if observer
11208            } //end run
11209        });
11210    }
11211
11212    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11213        if (packageName == null) {
11214            Slog.w(TAG, "Attempt to delete null packageName.");
11215            return false;
11216        }
11217        PackageParser.Package p;
11218        synchronized (mPackages) {
11219            p = mPackages.get(packageName);
11220        }
11221        if (p == null) {
11222            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11223            return false;
11224        }
11225        final ApplicationInfo applicationInfo = p.applicationInfo;
11226        if (applicationInfo == null) {
11227            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11228            return false;
11229        }
11230        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11231        if (retCode < 0) {
11232            Slog.w(TAG, "Couldn't remove cache files for package: "
11233                       + packageName + " u" + userId);
11234            return false;
11235        }
11236        return true;
11237    }
11238
11239    @Override
11240    public void getPackageSizeInfo(final String packageName, int userHandle,
11241            final IPackageStatsObserver observer) {
11242        mContext.enforceCallingOrSelfPermission(
11243                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11244        if (packageName == null) {
11245            throw new IllegalArgumentException("Attempt to get size of null packageName");
11246        }
11247
11248        PackageStats stats = new PackageStats(packageName, userHandle);
11249
11250        /*
11251         * Queue up an async operation since the package measurement may take a
11252         * little while.
11253         */
11254        Message msg = mHandler.obtainMessage(INIT_COPY);
11255        msg.obj = new MeasureParams(stats, observer);
11256        mHandler.sendMessage(msg);
11257    }
11258
11259    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11260            PackageStats pStats) {
11261        if (packageName == null) {
11262            Slog.w(TAG, "Attempt to get size of null packageName.");
11263            return false;
11264        }
11265        PackageParser.Package p;
11266        boolean dataOnly = false;
11267        String libDirRoot = null;
11268        String asecPath = null;
11269        PackageSetting ps = null;
11270        synchronized (mPackages) {
11271            p = mPackages.get(packageName);
11272            ps = mSettings.mPackages.get(packageName);
11273            if(p == null) {
11274                dataOnly = true;
11275                if((ps == null) || (ps.pkg == null)) {
11276                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11277                    return false;
11278                }
11279                p = ps.pkg;
11280            }
11281            if (ps != null) {
11282                libDirRoot = ps.legacyNativeLibraryPathString;
11283            }
11284            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11285                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11286                if (secureContainerId != null) {
11287                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11288                }
11289            }
11290        }
11291        String publicSrcDir = null;
11292        if(!dataOnly) {
11293            final ApplicationInfo applicationInfo = p.applicationInfo;
11294            if (applicationInfo == null) {
11295                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11296                return false;
11297            }
11298            if (isForwardLocked(p)) {
11299                publicSrcDir = applicationInfo.getBaseResourcePath();
11300            }
11301        }
11302        // TODO: extend to measure size of split APKs
11303        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11304        // not just the first level.
11305        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11306        // just the primary.
11307        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11308        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11309                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11310        if (res < 0) {
11311            return false;
11312        }
11313
11314        // Fix-up for forward-locked applications in ASEC containers.
11315        if (!isExternal(p)) {
11316            pStats.codeSize += pStats.externalCodeSize;
11317            pStats.externalCodeSize = 0L;
11318        }
11319
11320        return true;
11321    }
11322
11323
11324    @Override
11325    public void addPackageToPreferred(String packageName) {
11326        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11327    }
11328
11329    @Override
11330    public void removePackageFromPreferred(String packageName) {
11331        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11332    }
11333
11334    @Override
11335    public List<PackageInfo> getPreferredPackages(int flags) {
11336        return new ArrayList<PackageInfo>();
11337    }
11338
11339    private int getUidTargetSdkVersionLockedLPr(int uid) {
11340        Object obj = mSettings.getUserIdLPr(uid);
11341        if (obj instanceof SharedUserSetting) {
11342            final SharedUserSetting sus = (SharedUserSetting) obj;
11343            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11344            final Iterator<PackageSetting> it = sus.packages.iterator();
11345            while (it.hasNext()) {
11346                final PackageSetting ps = it.next();
11347                if (ps.pkg != null) {
11348                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11349                    if (v < vers) vers = v;
11350                }
11351            }
11352            return vers;
11353        } else if (obj instanceof PackageSetting) {
11354            final PackageSetting ps = (PackageSetting) obj;
11355            if (ps.pkg != null) {
11356                return ps.pkg.applicationInfo.targetSdkVersion;
11357            }
11358        }
11359        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11360    }
11361
11362    @Override
11363    public void addPreferredActivity(IntentFilter filter, int match,
11364            ComponentName[] set, ComponentName activity, int userId) {
11365        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11366                "Adding preferred");
11367    }
11368
11369    private void addPreferredActivityInternal(IntentFilter filter, int match,
11370            ComponentName[] set, ComponentName activity, boolean always, int userId,
11371            String opname) {
11372        // writer
11373        int callingUid = Binder.getCallingUid();
11374        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11375        if (filter.countActions() == 0) {
11376            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11377            return;
11378        }
11379        synchronized (mPackages) {
11380            if (mContext.checkCallingOrSelfPermission(
11381                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11382                    != PackageManager.PERMISSION_GRANTED) {
11383                if (getUidTargetSdkVersionLockedLPr(callingUid)
11384                        < Build.VERSION_CODES.FROYO) {
11385                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11386                            + callingUid);
11387                    return;
11388                }
11389                mContext.enforceCallingOrSelfPermission(
11390                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11391            }
11392
11393            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11394            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11395                    + userId + ":");
11396            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11397            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11398            mSettings.writePackageRestrictionsLPr(userId);
11399        }
11400    }
11401
11402    @Override
11403    public void replacePreferredActivity(IntentFilter filter, int match,
11404            ComponentName[] set, ComponentName activity, int userId) {
11405        if (filter.countActions() != 1) {
11406            throw new IllegalArgumentException(
11407                    "replacePreferredActivity expects filter to have only 1 action.");
11408        }
11409        if (filter.countDataAuthorities() != 0
11410                || filter.countDataPaths() != 0
11411                || filter.countDataSchemes() > 1
11412                || filter.countDataTypes() != 0) {
11413            throw new IllegalArgumentException(
11414                    "replacePreferredActivity expects filter to have no data authorities, " +
11415                    "paths, or types; and at most one scheme.");
11416        }
11417
11418        final int callingUid = Binder.getCallingUid();
11419        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11420        synchronized (mPackages) {
11421            if (mContext.checkCallingOrSelfPermission(
11422                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11423                    != PackageManager.PERMISSION_GRANTED) {
11424                if (getUidTargetSdkVersionLockedLPr(callingUid)
11425                        < Build.VERSION_CODES.FROYO) {
11426                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11427                            + Binder.getCallingUid());
11428                    return;
11429                }
11430                mContext.enforceCallingOrSelfPermission(
11431                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11432            }
11433
11434            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11435            if (pir != null) {
11436                // Get all of the existing entries that exactly match this filter.
11437                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11438                if (existing != null && existing.size() == 1) {
11439                    PreferredActivity cur = existing.get(0);
11440                    if (DEBUG_PREFERRED) {
11441                        Slog.i(TAG, "Checking replace of preferred:");
11442                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11443                        if (!cur.mPref.mAlways) {
11444                            Slog.i(TAG, "  -- CUR; not mAlways!");
11445                        } else {
11446                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11447                            Slog.i(TAG, "  -- CUR: mSet="
11448                                    + Arrays.toString(cur.mPref.mSetComponents));
11449                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11450                            Slog.i(TAG, "  -- NEW: mMatch="
11451                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11452                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11453                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11454                        }
11455                    }
11456                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11457                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11458                            && cur.mPref.sameSet(set)) {
11459                        // Setting the preferred activity to what it happens to be already
11460                        if (DEBUG_PREFERRED) {
11461                            Slog.i(TAG, "Replacing with same preferred activity "
11462                                    + cur.mPref.mShortComponent + " for user "
11463                                    + userId + ":");
11464                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11465                        }
11466                        return;
11467                    }
11468                }
11469
11470                if (existing != null) {
11471                    if (DEBUG_PREFERRED) {
11472                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11473                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11474                    }
11475                    for (int i = 0; i < existing.size(); i++) {
11476                        PreferredActivity pa = existing.get(i);
11477                        if (DEBUG_PREFERRED) {
11478                            Slog.i(TAG, "Removing existing preferred activity "
11479                                    + pa.mPref.mComponent + ":");
11480                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11481                        }
11482                        pir.removeFilter(pa);
11483                    }
11484                }
11485            }
11486            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11487                    "Replacing preferred");
11488        }
11489    }
11490
11491    @Override
11492    public void clearPackagePreferredActivities(String packageName) {
11493        final int uid = Binder.getCallingUid();
11494        // writer
11495        synchronized (mPackages) {
11496            PackageParser.Package pkg = mPackages.get(packageName);
11497            if (pkg == null || pkg.applicationInfo.uid != uid) {
11498                if (mContext.checkCallingOrSelfPermission(
11499                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11500                        != PackageManager.PERMISSION_GRANTED) {
11501                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11502                            < Build.VERSION_CODES.FROYO) {
11503                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11504                                + Binder.getCallingUid());
11505                        return;
11506                    }
11507                    mContext.enforceCallingOrSelfPermission(
11508                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11509                }
11510            }
11511
11512            int user = UserHandle.getCallingUserId();
11513            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11514                mSettings.writePackageRestrictionsLPr(user);
11515                scheduleWriteSettingsLocked();
11516            }
11517        }
11518    }
11519
11520    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11521    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11522        ArrayList<PreferredActivity> removed = null;
11523        boolean changed = false;
11524        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11525            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11526            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11527            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11528                continue;
11529            }
11530            Iterator<PreferredActivity> it = pir.filterIterator();
11531            while (it.hasNext()) {
11532                PreferredActivity pa = it.next();
11533                // Mark entry for removal only if it matches the package name
11534                // and the entry is of type "always".
11535                if (packageName == null ||
11536                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11537                                && pa.mPref.mAlways)) {
11538                    if (removed == null) {
11539                        removed = new ArrayList<PreferredActivity>();
11540                    }
11541                    removed.add(pa);
11542                }
11543            }
11544            if (removed != null) {
11545                for (int j=0; j<removed.size(); j++) {
11546                    PreferredActivity pa = removed.get(j);
11547                    pir.removeFilter(pa);
11548                }
11549                changed = true;
11550            }
11551        }
11552        return changed;
11553    }
11554
11555    @Override
11556    public void resetPreferredActivities(int userId) {
11557        /* TODO: Actually use userId. Why is it being passed in? */
11558        mContext.enforceCallingOrSelfPermission(
11559                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11560        // writer
11561        synchronized (mPackages) {
11562            int user = UserHandle.getCallingUserId();
11563            clearPackagePreferredActivitiesLPw(null, user);
11564            mSettings.readDefaultPreferredAppsLPw(this, user);
11565            mSettings.writePackageRestrictionsLPr(user);
11566            scheduleWriteSettingsLocked();
11567        }
11568    }
11569
11570    @Override
11571    public int getPreferredActivities(List<IntentFilter> outFilters,
11572            List<ComponentName> outActivities, String packageName) {
11573
11574        int num = 0;
11575        final int userId = UserHandle.getCallingUserId();
11576        // reader
11577        synchronized (mPackages) {
11578            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11579            if (pir != null) {
11580                final Iterator<PreferredActivity> it = pir.filterIterator();
11581                while (it.hasNext()) {
11582                    final PreferredActivity pa = it.next();
11583                    if (packageName == null
11584                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11585                                    && pa.mPref.mAlways)) {
11586                        if (outFilters != null) {
11587                            outFilters.add(new IntentFilter(pa));
11588                        }
11589                        if (outActivities != null) {
11590                            outActivities.add(pa.mPref.mComponent);
11591                        }
11592                    }
11593                }
11594            }
11595        }
11596
11597        return num;
11598    }
11599
11600    @Override
11601    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11602            int userId) {
11603        int callingUid = Binder.getCallingUid();
11604        if (callingUid != Process.SYSTEM_UID) {
11605            throw new SecurityException(
11606                    "addPersistentPreferredActivity can only be run by the system");
11607        }
11608        if (filter.countActions() == 0) {
11609            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11610            return;
11611        }
11612        synchronized (mPackages) {
11613            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11614                    " :");
11615            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11616            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11617                    new PersistentPreferredActivity(filter, activity));
11618            mSettings.writePackageRestrictionsLPr(userId);
11619        }
11620    }
11621
11622    @Override
11623    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11624        int callingUid = Binder.getCallingUid();
11625        if (callingUid != Process.SYSTEM_UID) {
11626            throw new SecurityException(
11627                    "clearPackagePersistentPreferredActivities can only be run by the system");
11628        }
11629        ArrayList<PersistentPreferredActivity> removed = null;
11630        boolean changed = false;
11631        synchronized (mPackages) {
11632            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11633                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11634                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11635                        .valueAt(i);
11636                if (userId != thisUserId) {
11637                    continue;
11638                }
11639                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11640                while (it.hasNext()) {
11641                    PersistentPreferredActivity ppa = it.next();
11642                    // Mark entry for removal only if it matches the package name.
11643                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11644                        if (removed == null) {
11645                            removed = new ArrayList<PersistentPreferredActivity>();
11646                        }
11647                        removed.add(ppa);
11648                    }
11649                }
11650                if (removed != null) {
11651                    for (int j=0; j<removed.size(); j++) {
11652                        PersistentPreferredActivity ppa = removed.get(j);
11653                        ppir.removeFilter(ppa);
11654                    }
11655                    changed = true;
11656                }
11657            }
11658
11659            if (changed) {
11660                mSettings.writePackageRestrictionsLPr(userId);
11661            }
11662        }
11663    }
11664
11665    @Override
11666    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11667            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11668        mContext.enforceCallingOrSelfPermission(
11669                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11670        int callingUid = Binder.getCallingUid();
11671        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11672        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11673        if (intentFilter.countActions() == 0) {
11674            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11675            return;
11676        }
11677        synchronized (mPackages) {
11678            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11679                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11680            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11681            mSettings.writePackageRestrictionsLPr(sourceUserId);
11682        }
11683    }
11684
11685    @Override
11686    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11687            int ownerUserId) {
11688        mContext.enforceCallingOrSelfPermission(
11689                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11690        int callingUid = Binder.getCallingUid();
11691        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11692        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11693        int callingUserId = UserHandle.getUserId(callingUid);
11694        synchronized (mPackages) {
11695            CrossProfileIntentResolver resolver =
11696                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11697            HashSet<CrossProfileIntentFilter> set =
11698                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11699            for (CrossProfileIntentFilter filter : set) {
11700                if (filter.getOwnerPackage().equals(ownerPackage)
11701                        && filter.getOwnerUserId() == callingUserId) {
11702                    resolver.removeFilter(filter);
11703                }
11704            }
11705            mSettings.writePackageRestrictionsLPr(sourceUserId);
11706        }
11707    }
11708
11709    // Enforcing that callingUid is owning pkg on userId
11710    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11711        // The system owns everything.
11712        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11713            return;
11714        }
11715        int callingUserId = UserHandle.getUserId(callingUid);
11716        if (callingUserId != userId) {
11717            throw new SecurityException("calling uid " + callingUid
11718                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11719                    + callingUserId);
11720        }
11721        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11722        if (pi == null) {
11723            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11724                    + callingUserId);
11725        }
11726        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11727            throw new SecurityException("Calling uid " + callingUid
11728                    + " does not own package " + pkg);
11729        }
11730    }
11731
11732    @Override
11733    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11734        Intent intent = new Intent(Intent.ACTION_MAIN);
11735        intent.addCategory(Intent.CATEGORY_HOME);
11736
11737        final int callingUserId = UserHandle.getCallingUserId();
11738        List<ResolveInfo> list = queryIntentActivities(intent, null,
11739                PackageManager.GET_META_DATA, callingUserId);
11740        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11741                true, false, false, callingUserId);
11742
11743        allHomeCandidates.clear();
11744        if (list != null) {
11745            for (ResolveInfo ri : list) {
11746                allHomeCandidates.add(ri);
11747            }
11748        }
11749        return (preferred == null || preferred.activityInfo == null)
11750                ? null
11751                : new ComponentName(preferred.activityInfo.packageName,
11752                        preferred.activityInfo.name);
11753    }
11754
11755    @Override
11756    public void setApplicationEnabledSetting(String appPackageName,
11757            int newState, int flags, int userId, String callingPackage) {
11758        if (!sUserManager.exists(userId)) return;
11759        if (callingPackage == null) {
11760            callingPackage = Integer.toString(Binder.getCallingUid());
11761        }
11762        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11763    }
11764
11765    @Override
11766    public void setComponentEnabledSetting(ComponentName componentName,
11767            int newState, int flags, int userId) {
11768        if (!sUserManager.exists(userId)) return;
11769        setEnabledSetting(componentName.getPackageName(),
11770                componentName.getClassName(), newState, flags, userId, null);
11771    }
11772
11773    private void setEnabledSetting(final String packageName, String className, int newState,
11774            final int flags, int userId, String callingPackage) {
11775        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11776              || newState == COMPONENT_ENABLED_STATE_ENABLED
11777              || newState == COMPONENT_ENABLED_STATE_DISABLED
11778              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11779              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11780            throw new IllegalArgumentException("Invalid new component state: "
11781                    + newState);
11782        }
11783        PackageSetting pkgSetting;
11784        final int uid = Binder.getCallingUid();
11785        final int permission = mContext.checkCallingOrSelfPermission(
11786                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11787        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11788        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11789        boolean sendNow = false;
11790        boolean isApp = (className == null);
11791        String componentName = isApp ? packageName : className;
11792        int packageUid = -1;
11793        ArrayList<String> components;
11794
11795        // writer
11796        synchronized (mPackages) {
11797            pkgSetting = mSettings.mPackages.get(packageName);
11798            if (pkgSetting == null) {
11799                if (className == null) {
11800                    throw new IllegalArgumentException(
11801                            "Unknown package: " + packageName);
11802                }
11803                throw new IllegalArgumentException(
11804                        "Unknown component: " + packageName
11805                        + "/" + className);
11806            }
11807            // Allow root and verify that userId is not being specified by a different user
11808            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11809                throw new SecurityException(
11810                        "Permission Denial: attempt to change component state from pid="
11811                        + Binder.getCallingPid()
11812                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11813            }
11814            if (className == null) {
11815                // We're dealing with an application/package level state change
11816                if (pkgSetting.getEnabled(userId) == newState) {
11817                    // Nothing to do
11818                    return;
11819                }
11820                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11821                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11822                    // Don't care about who enables an app.
11823                    callingPackage = null;
11824                }
11825                pkgSetting.setEnabled(newState, userId, callingPackage);
11826                // pkgSetting.pkg.mSetEnabled = newState;
11827            } else {
11828                // We're dealing with a component level state change
11829                // First, verify that this is a valid class name.
11830                PackageParser.Package pkg = pkgSetting.pkg;
11831                if (pkg == null || !pkg.hasComponentClassName(className)) {
11832                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11833                        throw new IllegalArgumentException("Component class " + className
11834                                + " does not exist in " + packageName);
11835                    } else {
11836                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11837                                + className + " does not exist in " + packageName);
11838                    }
11839                }
11840                switch (newState) {
11841                case COMPONENT_ENABLED_STATE_ENABLED:
11842                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11843                        return;
11844                    }
11845                    break;
11846                case COMPONENT_ENABLED_STATE_DISABLED:
11847                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11848                        return;
11849                    }
11850                    break;
11851                case COMPONENT_ENABLED_STATE_DEFAULT:
11852                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11853                        return;
11854                    }
11855                    break;
11856                default:
11857                    Slog.e(TAG, "Invalid new component state: " + newState);
11858                    return;
11859                }
11860            }
11861            mSettings.writePackageRestrictionsLPr(userId);
11862            components = mPendingBroadcasts.get(userId, packageName);
11863            final boolean newPackage = components == null;
11864            if (newPackage) {
11865                components = new ArrayList<String>();
11866            }
11867            if (!components.contains(componentName)) {
11868                components.add(componentName);
11869            }
11870            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11871                sendNow = true;
11872                // Purge entry from pending broadcast list if another one exists already
11873                // since we are sending one right away.
11874                mPendingBroadcasts.remove(userId, packageName);
11875            } else {
11876                if (newPackage) {
11877                    mPendingBroadcasts.put(userId, packageName, components);
11878                }
11879                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11880                    // Schedule a message
11881                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11882                }
11883            }
11884        }
11885
11886        long callingId = Binder.clearCallingIdentity();
11887        try {
11888            if (sendNow) {
11889                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11890                sendPackageChangedBroadcast(packageName,
11891                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11892            }
11893        } finally {
11894            Binder.restoreCallingIdentity(callingId);
11895        }
11896    }
11897
11898    private void sendPackageChangedBroadcast(String packageName,
11899            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11900        if (DEBUG_INSTALL)
11901            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11902                    + componentNames);
11903        Bundle extras = new Bundle(4);
11904        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11905        String nameList[] = new String[componentNames.size()];
11906        componentNames.toArray(nameList);
11907        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11908        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11909        extras.putInt(Intent.EXTRA_UID, packageUid);
11910        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11911                new int[] {UserHandle.getUserId(packageUid)});
11912    }
11913
11914    @Override
11915    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11916        if (!sUserManager.exists(userId)) return;
11917        final int uid = Binder.getCallingUid();
11918        final int permission = mContext.checkCallingOrSelfPermission(
11919                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11920        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11921        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11922        // writer
11923        synchronized (mPackages) {
11924            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11925                    uid, userId)) {
11926                scheduleWritePackageRestrictionsLocked(userId);
11927            }
11928        }
11929    }
11930
11931    @Override
11932    public String getInstallerPackageName(String packageName) {
11933        // reader
11934        synchronized (mPackages) {
11935            return mSettings.getInstallerPackageNameLPr(packageName);
11936        }
11937    }
11938
11939    @Override
11940    public int getApplicationEnabledSetting(String packageName, int userId) {
11941        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11942        int uid = Binder.getCallingUid();
11943        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11944        // reader
11945        synchronized (mPackages) {
11946            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11947        }
11948    }
11949
11950    @Override
11951    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11952        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11953        int uid = Binder.getCallingUid();
11954        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11955        // reader
11956        synchronized (mPackages) {
11957            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11958        }
11959    }
11960
11961    @Override
11962    public void enterSafeMode() {
11963        enforceSystemOrRoot("Only the system can request entering safe mode");
11964
11965        if (!mSystemReady) {
11966            mSafeMode = true;
11967        }
11968    }
11969
11970    @Override
11971    public void systemReady() {
11972        mSystemReady = true;
11973
11974        // Read the compatibilty setting when the system is ready.
11975        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11976                mContext.getContentResolver(),
11977                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11978        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11979        if (DEBUG_SETTINGS) {
11980            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11981        }
11982
11983        synchronized (mPackages) {
11984            // Verify that all of the preferred activity components actually
11985            // exist.  It is possible for applications to be updated and at
11986            // that point remove a previously declared activity component that
11987            // had been set as a preferred activity.  We try to clean this up
11988            // the next time we encounter that preferred activity, but it is
11989            // possible for the user flow to never be able to return to that
11990            // situation so here we do a sanity check to make sure we haven't
11991            // left any junk around.
11992            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11993            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11994                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11995                removed.clear();
11996                for (PreferredActivity pa : pir.filterSet()) {
11997                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11998                        removed.add(pa);
11999                    }
12000                }
12001                if (removed.size() > 0) {
12002                    for (int r=0; r<removed.size(); r++) {
12003                        PreferredActivity pa = removed.get(r);
12004                        Slog.w(TAG, "Removing dangling preferred activity: "
12005                                + pa.mPref.mComponent);
12006                        pir.removeFilter(pa);
12007                    }
12008                    mSettings.writePackageRestrictionsLPr(
12009                            mSettings.mPreferredActivities.keyAt(i));
12010                }
12011            }
12012        }
12013        sUserManager.systemReady();
12014
12015        // Kick off any messages waiting for system ready
12016        if (mPostSystemReadyMessages != null) {
12017            for (Message msg : mPostSystemReadyMessages) {
12018                msg.sendToTarget();
12019            }
12020            mPostSystemReadyMessages = null;
12021        }
12022    }
12023
12024    @Override
12025    public boolean isSafeMode() {
12026        return mSafeMode;
12027    }
12028
12029    @Override
12030    public boolean hasSystemUidErrors() {
12031        return mHasSystemUidErrors;
12032    }
12033
12034    static String arrayToString(int[] array) {
12035        StringBuffer buf = new StringBuffer(128);
12036        buf.append('[');
12037        if (array != null) {
12038            for (int i=0; i<array.length; i++) {
12039                if (i > 0) buf.append(", ");
12040                buf.append(array[i]);
12041            }
12042        }
12043        buf.append(']');
12044        return buf.toString();
12045    }
12046
12047    static class DumpState {
12048        public static final int DUMP_LIBS = 1 << 0;
12049        public static final int DUMP_FEATURES = 1 << 1;
12050        public static final int DUMP_RESOLVERS = 1 << 2;
12051        public static final int DUMP_PERMISSIONS = 1 << 3;
12052        public static final int DUMP_PACKAGES = 1 << 4;
12053        public static final int DUMP_SHARED_USERS = 1 << 5;
12054        public static final int DUMP_MESSAGES = 1 << 6;
12055        public static final int DUMP_PROVIDERS = 1 << 7;
12056        public static final int DUMP_VERIFIERS = 1 << 8;
12057        public static final int DUMP_PREFERRED = 1 << 9;
12058        public static final int DUMP_PREFERRED_XML = 1 << 10;
12059        public static final int DUMP_KEYSETS = 1 << 11;
12060        public static final int DUMP_VERSION = 1 << 12;
12061        public static final int DUMP_INSTALLS = 1 << 13;
12062
12063        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12064
12065        private int mTypes;
12066
12067        private int mOptions;
12068
12069        private boolean mTitlePrinted;
12070
12071        private SharedUserSetting mSharedUser;
12072
12073        public boolean isDumping(int type) {
12074            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12075                return true;
12076            }
12077
12078            return (mTypes & type) != 0;
12079        }
12080
12081        public void setDump(int type) {
12082            mTypes |= type;
12083        }
12084
12085        public boolean isOptionEnabled(int option) {
12086            return (mOptions & option) != 0;
12087        }
12088
12089        public void setOptionEnabled(int option) {
12090            mOptions |= option;
12091        }
12092
12093        public boolean onTitlePrinted() {
12094            final boolean printed = mTitlePrinted;
12095            mTitlePrinted = true;
12096            return printed;
12097        }
12098
12099        public boolean getTitlePrinted() {
12100            return mTitlePrinted;
12101        }
12102
12103        public void setTitlePrinted(boolean enabled) {
12104            mTitlePrinted = enabled;
12105        }
12106
12107        public SharedUserSetting getSharedUser() {
12108            return mSharedUser;
12109        }
12110
12111        public void setSharedUser(SharedUserSetting user) {
12112            mSharedUser = user;
12113        }
12114    }
12115
12116    @Override
12117    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12118        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12119                != PackageManager.PERMISSION_GRANTED) {
12120            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12121                    + Binder.getCallingPid()
12122                    + ", uid=" + Binder.getCallingUid()
12123                    + " without permission "
12124                    + android.Manifest.permission.DUMP);
12125            return;
12126        }
12127
12128        DumpState dumpState = new DumpState();
12129        boolean fullPreferred = false;
12130        boolean checkin = false;
12131
12132        String packageName = null;
12133
12134        int opti = 0;
12135        while (opti < args.length) {
12136            String opt = args[opti];
12137            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12138                break;
12139            }
12140            opti++;
12141            if ("-a".equals(opt)) {
12142                // Right now we only know how to print all.
12143            } else if ("-h".equals(opt)) {
12144                pw.println("Package manager dump options:");
12145                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12146                pw.println("    --checkin: dump for a checkin");
12147                pw.println("    -f: print details of intent filters");
12148                pw.println("    -h: print this help");
12149                pw.println("  cmd may be one of:");
12150                pw.println("    l[ibraries]: list known shared libraries");
12151                pw.println("    f[ibraries]: list device features");
12152                pw.println("    k[eysets]: print known keysets");
12153                pw.println("    r[esolvers]: dump intent resolvers");
12154                pw.println("    perm[issions]: dump permissions");
12155                pw.println("    pref[erred]: print preferred package settings");
12156                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12157                pw.println("    prov[iders]: dump content providers");
12158                pw.println("    p[ackages]: dump installed packages");
12159                pw.println("    s[hared-users]: dump shared user IDs");
12160                pw.println("    m[essages]: print collected runtime messages");
12161                pw.println("    v[erifiers]: print package verifier info");
12162                pw.println("    version: print database version info");
12163                pw.println("    write: write current settings now");
12164                pw.println("    <package.name>: info about given package");
12165                pw.println("    installs: details about install sessions");
12166                return;
12167            } else if ("--checkin".equals(opt)) {
12168                checkin = true;
12169            } else if ("-f".equals(opt)) {
12170                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12171            } else {
12172                pw.println("Unknown argument: " + opt + "; use -h for help");
12173            }
12174        }
12175
12176        // Is the caller requesting to dump a particular piece of data?
12177        if (opti < args.length) {
12178            String cmd = args[opti];
12179            opti++;
12180            // Is this a package name?
12181            if ("android".equals(cmd) || cmd.contains(".")) {
12182                packageName = cmd;
12183                // When dumping a single package, we always dump all of its
12184                // filter information since the amount of data will be reasonable.
12185                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12186            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12187                dumpState.setDump(DumpState.DUMP_LIBS);
12188            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12189                dumpState.setDump(DumpState.DUMP_FEATURES);
12190            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12191                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12192            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12193                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12194            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12195                dumpState.setDump(DumpState.DUMP_PREFERRED);
12196            } else if ("preferred-xml".equals(cmd)) {
12197                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12198                if (opti < args.length && "--full".equals(args[opti])) {
12199                    fullPreferred = true;
12200                    opti++;
12201                }
12202            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12203                dumpState.setDump(DumpState.DUMP_PACKAGES);
12204            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12205                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12206            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12207                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12208            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12209                dumpState.setDump(DumpState.DUMP_MESSAGES);
12210            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12212            } else if ("version".equals(cmd)) {
12213                dumpState.setDump(DumpState.DUMP_VERSION);
12214            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12215                dumpState.setDump(DumpState.DUMP_KEYSETS);
12216            } else if ("installs".equals(cmd)) {
12217                dumpState.setDump(DumpState.DUMP_INSTALLS);
12218            } else if ("write".equals(cmd)) {
12219                synchronized (mPackages) {
12220                    mSettings.writeLPr();
12221                    pw.println("Settings written.");
12222                    return;
12223                }
12224            }
12225        }
12226
12227        if (checkin) {
12228            pw.println("vers,1");
12229        }
12230
12231        // reader
12232        synchronized (mPackages) {
12233            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12234                if (!checkin) {
12235                    if (dumpState.onTitlePrinted())
12236                        pw.println();
12237                    pw.println("Database versions:");
12238                    pw.print("  SDK Version:");
12239                    pw.print(" internal=");
12240                    pw.print(mSettings.mInternalSdkPlatform);
12241                    pw.print(" external=");
12242                    pw.println(mSettings.mExternalSdkPlatform);
12243                    pw.print("  DB Version:");
12244                    pw.print(" internal=");
12245                    pw.print(mSettings.mInternalDatabaseVersion);
12246                    pw.print(" external=");
12247                    pw.println(mSettings.mExternalDatabaseVersion);
12248                }
12249            }
12250
12251            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12252                if (!checkin) {
12253                    if (dumpState.onTitlePrinted())
12254                        pw.println();
12255                    pw.println("Verifiers:");
12256                    pw.print("  Required: ");
12257                    pw.print(mRequiredVerifierPackage);
12258                    pw.print(" (uid=");
12259                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12260                    pw.println(")");
12261                } else if (mRequiredVerifierPackage != null) {
12262                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12263                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12264                }
12265            }
12266
12267            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12268                boolean printedHeader = false;
12269                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12270                while (it.hasNext()) {
12271                    String name = it.next();
12272                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12273                    if (!checkin) {
12274                        if (!printedHeader) {
12275                            if (dumpState.onTitlePrinted())
12276                                pw.println();
12277                            pw.println("Libraries:");
12278                            printedHeader = true;
12279                        }
12280                        pw.print("  ");
12281                    } else {
12282                        pw.print("lib,");
12283                    }
12284                    pw.print(name);
12285                    if (!checkin) {
12286                        pw.print(" -> ");
12287                    }
12288                    if (ent.path != null) {
12289                        if (!checkin) {
12290                            pw.print("(jar) ");
12291                            pw.print(ent.path);
12292                        } else {
12293                            pw.print(",jar,");
12294                            pw.print(ent.path);
12295                        }
12296                    } else {
12297                        if (!checkin) {
12298                            pw.print("(apk) ");
12299                            pw.print(ent.apk);
12300                        } else {
12301                            pw.print(",apk,");
12302                            pw.print(ent.apk);
12303                        }
12304                    }
12305                    pw.println();
12306                }
12307            }
12308
12309            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12310                if (dumpState.onTitlePrinted())
12311                    pw.println();
12312                if (!checkin) {
12313                    pw.println("Features:");
12314                }
12315                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12316                while (it.hasNext()) {
12317                    String name = it.next();
12318                    if (!checkin) {
12319                        pw.print("  ");
12320                    } else {
12321                        pw.print("feat,");
12322                    }
12323                    pw.println(name);
12324                }
12325            }
12326
12327            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12328                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12329                        : "Activity Resolver Table:", "  ", packageName,
12330                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12331                    dumpState.setTitlePrinted(true);
12332                }
12333                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12334                        : "Receiver Resolver Table:", "  ", packageName,
12335                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12336                    dumpState.setTitlePrinted(true);
12337                }
12338                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12339                        : "Service Resolver Table:", "  ", packageName,
12340                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12341                    dumpState.setTitlePrinted(true);
12342                }
12343                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12344                        : "Provider Resolver Table:", "  ", packageName,
12345                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12346                    dumpState.setTitlePrinted(true);
12347                }
12348            }
12349
12350            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12351                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12352                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12353                    int user = mSettings.mPreferredActivities.keyAt(i);
12354                    if (pir.dump(pw,
12355                            dumpState.getTitlePrinted()
12356                                ? "\nPreferred Activities User " + user + ":"
12357                                : "Preferred Activities User " + user + ":", "  ",
12358                            packageName, true)) {
12359                        dumpState.setTitlePrinted(true);
12360                    }
12361                }
12362            }
12363
12364            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12365                pw.flush();
12366                FileOutputStream fout = new FileOutputStream(fd);
12367                BufferedOutputStream str = new BufferedOutputStream(fout);
12368                XmlSerializer serializer = new FastXmlSerializer();
12369                try {
12370                    serializer.setOutput(str, "utf-8");
12371                    serializer.startDocument(null, true);
12372                    serializer.setFeature(
12373                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12374                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12375                    serializer.endDocument();
12376                    serializer.flush();
12377                } catch (IllegalArgumentException e) {
12378                    pw.println("Failed writing: " + e);
12379                } catch (IllegalStateException e) {
12380                    pw.println("Failed writing: " + e);
12381                } catch (IOException e) {
12382                    pw.println("Failed writing: " + e);
12383                }
12384            }
12385
12386            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12387                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12388                if (packageName == null) {
12389                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12390                        if (iperm == 0) {
12391                            if (dumpState.onTitlePrinted())
12392                                pw.println();
12393                            pw.println("AppOp Permissions:");
12394                        }
12395                        pw.print("  AppOp Permission ");
12396                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12397                        pw.println(":");
12398                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12399                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12400                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12401                        }
12402                    }
12403                }
12404            }
12405
12406            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12407                boolean printedSomething = false;
12408                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12409                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12410                        continue;
12411                    }
12412                    if (!printedSomething) {
12413                        if (dumpState.onTitlePrinted())
12414                            pw.println();
12415                        pw.println("Registered ContentProviders:");
12416                        printedSomething = true;
12417                    }
12418                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12419                    pw.print("    "); pw.println(p.toString());
12420                }
12421                printedSomething = false;
12422                for (Map.Entry<String, PackageParser.Provider> entry :
12423                        mProvidersByAuthority.entrySet()) {
12424                    PackageParser.Provider p = entry.getValue();
12425                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12426                        continue;
12427                    }
12428                    if (!printedSomething) {
12429                        if (dumpState.onTitlePrinted())
12430                            pw.println();
12431                        pw.println("ContentProvider Authorities:");
12432                        printedSomething = true;
12433                    }
12434                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12435                    pw.print("    "); pw.println(p.toString());
12436                    if (p.info != null && p.info.applicationInfo != null) {
12437                        final String appInfo = p.info.applicationInfo.toString();
12438                        pw.print("      applicationInfo="); pw.println(appInfo);
12439                    }
12440                }
12441            }
12442
12443            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12444                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12445            }
12446
12447            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12448                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12449            }
12450
12451            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12452                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12453            }
12454
12455            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12456                // XXX should handle packageName != null by dumping only install data that
12457                // the given package is involved with.
12458                if (dumpState.onTitlePrinted()) pw.println();
12459                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12460            }
12461
12462            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12463                if (dumpState.onTitlePrinted()) pw.println();
12464                mSettings.dumpReadMessagesLPr(pw, dumpState);
12465
12466                pw.println();
12467                pw.println("Package warning messages:");
12468                final File fname = getSettingsProblemFile();
12469                FileInputStream in = null;
12470                try {
12471                    in = new FileInputStream(fname);
12472                    final int avail = in.available();
12473                    final byte[] data = new byte[avail];
12474                    in.read(data);
12475                    pw.print(new String(data));
12476                } catch (FileNotFoundException e) {
12477                } catch (IOException e) {
12478                } finally {
12479                    if (in != null) {
12480                        try {
12481                            in.close();
12482                        } catch (IOException e) {
12483                        }
12484                    }
12485                }
12486            }
12487        }
12488    }
12489
12490    // ------- apps on sdcard specific code -------
12491    static final boolean DEBUG_SD_INSTALL = false;
12492
12493    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12494
12495    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12496
12497    private boolean mMediaMounted = false;
12498
12499    static String getEncryptKey() {
12500        try {
12501            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12502                    SD_ENCRYPTION_KEYSTORE_NAME);
12503            if (sdEncKey == null) {
12504                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12505                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12506                if (sdEncKey == null) {
12507                    Slog.e(TAG, "Failed to create encryption keys");
12508                    return null;
12509                }
12510            }
12511            return sdEncKey;
12512        } catch (NoSuchAlgorithmException nsae) {
12513            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12514            return null;
12515        } catch (IOException ioe) {
12516            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12517            return null;
12518        }
12519    }
12520
12521    /*
12522     * Update media status on PackageManager.
12523     */
12524    @Override
12525    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12526        int callingUid = Binder.getCallingUid();
12527        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12528            throw new SecurityException("Media status can only be updated by the system");
12529        }
12530        // reader; this apparently protects mMediaMounted, but should probably
12531        // be a different lock in that case.
12532        synchronized (mPackages) {
12533            Log.i(TAG, "Updating external media status from "
12534                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12535                    + (mediaStatus ? "mounted" : "unmounted"));
12536            if (DEBUG_SD_INSTALL)
12537                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12538                        + ", mMediaMounted=" + mMediaMounted);
12539            if (mediaStatus == mMediaMounted) {
12540                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12541                        : 0, -1);
12542                mHandler.sendMessage(msg);
12543                return;
12544            }
12545            mMediaMounted = mediaStatus;
12546        }
12547        // Queue up an async operation since the package installation may take a
12548        // little while.
12549        mHandler.post(new Runnable() {
12550            public void run() {
12551                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12552            }
12553        });
12554    }
12555
12556    /**
12557     * Called by MountService when the initial ASECs to scan are available.
12558     * Should block until all the ASEC containers are finished being scanned.
12559     */
12560    public void scanAvailableAsecs() {
12561        updateExternalMediaStatusInner(true, false, false);
12562        if (mShouldRestoreconData) {
12563            SELinuxMMAC.setRestoreconDone();
12564            mShouldRestoreconData = false;
12565        }
12566    }
12567
12568    /*
12569     * Collect information of applications on external media, map them against
12570     * existing containers and update information based on current mount status.
12571     * Please note that we always have to report status if reportStatus has been
12572     * set to true especially when unloading packages.
12573     */
12574    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12575            boolean externalStorage) {
12576        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12577        int[] uidArr = EmptyArray.INT;
12578
12579        final String[] list = PackageHelper.getSecureContainerList();
12580        if (ArrayUtils.isEmpty(list)) {
12581            Log.i(TAG, "No secure containers found");
12582        } else {
12583            // Process list of secure containers and categorize them
12584            // as active or stale based on their package internal state.
12585
12586            // reader
12587            synchronized (mPackages) {
12588                for (String cid : list) {
12589                    // Leave stages untouched for now; installer service owns them
12590                    if (PackageInstallerService.isStageName(cid)) continue;
12591
12592                    if (DEBUG_SD_INSTALL)
12593                        Log.i(TAG, "Processing container " + cid);
12594                    String pkgName = getAsecPackageName(cid);
12595                    if (pkgName == null) {
12596                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12597                        continue;
12598                    }
12599                    if (DEBUG_SD_INSTALL)
12600                        Log.i(TAG, "Looking for pkg : " + pkgName);
12601
12602                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12603                    if (ps == null) {
12604                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12605                        continue;
12606                    }
12607
12608                    /*
12609                     * Skip packages that are not external if we're unmounting
12610                     * external storage.
12611                     */
12612                    if (externalStorage && !isMounted && !isExternal(ps)) {
12613                        continue;
12614                    }
12615
12616                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12617                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12618                    // The package status is changed only if the code path
12619                    // matches between settings and the container id.
12620                    if (ps.codePathString != null
12621                            && ps.codePathString.startsWith(args.getCodePath())) {
12622                        if (DEBUG_SD_INSTALL) {
12623                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12624                                    + " at code path: " + ps.codePathString);
12625                        }
12626
12627                        // We do have a valid package installed on sdcard
12628                        processCids.put(args, ps.codePathString);
12629                        final int uid = ps.appId;
12630                        if (uid != -1) {
12631                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12632                        }
12633                    } else {
12634                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12635                                + ps.codePathString);
12636                    }
12637                }
12638            }
12639
12640            Arrays.sort(uidArr);
12641        }
12642
12643        // Process packages with valid entries.
12644        if (isMounted) {
12645            if (DEBUG_SD_INSTALL)
12646                Log.i(TAG, "Loading packages");
12647            loadMediaPackages(processCids, uidArr);
12648            startCleaningPackages();
12649            mInstallerService.onSecureContainersAvailable();
12650        } else {
12651            if (DEBUG_SD_INSTALL)
12652                Log.i(TAG, "Unloading packages");
12653            unloadMediaPackages(processCids, uidArr, reportStatus);
12654        }
12655    }
12656
12657    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12658            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12659        int size = pkgList.size();
12660        if (size > 0) {
12661            // Send broadcasts here
12662            Bundle extras = new Bundle();
12663            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12664                    .toArray(new String[size]));
12665            if (uidArr != null) {
12666                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12667            }
12668            if (replacing) {
12669                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12670            }
12671            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12672                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12673            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12674        }
12675    }
12676
12677   /*
12678     * Look at potentially valid container ids from processCids If package
12679     * information doesn't match the one on record or package scanning fails,
12680     * the cid is added to list of removeCids. We currently don't delete stale
12681     * containers.
12682     */
12683    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12684        ArrayList<String> pkgList = new ArrayList<String>();
12685        Set<AsecInstallArgs> keys = processCids.keySet();
12686
12687        for (AsecInstallArgs args : keys) {
12688            String codePath = processCids.get(args);
12689            if (DEBUG_SD_INSTALL)
12690                Log.i(TAG, "Loading container : " + args.cid);
12691            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12692            try {
12693                // Make sure there are no container errors first.
12694                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12695                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12696                            + " when installing from sdcard");
12697                    continue;
12698                }
12699                // Check code path here.
12700                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12701                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12702                            + " does not match one in settings " + codePath);
12703                    continue;
12704                }
12705                // Parse package
12706                int parseFlags = mDefParseFlags;
12707                if (args.isExternal()) {
12708                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12709                }
12710                if (args.isFwdLocked()) {
12711                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12712                }
12713
12714                synchronized (mInstallLock) {
12715                    PackageParser.Package pkg = null;
12716                    try {
12717                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12718                    } catch (PackageManagerException e) {
12719                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12720                    }
12721                    // Scan the package
12722                    if (pkg != null) {
12723                        /*
12724                         * TODO why is the lock being held? doPostInstall is
12725                         * called in other places without the lock. This needs
12726                         * to be straightened out.
12727                         */
12728                        // writer
12729                        synchronized (mPackages) {
12730                            retCode = PackageManager.INSTALL_SUCCEEDED;
12731                            pkgList.add(pkg.packageName);
12732                            // Post process args
12733                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12734                                    pkg.applicationInfo.uid);
12735                        }
12736                    } else {
12737                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12738                    }
12739                }
12740
12741            } finally {
12742                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12743                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12744                }
12745            }
12746        }
12747        // writer
12748        synchronized (mPackages) {
12749            // If the platform SDK has changed since the last time we booted,
12750            // we need to re-grant app permission to catch any new ones that
12751            // appear. This is really a hack, and means that apps can in some
12752            // cases get permissions that the user didn't initially explicitly
12753            // allow... it would be nice to have some better way to handle
12754            // this situation.
12755            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12756            if (regrantPermissions)
12757                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12758                        + mSdkVersion + "; regranting permissions for external storage");
12759            mSettings.mExternalSdkPlatform = mSdkVersion;
12760
12761            // Make sure group IDs have been assigned, and any permission
12762            // changes in other apps are accounted for
12763            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12764                    | (regrantPermissions
12765                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12766                            : 0));
12767
12768            mSettings.updateExternalDatabaseVersion();
12769
12770            // can downgrade to reader
12771            // Persist settings
12772            mSettings.writeLPr();
12773        }
12774        // Send a broadcast to let everyone know we are done processing
12775        if (pkgList.size() > 0) {
12776            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12777        }
12778    }
12779
12780   /*
12781     * Utility method to unload a list of specified containers
12782     */
12783    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12784        // Just unmount all valid containers.
12785        for (AsecInstallArgs arg : cidArgs) {
12786            synchronized (mInstallLock) {
12787                arg.doPostDeleteLI(false);
12788           }
12789       }
12790   }
12791
12792    /*
12793     * Unload packages mounted on external media. This involves deleting package
12794     * data from internal structures, sending broadcasts about diabled packages,
12795     * gc'ing to free up references, unmounting all secure containers
12796     * corresponding to packages on external media, and posting a
12797     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12798     * that we always have to post this message if status has been requested no
12799     * matter what.
12800     */
12801    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12802            final boolean reportStatus) {
12803        if (DEBUG_SD_INSTALL)
12804            Log.i(TAG, "unloading media packages");
12805        ArrayList<String> pkgList = new ArrayList<String>();
12806        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12807        final Set<AsecInstallArgs> keys = processCids.keySet();
12808        for (AsecInstallArgs args : keys) {
12809            String pkgName = args.getPackageName();
12810            if (DEBUG_SD_INSTALL)
12811                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12812            // Delete package internally
12813            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12814            synchronized (mInstallLock) {
12815                boolean res = deletePackageLI(pkgName, null, false, null, null,
12816                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12817                if (res) {
12818                    pkgList.add(pkgName);
12819                } else {
12820                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12821                    failedList.add(args);
12822                }
12823            }
12824        }
12825
12826        // reader
12827        synchronized (mPackages) {
12828            // We didn't update the settings after removing each package;
12829            // write them now for all packages.
12830            mSettings.writeLPr();
12831        }
12832
12833        // We have to absolutely send UPDATED_MEDIA_STATUS only
12834        // after confirming that all the receivers processed the ordered
12835        // broadcast when packages get disabled, force a gc to clean things up.
12836        // and unload all the containers.
12837        if (pkgList.size() > 0) {
12838            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12839                    new IIntentReceiver.Stub() {
12840                public void performReceive(Intent intent, int resultCode, String data,
12841                        Bundle extras, boolean ordered, boolean sticky,
12842                        int sendingUser) throws RemoteException {
12843                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12844                            reportStatus ? 1 : 0, 1, keys);
12845                    mHandler.sendMessage(msg);
12846                }
12847            });
12848        } else {
12849            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12850                    keys);
12851            mHandler.sendMessage(msg);
12852        }
12853    }
12854
12855    /** Binder call */
12856    @Override
12857    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12858            final int flags) {
12859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12860        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12861        int returnCode = PackageManager.MOVE_SUCCEEDED;
12862        int currInstallFlags = 0;
12863        int newInstallFlags = 0;
12864
12865        File codeFile = null;
12866        String installerPackageName = null;
12867        String packageAbiOverride = null;
12868
12869        // reader
12870        synchronized (mPackages) {
12871            final PackageParser.Package pkg = mPackages.get(packageName);
12872            final PackageSetting ps = mSettings.mPackages.get(packageName);
12873            if (pkg == null || ps == null) {
12874                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12875            } else {
12876                // Disable moving fwd locked apps and system packages
12877                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12878                    Slog.w(TAG, "Cannot move system application");
12879                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12880                } else if (pkg.mOperationPending) {
12881                    Slog.w(TAG, "Attempt to move package which has pending operations");
12882                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12883                } else {
12884                    // Find install location first
12885                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12886                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12887                        Slog.w(TAG, "Ambigous flags specified for move location.");
12888                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12889                    } else {
12890                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12891                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12892                        currInstallFlags = isExternal(pkg)
12893                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12894
12895                        if (newInstallFlags == currInstallFlags) {
12896                            Slog.w(TAG, "No move required. Trying to move to same location");
12897                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12898                        } else {
12899                            if (isForwardLocked(pkg)) {
12900                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12901                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12902                            }
12903                        }
12904                    }
12905                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12906                        pkg.mOperationPending = true;
12907                    }
12908                }
12909
12910                codeFile = new File(pkg.codePath);
12911                installerPackageName = ps.installerPackageName;
12912                packageAbiOverride = ps.cpuAbiOverrideString;
12913            }
12914        }
12915
12916        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12917            try {
12918                observer.packageMoved(packageName, returnCode);
12919            } catch (RemoteException ignored) {
12920            }
12921            return;
12922        }
12923
12924        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12925            @Override
12926            public void onUserActionRequired(Intent intent) throws RemoteException {
12927                throw new IllegalStateException();
12928            }
12929
12930            @Override
12931            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12932                    Bundle extras) throws RemoteException {
12933                Slog.d(TAG, "Install result for move: "
12934                        + PackageManager.installStatusToString(returnCode, msg));
12935
12936                // We usually have a new package now after the install, but if
12937                // we failed we need to clear the pending flag on the original
12938                // package object.
12939                synchronized (mPackages) {
12940                    final PackageParser.Package pkg = mPackages.get(packageName);
12941                    if (pkg != null) {
12942                        pkg.mOperationPending = false;
12943                    }
12944                }
12945
12946                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12947                switch (status) {
12948                    case PackageInstaller.STATUS_SUCCESS:
12949                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12950                        break;
12951                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12952                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12953                        break;
12954                    default:
12955                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12956                        break;
12957                }
12958            }
12959        };
12960
12961        // Treat a move like reinstalling an existing app, which ensures that we
12962        // process everythign uniformly, like unpacking native libraries.
12963        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12964
12965        final Message msg = mHandler.obtainMessage(INIT_COPY);
12966        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12967        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12968                installerPackageName, null, user, packageAbiOverride);
12969        mHandler.sendMessage(msg);
12970    }
12971
12972    @Override
12973    public boolean setInstallLocation(int loc) {
12974        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12975                null);
12976        if (getInstallLocation() == loc) {
12977            return true;
12978        }
12979        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12980                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12981            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12982                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12983            return true;
12984        }
12985        return false;
12986   }
12987
12988    @Override
12989    public int getInstallLocation() {
12990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12991                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12992                PackageHelper.APP_INSTALL_AUTO);
12993    }
12994
12995    /** Called by UserManagerService */
12996    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12997        mDirtyUsers.remove(userHandle);
12998        mSettings.removeUserLPw(userHandle);
12999        mPendingBroadcasts.remove(userHandle);
13000        if (mInstaller != null) {
13001            // Technically, we shouldn't be doing this with the package lock
13002            // held.  However, this is very rare, and there is already so much
13003            // other disk I/O going on, that we'll let it slide for now.
13004            mInstaller.removeUserDataDirs(userHandle);
13005        }
13006        mUserNeedsBadging.delete(userHandle);
13007        removeUnusedPackagesLILPw(userManager, userHandle);
13008    }
13009
13010    /**
13011     * We're removing userHandle and would like to remove any downloaded packages
13012     * that are no longer in use by any other user.
13013     * @param userHandle the user being removed
13014     */
13015    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13016        final boolean DEBUG_CLEAN_APKS = false;
13017        int [] users = userManager.getUserIdsLPr();
13018        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13019        while (psit.hasNext()) {
13020            PackageSetting ps = psit.next();
13021            if (ps.pkg == null) {
13022                continue;
13023            }
13024            final String packageName = ps.pkg.packageName;
13025            // Skip over if system app
13026            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13027                continue;
13028            }
13029            if (DEBUG_CLEAN_APKS) {
13030                Slog.i(TAG, "Checking package " + packageName);
13031            }
13032            boolean keep = false;
13033            for (int i = 0; i < users.length; i++) {
13034                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13035                    keep = true;
13036                    if (DEBUG_CLEAN_APKS) {
13037                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13038                                + users[i]);
13039                    }
13040                    break;
13041                }
13042            }
13043            if (!keep) {
13044                if (DEBUG_CLEAN_APKS) {
13045                    Slog.i(TAG, "  Removing package " + packageName);
13046                }
13047                mHandler.post(new Runnable() {
13048                    public void run() {
13049                        deletePackageX(packageName, userHandle, 0);
13050                    } //end run
13051                });
13052            }
13053        }
13054    }
13055
13056    /** Called by UserManagerService */
13057    void createNewUserLILPw(int userHandle, File path) {
13058        if (mInstaller != null) {
13059            mInstaller.createUserConfig(userHandle);
13060            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13061        }
13062    }
13063
13064    @Override
13065    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13066        mContext.enforceCallingOrSelfPermission(
13067                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13068                "Only package verification agents can read the verifier device identity");
13069
13070        synchronized (mPackages) {
13071            return mSettings.getVerifierDeviceIdentityLPw();
13072        }
13073    }
13074
13075    @Override
13076    public void setPermissionEnforced(String permission, boolean enforced) {
13077        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13078        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13079            synchronized (mPackages) {
13080                if (mSettings.mReadExternalStorageEnforced == null
13081                        || mSettings.mReadExternalStorageEnforced != enforced) {
13082                    mSettings.mReadExternalStorageEnforced = enforced;
13083                    mSettings.writeLPr();
13084                }
13085            }
13086            // kill any non-foreground processes so we restart them and
13087            // grant/revoke the GID.
13088            final IActivityManager am = ActivityManagerNative.getDefault();
13089            if (am != null) {
13090                final long token = Binder.clearCallingIdentity();
13091                try {
13092                    am.killProcessesBelowForeground("setPermissionEnforcement");
13093                } catch (RemoteException e) {
13094                } finally {
13095                    Binder.restoreCallingIdentity(token);
13096                }
13097            }
13098        } else {
13099            throw new IllegalArgumentException("No selective enforcement for " + permission);
13100        }
13101    }
13102
13103    @Override
13104    @Deprecated
13105    public boolean isPermissionEnforced(String permission) {
13106        return true;
13107    }
13108
13109    @Override
13110    public boolean isStorageLow() {
13111        final long token = Binder.clearCallingIdentity();
13112        try {
13113            final DeviceStorageMonitorInternal
13114                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13115            if (dsm != null) {
13116                return dsm.isMemoryLow();
13117            } else {
13118                return false;
13119            }
13120        } finally {
13121            Binder.restoreCallingIdentity(token);
13122        }
13123    }
13124
13125    @Override
13126    public IPackageInstaller getPackageInstaller() {
13127        return mInstallerService;
13128    }
13129
13130    private boolean userNeedsBadging(int userId) {
13131        int index = mUserNeedsBadging.indexOfKey(userId);
13132        if (index < 0) {
13133            final UserInfo userInfo;
13134            final long token = Binder.clearCallingIdentity();
13135            try {
13136                userInfo = sUserManager.getUserInfo(userId);
13137            } finally {
13138                Binder.restoreCallingIdentity(token);
13139            }
13140            final boolean b;
13141            if (userInfo != null && userInfo.isManagedProfile()) {
13142                b = true;
13143            } else {
13144                b = false;
13145            }
13146            mUserNeedsBadging.put(userId, b);
13147            return b;
13148        }
13149        return mUserNeedsBadging.valueAt(index);
13150    }
13151
13152    @Override
13153    public KeySet getKeySetByAlias(String packageName, String alias) {
13154        if (packageName == null || alias == null) {
13155            return null;
13156        }
13157        synchronized(mPackages) {
13158            final PackageParser.Package pkg = mPackages.get(packageName);
13159            if (pkg == null) {
13160                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13161                throw new IllegalArgumentException("Unknown package: " + packageName);
13162            }
13163            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13164            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13165        }
13166    }
13167
13168    @Override
13169    public KeySet getSigningKeySet(String packageName) {
13170        if (packageName == null) {
13171            return null;
13172        }
13173        synchronized(mPackages) {
13174            final PackageParser.Package pkg = mPackages.get(packageName);
13175            if (pkg == null) {
13176                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13177                throw new IllegalArgumentException("Unknown package: " + packageName);
13178            }
13179            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13180                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13181                throw new SecurityException("May not access signing KeySet of other apps.");
13182            }
13183            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13184            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13185        }
13186    }
13187
13188    @Override
13189    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13190        if (packageName == null || ks == null) {
13191            return false;
13192        }
13193        synchronized(mPackages) {
13194            final PackageParser.Package pkg = mPackages.get(packageName);
13195            if (pkg == null) {
13196                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13197                throw new IllegalArgumentException("Unknown package: " + packageName);
13198            }
13199            IBinder ksh = ks.getToken();
13200            if (ksh instanceof KeySetHandle) {
13201                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13202                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13203            }
13204            return false;
13205        }
13206    }
13207
13208    @Override
13209    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13210        if (packageName == null || ks == null) {
13211            return false;
13212        }
13213        synchronized(mPackages) {
13214            final PackageParser.Package pkg = mPackages.get(packageName);
13215            if (pkg == null) {
13216                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13217                throw new IllegalArgumentException("Unknown package: " + packageName);
13218            }
13219            IBinder ksh = ks.getToken();
13220            if (ksh instanceof KeySetHandle) {
13221                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13222                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13223            }
13224            return false;
13225        }
13226    }
13227}
13228