PackageManagerService.java revision a39871ef5e9bf6703f18af0725484b06f5c78216
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.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Objects;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214import libcore.util.EmptyArray;
215
216/**
217 * Keep track of all those .apks everywhere.
218 *
219 * This is very central to the platform's security; please run the unit
220 * tests whenever making modifications here:
221 *
222mmm frameworks/base/tests/AndroidTests
223adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
224adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
225 *
226 * {@hide}
227 */
228public class PackageManagerService extends IPackageManager.Stub {
229    static final String TAG = "PackageManager";
230    static final boolean DEBUG_SETTINGS = false;
231    static final boolean DEBUG_PREFERRED = false;
232    static final boolean DEBUG_UPGRADE = false;
233    private static final boolean DEBUG_INSTALL = false;
234    private static final boolean DEBUG_REMOVE = false;
235    private static final boolean DEBUG_BROADCASTS = false;
236    private static final boolean DEBUG_SHOW_INFO = false;
237    private static final boolean DEBUG_PACKAGE_INFO = false;
238    private static final boolean DEBUG_INTENT_MATCHING = false;
239    private static final boolean DEBUG_PACKAGE_SCANNING = false;
240    private static final boolean DEBUG_VERIFY = false;
241    private static final boolean DEBUG_DEXOPT = false;
242    private static final boolean DEBUG_ABI_SELECTION = false;
243
244    private static final int RADIO_UID = Process.PHONE_UID;
245    private static final int LOG_UID = Process.LOG_UID;
246    private static final int NFC_UID = Process.NFC_UID;
247    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
248    private static final int SHELL_UID = Process.SHELL_UID;
249
250    // Cap the size of permission trees that 3rd party apps can define
251    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
252
253    // Suffix used during package installation when copying/moving
254    // package apks to install directory.
255    private static final String INSTALL_PACKAGE_SUFFIX = "-";
256
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267    static final int SCAN_REPLACING = 1<<11;
268
269    static final int REMOVE_CHATTY = 1<<16;
270
271    /**
272     * Timeout (in milliseconds) after which the watchdog should declare that
273     * our handler thread is wedged.  The usual default for such things is one
274     * minute but we sometimes do very lengthy I/O operations on this thread,
275     * such as installing multi-gigabyte applications, so ours needs to be longer.
276     */
277    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
278
279    /**
280     * Whether verification is enabled by default.
281     */
282    private static final boolean DEFAULT_VERIFY_ENABLE = true;
283
284    /**
285     * The default maximum time to wait for the verification agent to return in
286     * milliseconds.
287     */
288    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
289
290    /**
291     * The default response for package verification timeout.
292     *
293     * This can be either PackageManager.VERIFICATION_ALLOW or
294     * PackageManager.VERIFICATION_REJECT.
295     */
296    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
297
298    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
299
300    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
301            DEFAULT_CONTAINER_PACKAGE,
302            "com.android.defcontainer.DefaultContainerService");
303
304    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
305
306    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
307
308    private static String sPreferredInstructionSet;
309
310    final ServiceThread mHandlerThread;
311
312    private static final String IDMAP_PREFIX = "/data/resource-cache/";
313    private static final String IDMAP_SUFFIX = "@idmap";
314
315    final PackageHandler mHandler;
316
317    /**
318     * Messages for {@link #mHandler} that need to wait for system ready before
319     * being dispatched.
320     */
321    private ArrayList<Message> mPostSystemReadyMessages;
322
323    final int mSdkVersion = Build.VERSION.SDK_INT;
324
325    final Context mContext;
326    final boolean mFactoryTest;
327    final boolean mOnlyCore;
328    final boolean mLazyDexOpt;
329    final DisplayMetrics mMetrics;
330    final int mDefParseFlags;
331    final String[] mSeparateProcesses;
332
333    // This is where all application persistent data goes.
334    final File mAppDataDir;
335
336    // This is where all application persistent data goes for secondary users.
337    final File mUserAppDataDir;
338
339    /** The location for ASEC container files on internal storage. */
340    final String mAsecInternalPath;
341
342    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
343    // LOCK HELD.  Can be called with mInstallLock held.
344    final Installer mInstaller;
345
346    /** Directory where installed third-party apps stored */
347    final File mAppInstallDir;
348
349    /**
350     * Directory to which applications installed internally have their
351     * 32 bit native libraries copied.
352     */
353    private File mAppLib32InstallDir;
354
355    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
356    // apps.
357    final File mDrmAppPrivateInstallDir;
358
359    // ----------------------------------------------------------------
360
361    // Lock for state used when installing and doing other long running
362    // operations.  Methods that must be called with this lock held have
363    // the suffix "LI".
364    final Object mInstallLock = new Object();
365
366    // ----------------------------------------------------------------
367
368    // Keys are String (package name), values are Package.  This also serves
369    // as the lock for the global state.  Methods that must be called with
370    // this lock held have the prefix "LP".
371    final HashMap<String, PackageParser.Package> mPackages =
372            new HashMap<String, PackageParser.Package>();
373
374    // Tracks available target package names -> overlay package paths.
375    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
376        new HashMap<String, HashMap<String, PackageParser.Package>>();
377
378    final Settings mSettings;
379    boolean mRestoredSettings;
380
381    // System configuration read by SystemConfig.
382    final int[] mGlobalGids;
383    final SparseArray<HashSet<String>> mSystemPermissions;
384    final HashMap<String, FeatureInfo> mAvailableFeatures;
385
386    // If mac_permissions.xml was found for seinfo labeling.
387    boolean mFoundPolicyFile;
388
389    // If a recursive restorecon of /data/data/<pkg> is needed.
390    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
391
392    public static final class SharedLibraryEntry {
393        public final String path;
394        public final String apk;
395
396        SharedLibraryEntry(String _path, String _apk) {
397            path = _path;
398            apk = _apk;
399        }
400    }
401
402    // Currently known shared libraries.
403    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
404            new HashMap<String, SharedLibraryEntry>();
405
406    // All available activities, for your resolving pleasure.
407    final ActivityIntentResolver mActivities =
408            new ActivityIntentResolver();
409
410    // All available receivers, for your resolving pleasure.
411    final ActivityIntentResolver mReceivers =
412            new ActivityIntentResolver();
413
414    // All available services, for your resolving pleasure.
415    final ServiceIntentResolver mServices = new ServiceIntentResolver();
416
417    // All available providers, for your resolving pleasure.
418    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
419
420    // Mapping from provider base names (first directory in content URI codePath)
421    // to the provider information.
422    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
423            new HashMap<String, PackageParser.Provider>();
424
425    // Mapping from instrumentation class names to info about them.
426    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
427            new HashMap<ComponentName, PackageParser.Instrumentation>();
428
429    // Mapping from permission names to info about them.
430    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
431            new HashMap<String, PackageParser.PermissionGroup>();
432
433    // Packages whose data we have transfered into another package, thus
434    // should no longer exist.
435    final HashSet<String> mTransferedPackages = new HashSet<String>();
436
437    // Broadcast actions that are only available to the system.
438    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
439
440    /** List of packages waiting for verification. */
441    final SparseArray<PackageVerificationState> mPendingVerification
442            = new SparseArray<PackageVerificationState>();
443
444    /** Set of packages associated with each app op permission. */
445    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
446
447    final PackageInstallerService mInstallerService;
448
449    HashSet<PackageParser.Package> mDeferredDexOpt = null;
450
451    // Cache of users who need badging.
452    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
453
454    /** Token for keys in mPendingVerification. */
455    private int mPendingVerificationToken = 0;
456
457    volatile boolean mSystemReady;
458    volatile boolean mSafeMode;
459    volatile boolean mHasSystemUidErrors;
460
461    ApplicationInfo mAndroidApplication;
462    final ActivityInfo mResolveActivity = new ActivityInfo();
463    final ResolveInfo mResolveInfo = new ResolveInfo();
464    ComponentName mResolveComponentName;
465    PackageParser.Package mPlatformPackage;
466    ComponentName mCustomResolverComponentName;
467
468    boolean mResolverReplaced = false;
469
470    // Set of pending broadcasts for aggregating enable/disable of components.
471    static class PendingPackageBroadcasts {
472        // for each user id, a map of <package name -> components within that package>
473        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
474
475        public PendingPackageBroadcasts() {
476            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
477        }
478
479        public ArrayList<String> get(int userId, String packageName) {
480            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
481            return packages.get(packageName);
482        }
483
484        public void put(int userId, String packageName, ArrayList<String> components) {
485            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
486            packages.put(packageName, components);
487        }
488
489        public void remove(int userId, String packageName) {
490            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
491            if (packages != null) {
492                packages.remove(packageName);
493            }
494        }
495
496        public void remove(int userId) {
497            mUidMap.remove(userId);
498        }
499
500        public int userIdCount() {
501            return mUidMap.size();
502        }
503
504        public int userIdAt(int n) {
505            return mUidMap.keyAt(n);
506        }
507
508        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
509            return mUidMap.get(userId);
510        }
511
512        public int size() {
513            // total number of pending broadcast entries across all userIds
514            int num = 0;
515            for (int i = 0; i< mUidMap.size(); i++) {
516                num += mUidMap.valueAt(i).size();
517            }
518            return num;
519        }
520
521        public void clear() {
522            mUidMap.clear();
523        }
524
525        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
526            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
527            if (map == null) {
528                map = new HashMap<String, ArrayList<String>>();
529                mUidMap.put(userId, map);
530            }
531            return map;
532        }
533    }
534    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
535
536    // Service Connection to remote media container service to copy
537    // package uri's from external media onto secure containers
538    // or internal storage.
539    private IMediaContainerService mContainerService = null;
540
541    static final int SEND_PENDING_BROADCAST = 1;
542    static final int MCS_BOUND = 3;
543    static final int END_COPY = 4;
544    static final int INIT_COPY = 5;
545    static final int MCS_UNBIND = 6;
546    static final int START_CLEANING_PACKAGE = 7;
547    static final int FIND_INSTALL_LOC = 8;
548    static final int POST_INSTALL = 9;
549    static final int MCS_RECONNECT = 10;
550    static final int MCS_GIVE_UP = 11;
551    static final int UPDATED_MEDIA_STATUS = 12;
552    static final int WRITE_SETTINGS = 13;
553    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
554    static final int PACKAGE_VERIFIED = 15;
555    static final int CHECK_PENDING_VERIFICATION = 16;
556
557    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
558
559    // Delay time in millisecs
560    static final int BROADCAST_DELAY = 10 * 1000;
561
562    static UserManagerService sUserManager;
563
564    // Stores a list of users whose package restrictions file needs to be updated
565    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
566
567    final private DefaultContainerConnection mDefContainerConn =
568            new DefaultContainerConnection();
569    class DefaultContainerConnection implements ServiceConnection {
570        public void onServiceConnected(ComponentName name, IBinder service) {
571            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
572            IMediaContainerService imcs =
573                IMediaContainerService.Stub.asInterface(service);
574            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
575        }
576
577        public void onServiceDisconnected(ComponentName name) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
579        }
580    };
581
582    // Recordkeeping of restore-after-install operations that are currently in flight
583    // between the Package Manager and the Backup Manager
584    class PostInstallData {
585        public InstallArgs args;
586        public PackageInstalledInfo res;
587
588        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
589            args = _a;
590            res = _r;
591        }
592    };
593    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
594    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
595
596    private final String mRequiredVerifierPackage;
597
598    private final PackageUsage mPackageUsage = new PackageUsage();
599
600    private class PackageUsage {
601        private static final int WRITE_INTERVAL
602            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
603
604        private final Object mFileLock = new Object();
605        private final AtomicLong mLastWritten = new AtomicLong(0);
606        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
607
608        private boolean mIsHistoricalPackageUsageAvailable = true;
609
610        boolean isHistoricalPackageUsageAvailable() {
611            return mIsHistoricalPackageUsageAvailable;
612        }
613
614        void write(boolean force) {
615            if (force) {
616                writeInternal();
617                return;
618            }
619            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
620                && !DEBUG_DEXOPT) {
621                return;
622            }
623            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
624                new Thread("PackageUsage_DiskWriter") {
625                    @Override
626                    public void run() {
627                        try {
628                            writeInternal();
629                        } finally {
630                            mBackgroundWriteRunning.set(false);
631                        }
632                    }
633                }.start();
634            }
635        }
636
637        private void writeInternal() {
638            synchronized (mPackages) {
639                synchronized (mFileLock) {
640                    AtomicFile file = getFile();
641                    FileOutputStream f = null;
642                    try {
643                        f = file.startWrite();
644                        BufferedOutputStream out = new BufferedOutputStream(f);
645                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
646                        StringBuilder sb = new StringBuilder();
647                        for (PackageParser.Package pkg : mPackages.values()) {
648                            if (pkg.mLastPackageUsageTimeInMills == 0) {
649                                continue;
650                            }
651                            sb.setLength(0);
652                            sb.append(pkg.packageName);
653                            sb.append(' ');
654                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
655                            sb.append('\n');
656                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
657                        }
658                        out.flush();
659                        file.finishWrite(f);
660                    } catch (IOException e) {
661                        if (f != null) {
662                            file.failWrite(f);
663                        }
664                        Log.e(TAG, "Failed to write package usage times", e);
665                    }
666                }
667            }
668            mLastWritten.set(SystemClock.elapsedRealtime());
669        }
670
671        void readLP() {
672            synchronized (mFileLock) {
673                AtomicFile file = getFile();
674                BufferedInputStream in = null;
675                try {
676                    in = new BufferedInputStream(file.openRead());
677                    StringBuffer sb = new StringBuffer();
678                    while (true) {
679                        String packageName = readToken(in, sb, ' ');
680                        if (packageName == null) {
681                            break;
682                        }
683                        String timeInMillisString = readToken(in, sb, '\n');
684                        if (timeInMillisString == null) {
685                            throw new IOException("Failed to find last usage time for package "
686                                                  + packageName);
687                        }
688                        PackageParser.Package pkg = mPackages.get(packageName);
689                        if (pkg == null) {
690                            continue;
691                        }
692                        long timeInMillis;
693                        try {
694                            timeInMillis = Long.parseLong(timeInMillisString.toString());
695                        } catch (NumberFormatException e) {
696                            throw new IOException("Failed to parse " + timeInMillisString
697                                                  + " as a long.", e);
698                        }
699                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
700                    }
701                } catch (FileNotFoundException expected) {
702                    mIsHistoricalPackageUsageAvailable = false;
703                } catch (IOException e) {
704                    Log.w(TAG, "Failed to read package usage times", e);
705                } finally {
706                    IoUtils.closeQuietly(in);
707                }
708            }
709            mLastWritten.set(SystemClock.elapsedRealtime());
710        }
711
712        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
713                throws IOException {
714            sb.setLength(0);
715            while (true) {
716                int ch = in.read();
717                if (ch == -1) {
718                    if (sb.length() == 0) {
719                        return null;
720                    }
721                    throw new IOException("Unexpected EOF");
722                }
723                if (ch == endOfToken) {
724                    return sb.toString();
725                }
726                sb.append((char)ch);
727            }
728        }
729
730        private AtomicFile getFile() {
731            File dataDir = Environment.getDataDirectory();
732            File systemDir = new File(dataDir, "system");
733            File fname = new File(systemDir, "package-usage.list");
734            return new AtomicFile(fname);
735        }
736    }
737
738    class PackageHandler extends Handler {
739        private boolean mBound = false;
740        final ArrayList<HandlerParams> mPendingInstalls =
741            new ArrayList<HandlerParams>();
742
743        private boolean connectToService() {
744            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
745                    " DefaultContainerService");
746            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
747            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
748            if (mContext.bindServiceAsUser(service, mDefContainerConn,
749                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
750                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751                mBound = true;
752                return true;
753            }
754            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755            return false;
756        }
757
758        private void disconnectService() {
759            mContainerService = null;
760            mBound = false;
761            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
762            mContext.unbindService(mDefContainerConn);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764        }
765
766        PackageHandler(Looper looper) {
767            super(looper);
768        }
769
770        public void handleMessage(Message msg) {
771            try {
772                doHandleMessage(msg);
773            } finally {
774                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            }
776        }
777
778        void doHandleMessage(Message msg) {
779            switch (msg.what) {
780                case INIT_COPY: {
781                    HandlerParams params = (HandlerParams) msg.obj;
782                    int idx = mPendingInstalls.size();
783                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
784                    // If a bind was already initiated we dont really
785                    // need to do anything. The pending install
786                    // will be processed later on.
787                    if (!mBound) {
788                        // If this is the only one pending we might
789                        // have to bind to the service again.
790                        if (!connectToService()) {
791                            Slog.e(TAG, "Failed to bind to media container service");
792                            params.serviceError();
793                            return;
794                        } else {
795                            // Once we bind to the service, the first
796                            // pending request will be processed.
797                            mPendingInstalls.add(idx, params);
798                        }
799                    } else {
800                        mPendingInstalls.add(idx, params);
801                        // Already bound to the service. Just make
802                        // sure we trigger off processing the first request.
803                        if (idx == 0) {
804                            mHandler.sendEmptyMessage(MCS_BOUND);
805                        }
806                    }
807                    break;
808                }
809                case MCS_BOUND: {
810                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
811                    if (msg.obj != null) {
812                        mContainerService = (IMediaContainerService) msg.obj;
813                    }
814                    if (mContainerService == null) {
815                        // Something seriously wrong. Bail out
816                        Slog.e(TAG, "Cannot bind to media container service");
817                        for (HandlerParams params : mPendingInstalls) {
818                            // Indicate service bind error
819                            params.serviceError();
820                        }
821                        mPendingInstalls.clear();
822                    } else if (mPendingInstalls.size() > 0) {
823                        HandlerParams params = mPendingInstalls.get(0);
824                        if (params != null) {
825                            if (params.startCopy()) {
826                                // We are done...  look for more work or to
827                                // go idle.
828                                if (DEBUG_SD_INSTALL) Log.i(TAG,
829                                        "Checking for more work or unbind...");
830                                // Delete pending install
831                                if (mPendingInstalls.size() > 0) {
832                                    mPendingInstalls.remove(0);
833                                }
834                                if (mPendingInstalls.size() == 0) {
835                                    if (mBound) {
836                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
837                                                "Posting delayed MCS_UNBIND");
838                                        removeMessages(MCS_UNBIND);
839                                        Message ubmsg = obtainMessage(MCS_UNBIND);
840                                        // Unbind after a little delay, to avoid
841                                        // continual thrashing.
842                                        sendMessageDelayed(ubmsg, 10000);
843                                    }
844                                } else {
845                                    // There are more pending requests in queue.
846                                    // Just post MCS_BOUND message to trigger processing
847                                    // of next pending install.
848                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                            "Posting MCS_BOUND for next work");
850                                    mHandler.sendEmptyMessage(MCS_BOUND);
851                                }
852                            }
853                        }
854                    } else {
855                        // Should never happen ideally.
856                        Slog.w(TAG, "Empty queue");
857                    }
858                    break;
859                }
860                case MCS_RECONNECT: {
861                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
862                    if (mPendingInstalls.size() > 0) {
863                        if (mBound) {
864                            disconnectService();
865                        }
866                        if (!connectToService()) {
867                            Slog.e(TAG, "Failed to bind to media container service");
868                            for (HandlerParams params : mPendingInstalls) {
869                                // Indicate service bind error
870                                params.serviceError();
871                            }
872                            mPendingInstalls.clear();
873                        }
874                    }
875                    break;
876                }
877                case MCS_UNBIND: {
878                    // If there is no actual work left, then time to unbind.
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
880
881                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
882                        if (mBound) {
883                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
884
885                            disconnectService();
886                        }
887                    } else if (mPendingInstalls.size() > 0) {
888                        // There are more pending requests in queue.
889                        // Just post MCS_BOUND message to trigger processing
890                        // of next pending install.
891                        mHandler.sendEmptyMessage(MCS_BOUND);
892                    }
893
894                    break;
895                }
896                case MCS_GIVE_UP: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
898                    mPendingInstalls.remove(0);
899                    break;
900                }
901                case SEND_PENDING_BROADCAST: {
902                    String packages[];
903                    ArrayList<String> components[];
904                    int size = 0;
905                    int uids[];
906                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
907                    synchronized (mPackages) {
908                        if (mPendingBroadcasts == null) {
909                            return;
910                        }
911                        size = mPendingBroadcasts.size();
912                        if (size <= 0) {
913                            // Nothing to be done. Just return
914                            return;
915                        }
916                        packages = new String[size];
917                        components = new ArrayList[size];
918                        uids = new int[size];
919                        int i = 0;  // filling out the above arrays
920
921                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
922                            int packageUserId = mPendingBroadcasts.userIdAt(n);
923                            Iterator<Map.Entry<String, ArrayList<String>>> it
924                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
925                                            .entrySet().iterator();
926                            while (it.hasNext() && i < size) {
927                                Map.Entry<String, ArrayList<String>> ent = it.next();
928                                packages[i] = ent.getKey();
929                                components[i] = ent.getValue();
930                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
931                                uids[i] = (ps != null)
932                                        ? UserHandle.getUid(packageUserId, ps.appId)
933                                        : -1;
934                                i++;
935                            }
936                        }
937                        size = i;
938                        mPendingBroadcasts.clear();
939                    }
940                    // Send broadcasts
941                    for (int i = 0; i < size; i++) {
942                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
943                    }
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
945                    break;
946                }
947                case START_CLEANING_PACKAGE: {
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
949                    final String packageName = (String)msg.obj;
950                    final int userId = msg.arg1;
951                    final boolean andCode = msg.arg2 != 0;
952                    synchronized (mPackages) {
953                        if (userId == UserHandle.USER_ALL) {
954                            int[] users = sUserManager.getUserIds();
955                            for (int user : users) {
956                                mSettings.addPackageToCleanLPw(
957                                        new PackageCleanItem(user, packageName, andCode));
958                            }
959                        } else {
960                            mSettings.addPackageToCleanLPw(
961                                    new PackageCleanItem(userId, packageName, andCode));
962                        }
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    startCleaningPackages();
966                } break;
967                case POST_INSTALL: {
968                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
969                    PostInstallData data = mRunningInstalls.get(msg.arg1);
970                    mRunningInstalls.delete(msg.arg1);
971                    boolean deleteOld = false;
972
973                    if (data != null) {
974                        InstallArgs args = data.args;
975                        PackageInstalledInfo res = data.res;
976
977                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
978                            res.removedInfo.sendBroadcast(false, true, false);
979                            Bundle extras = new Bundle(1);
980                            extras.putInt(Intent.EXTRA_UID, res.uid);
981                            // Determine the set of users who are adding this
982                            // package for the first time vs. those who are seeing
983                            // an update.
984                            int[] firstUsers;
985                            int[] updateUsers = new int[0];
986                            if (res.origUsers == null || res.origUsers.length == 0) {
987                                firstUsers = res.newUsers;
988                            } else {
989                                firstUsers = new int[0];
990                                for (int i=0; i<res.newUsers.length; i++) {
991                                    int user = res.newUsers[i];
992                                    boolean isNew = true;
993                                    for (int j=0; j<res.origUsers.length; j++) {
994                                        if (res.origUsers[j] == user) {
995                                            isNew = false;
996                                            break;
997                                        }
998                                    }
999                                    if (isNew) {
1000                                        int[] newFirst = new int[firstUsers.length+1];
1001                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1002                                                firstUsers.length);
1003                                        newFirst[firstUsers.length] = user;
1004                                        firstUsers = newFirst;
1005                                    } else {
1006                                        int[] newUpdate = new int[updateUsers.length+1];
1007                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1008                                                updateUsers.length);
1009                                        newUpdate[updateUsers.length] = user;
1010                                        updateUsers = newUpdate;
1011                                    }
1012                                }
1013                            }
1014                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1015                                    res.pkg.applicationInfo.packageName,
1016                                    extras, null, null, firstUsers);
1017                            final boolean update = res.removedInfo.removedPackage != null;
1018                            if (update) {
1019                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, updateUsers);
1024                            if (update) {
1025                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1026                                        res.pkg.applicationInfo.packageName,
1027                                        extras, null, null, updateUsers);
1028                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1029                                        null, null,
1030                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1031
1032                                // treat asec-hosted packages like removable media on upgrade
1033                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1034                                    if (DEBUG_INSTALL) {
1035                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1036                                                + " is ASEC-hosted -> AVAILABLE");
1037                                    }
1038                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1039                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1040                                    pkgList.add(res.pkg.applicationInfo.packageName);
1041                                    sendResourcesChangedBroadcast(true, true,
1042                                            pkgList,uidArray, null);
1043                                }
1044                            }
1045                            if (res.removedInfo.args != null) {
1046                                // Remove the replaced package's older resources safely now
1047                                deleteOld = true;
1048                            }
1049
1050                            // Log current value of "unknown sources" setting
1051                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1052                                getUnknownSourcesSettings());
1053                        }
1054                        // Force a gc to clear up things
1055                        Runtime.getRuntime().gc();
1056                        // We delete after a gc for applications  on sdcard.
1057                        if (deleteOld) {
1058                            synchronized (mInstallLock) {
1059                                res.removedInfo.args.doPostDeleteLI(true);
1060                            }
1061                        }
1062                        if (args.observer != null) {
1063                            try {
1064                                Bundle extras = extrasForInstallResult(res);
1065                                args.observer.onPackageInstalled(res.name, res.returnCode,
1066                                        res.returnMsg, extras);
1067                            } catch (RemoteException e) {
1068                                Slog.i(TAG, "Observer no longer exists.");
1069                            }
1070                        }
1071                    } else {
1072                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1073                    }
1074                } break;
1075                case UPDATED_MEDIA_STATUS: {
1076                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1077                    boolean reportStatus = msg.arg1 == 1;
1078                    boolean doGc = msg.arg2 == 1;
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1080                    if (doGc) {
1081                        // Force a gc to clear up stale containers.
1082                        Runtime.getRuntime().gc();
1083                    }
1084                    if (msg.obj != null) {
1085                        @SuppressWarnings("unchecked")
1086                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1087                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1088                        // Unload containers
1089                        unloadAllContainers(args);
1090                    }
1091                    if (reportStatus) {
1092                        try {
1093                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1094                            PackageHelper.getMountService().finishMediaUpdate();
1095                        } catch (RemoteException e) {
1096                            Log.e(TAG, "MountService not running?");
1097                        }
1098                    }
1099                } break;
1100                case WRITE_SETTINGS: {
1101                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1102                    synchronized (mPackages) {
1103                        removeMessages(WRITE_SETTINGS);
1104                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1105                        mSettings.writeLPr();
1106                        mDirtyUsers.clear();
1107                    }
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109                } break;
1110                case WRITE_PACKAGE_RESTRICTIONS: {
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112                    synchronized (mPackages) {
1113                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1114                        for (int userId : mDirtyUsers) {
1115                            mSettings.writePackageRestrictionsLPr(userId);
1116                        }
1117                        mDirtyUsers.clear();
1118                    }
1119                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1120                } break;
1121                case CHECK_PENDING_VERIFICATION: {
1122                    final int verificationId = msg.arg1;
1123                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1124
1125                    if ((state != null) && !state.timeoutExtended()) {
1126                        final InstallArgs args = state.getInstallArgs();
1127                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1128
1129                        Slog.i(TAG, "Verification timed out for " + originUri);
1130                        mPendingVerification.remove(verificationId);
1131
1132                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1133
1134                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1135                            Slog.i(TAG, "Continuing with installation of " + originUri);
1136                            state.setVerifierResponse(Binder.getCallingUid(),
1137                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1138                            broadcastPackageVerified(verificationId, originUri,
1139                                    PackageManager.VERIFICATION_ALLOW,
1140                                    state.getInstallArgs().getUser());
1141                            try {
1142                                ret = args.copyApk(mContainerService, true);
1143                            } catch (RemoteException e) {
1144                                Slog.e(TAG, "Could not contact the ContainerService");
1145                            }
1146                        } else {
1147                            broadcastPackageVerified(verificationId, originUri,
1148                                    PackageManager.VERIFICATION_REJECT,
1149                                    state.getInstallArgs().getUser());
1150                        }
1151
1152                        processPendingInstall(args, ret);
1153                        mHandler.sendEmptyMessage(MCS_UNBIND);
1154                    }
1155                    break;
1156                }
1157                case PACKAGE_VERIFIED: {
1158                    final int verificationId = msg.arg1;
1159
1160                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1161                    if (state == null) {
1162                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1163                        break;
1164                    }
1165
1166                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1167
1168                    state.setVerifierResponse(response.callerUid, response.code);
1169
1170                    if (state.isVerificationComplete()) {
1171                        mPendingVerification.remove(verificationId);
1172
1173                        final InstallArgs args = state.getInstallArgs();
1174                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1175
1176                        int ret;
1177                        if (state.isInstallAllowed()) {
1178                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1179                            broadcastPackageVerified(verificationId, originUri,
1180                                    response.code, state.getInstallArgs().getUser());
1181                            try {
1182                                ret = args.copyApk(mContainerService, true);
1183                            } catch (RemoteException e) {
1184                                Slog.e(TAG, "Could not contact the ContainerService");
1185                            }
1186                        } else {
1187                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1188                        }
1189
1190                        processPendingInstall(args, ret);
1191
1192                        mHandler.sendEmptyMessage(MCS_UNBIND);
1193                    }
1194
1195                    break;
1196                }
1197            }
1198        }
1199    }
1200
1201    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1202        Bundle extras = null;
1203        switch (res.returnCode) {
1204            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1205                extras = new Bundle();
1206                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1207                        res.origPermission);
1208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1209                        res.origPackage);
1210                break;
1211            }
1212        }
1213        return extras;
1214    }
1215
1216    void scheduleWriteSettingsLocked() {
1217        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1218            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1219        }
1220    }
1221
1222    void scheduleWritePackageRestrictionsLocked(int userId) {
1223        if (!sUserManager.exists(userId)) return;
1224        mDirtyUsers.add(userId);
1225        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1226            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1227        }
1228    }
1229
1230    public static final PackageManagerService main(Context context, Installer installer,
1231            boolean factoryTest, boolean onlyCore) {
1232        PackageManagerService m = new PackageManagerService(context, installer,
1233                factoryTest, onlyCore);
1234        ServiceManager.addService("package", m);
1235        return m;
1236    }
1237
1238    static String[] splitString(String str, char sep) {
1239        int count = 1;
1240        int i = 0;
1241        while ((i=str.indexOf(sep, i)) >= 0) {
1242            count++;
1243            i++;
1244        }
1245
1246        String[] res = new String[count];
1247        i=0;
1248        count = 0;
1249        int lastI=0;
1250        while ((i=str.indexOf(sep, i)) >= 0) {
1251            res[count] = str.substring(lastI, i);
1252            count++;
1253            i++;
1254            lastI = i;
1255        }
1256        res[count] = str.substring(lastI, str.length());
1257        return res;
1258    }
1259
1260    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1261        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1262                Context.DISPLAY_SERVICE);
1263        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1264    }
1265
1266    public PackageManagerService(Context context, Installer installer,
1267            boolean factoryTest, boolean onlyCore) {
1268        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1269                SystemClock.uptimeMillis());
1270
1271        if (mSdkVersion <= 0) {
1272            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1273        }
1274
1275        mContext = context;
1276        mFactoryTest = factoryTest;
1277        mOnlyCore = onlyCore;
1278        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1279        mMetrics = new DisplayMetrics();
1280        mSettings = new Settings(context);
1281        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1282                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1283        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293
1294        String separateProcesses = SystemProperties.get("debug.separate_processes");
1295        if (separateProcesses != null && separateProcesses.length() > 0) {
1296            if ("*".equals(separateProcesses)) {
1297                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1298                mSeparateProcesses = null;
1299                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1300            } else {
1301                mDefParseFlags = 0;
1302                mSeparateProcesses = separateProcesses.split(",");
1303                Slog.w(TAG, "Running with debug.separate_processes: "
1304                        + separateProcesses);
1305            }
1306        } else {
1307            mDefParseFlags = 0;
1308            mSeparateProcesses = null;
1309        }
1310
1311        mInstaller = installer;
1312
1313        getDefaultDisplayMetrics(context, mMetrics);
1314
1315        SystemConfig systemConfig = SystemConfig.getInstance();
1316        mGlobalGids = systemConfig.getGlobalGids();
1317        mSystemPermissions = systemConfig.getSystemPermissions();
1318        mAvailableFeatures = systemConfig.getAvailableFeatures();
1319
1320        synchronized (mInstallLock) {
1321        // writer
1322        synchronized (mPackages) {
1323            mHandlerThread = new ServiceThread(TAG,
1324                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1325            mHandlerThread.start();
1326            mHandler = new PackageHandler(mHandlerThread.getLooper());
1327            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1328
1329            File dataDir = Environment.getDataDirectory();
1330            mAppDataDir = new File(dataDir, "data");
1331            mAppInstallDir = new File(dataDir, "app");
1332            mAppLib32InstallDir = new File(dataDir, "app-lib");
1333            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1334            mUserAppDataDir = new File(dataDir, "user");
1335            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1336
1337            sUserManager = new UserManagerService(context, this,
1338                    mInstallLock, mPackages);
1339
1340            // Propagate permission configuration in to package manager.
1341            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1342                    = systemConfig.getPermissions();
1343            for (int i=0; i<permConfig.size(); i++) {
1344                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1345                BasePermission bp = mSettings.mPermissions.get(perm.name);
1346                if (bp == null) {
1347                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1348                    mSettings.mPermissions.put(perm.name, bp);
1349                }
1350                if (perm.gids != null) {
1351                    bp.gids = appendInts(bp.gids, perm.gids);
1352                }
1353            }
1354
1355            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1356            for (int i=0; i<libConfig.size(); i++) {
1357                mSharedLibraries.put(libConfig.keyAt(i),
1358                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1359            }
1360
1361            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1362
1363            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1364                    mSdkVersion, mOnlyCore);
1365
1366            String customResolverActivity = Resources.getSystem().getString(
1367                    R.string.config_customResolverActivity);
1368            if (TextUtils.isEmpty(customResolverActivity)) {
1369                customResolverActivity = null;
1370            } else {
1371                mCustomResolverComponentName = ComponentName.unflattenFromString(
1372                        customResolverActivity);
1373            }
1374
1375            long startTime = SystemClock.uptimeMillis();
1376
1377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1378                    startTime);
1379
1380            // Set flag to monitor and not change apk file paths when
1381            // scanning install directories.
1382            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1383
1384            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1385
1386            /**
1387             * Add everything in the in the boot class path to the
1388             * list of process files because dexopt will have been run
1389             * if necessary during zygote startup.
1390             */
1391            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1392            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1393
1394            if (bootClassPath != null) {
1395                String[] bootClassPathElements = splitString(bootClassPath, ':');
1396                for (String element : bootClassPathElements) {
1397                    alreadyDexOpted.add(element);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            if (systemServerClassPath != null) {
1404                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1405                for (String element : systemServerClassPathElements) {
1406                    alreadyDexOpted.add(element);
1407                }
1408            } else {
1409                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1410            }
1411
1412            boolean didDexOptLibraryOrTool = false;
1413
1414            final List<String> allInstructionSets = getAllInstructionSets();
1415            final String[] dexCodeInstructionSets =
1416                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1417
1418            /**
1419             * Ensure all external libraries have had dexopt run on them.
1420             */
1421            if (mSharedLibraries.size() > 0) {
1422                // NOTE: For now, we're compiling these system "shared libraries"
1423                // (and framework jars) into all available architectures. It's possible
1424                // to compile them only when we come across an app that uses them (there's
1425                // already logic for that in scanPackageLI) but that adds some complexity.
1426                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1427                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1428                        final String lib = libEntry.path;
1429                        if (lib == null) {
1430                            continue;
1431                        }
1432
1433                        try {
1434                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1435                                                                                 dexCodeInstructionSet,
1436                                                                                 false);
1437                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1438                                alreadyDexOpted.add(lib);
1439
1440                                // The list of "shared libraries" we have at this point is
1441                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1442                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1443                                } else {
1444                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1445                                }
1446                                didDexOptLibraryOrTool = true;
1447                            }
1448                        } catch (FileNotFoundException e) {
1449                            Slog.w(TAG, "Library not found: " + lib);
1450                        } catch (IOException e) {
1451                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1452                                    + e.getMessage());
1453                        }
1454                    }
1455                }
1456            }
1457
1458            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1459
1460            // Gross hack for now: we know this file doesn't contain any
1461            // code, so don't dexopt it to avoid the resulting log spew.
1462            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1463
1464            // Gross hack for now: we know this file is only part of
1465            // the boot class path for art, so don't dexopt it to
1466            // avoid the resulting log spew.
1467            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1468
1469            /**
1470             * And there are a number of commands implemented in Java, which
1471             * we currently need to do the dexopt on so that they can be
1472             * run from a non-root shell.
1473             */
1474            String[] frameworkFiles = frameworkDir.list();
1475            if (frameworkFiles != null) {
1476                // TODO: We could compile these only for the most preferred ABI. We should
1477                // first double check that the dex files for these commands are not referenced
1478                // by other system apps.
1479                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1480                    for (int i=0; i<frameworkFiles.length; i++) {
1481                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1482                        String path = libPath.getPath();
1483                        // Skip the file if we already did it.
1484                        if (alreadyDexOpted.contains(path)) {
1485                            continue;
1486                        }
1487                        // Skip the file if it is not a type we want to dexopt.
1488                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1489                            continue;
1490                        }
1491                        try {
1492                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1493                                                                                 dexCodeInstructionSet,
1494                                                                                 false);
1495                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1496                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1497                                didDexOptLibraryOrTool = true;
1498                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1499                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1500                                didDexOptLibraryOrTool = true;
1501                            }
1502                        } catch (FileNotFoundException e) {
1503                            Slog.w(TAG, "Jar not found: " + path);
1504                        } catch (IOException e) {
1505                            Slog.w(TAG, "Exception reading jar: " + path, e);
1506                        }
1507                    }
1508                }
1509            }
1510
1511            // Collect vendor overlay packages.
1512            // (Do this before scanning any apps.)
1513            // For security and version matching reason, only consider
1514            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1515            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1516            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1517                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1518
1519            // Find base frameworks (resource packages without code).
1520            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR
1522                    | PackageParser.PARSE_IS_PRIVILEGED,
1523                    scanFlags | SCAN_NO_DEX, 0);
1524
1525            // Collected privileged system packages.
1526            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1527            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1528                    | PackageParser.PARSE_IS_SYSTEM_DIR
1529                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1530
1531            // Collect ordinary system packages.
1532            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1533            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1534                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1535
1536            // Collect all vendor packages.
1537            File vendorAppDir = new File("/vendor/app");
1538            try {
1539                vendorAppDir = vendorAppDir.getCanonicalFile();
1540            } catch (IOException e) {
1541                // failed to look up canonical path, continue with original one
1542            }
1543            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1544                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1545
1546            // Collect all OEM packages.
1547            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1548            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1549                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1550
1551            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1552            mInstaller.moveFiles();
1553
1554            // Prune any system packages that no longer exist.
1555            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1556            if (!mOnlyCore) {
1557                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1558                while (psit.hasNext()) {
1559                    PackageSetting ps = psit.next();
1560
1561                    /*
1562                     * If this is not a system app, it can't be a
1563                     * disable system app.
1564                     */
1565                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1566                        continue;
1567                    }
1568
1569                    /*
1570                     * If the package is scanned, it's not erased.
1571                     */
1572                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1573                    if (scannedPkg != null) {
1574                        /*
1575                         * If the system app is both scanned and in the
1576                         * disabled packages list, then it must have been
1577                         * added via OTA. Remove it from the currently
1578                         * scanned package so the previously user-installed
1579                         * application can be scanned.
1580                         */
1581                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1582                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1583                                    + "; removing system app");
1584                            removePackageLI(ps, true);
1585                        }
1586
1587                        continue;
1588                    }
1589
1590                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1591                        psit.remove();
1592                        String msg = "System package " + ps.name
1593                                + " no longer exists; wiping its data";
1594                        reportSettingsProblem(Log.WARN, msg);
1595                        removeDataDirsLI(ps.name);
1596                    } else {
1597                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1598                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1599                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1600                        }
1601                    }
1602                }
1603            }
1604
1605            //look for any incomplete package installations
1606            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1607            //clean up list
1608            for(int i = 0; i < deletePkgsList.size(); i++) {
1609                //clean up here
1610                cleanupInstallFailedPackage(deletePkgsList.get(i));
1611            }
1612            //delete tmp files
1613            deleteTempPackageFiles();
1614
1615            // Remove any shared userIDs that have no associated packages
1616            mSettings.pruneSharedUsersLPw();
1617
1618            if (!mOnlyCore) {
1619                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1620                        SystemClock.uptimeMillis());
1621                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1622
1623                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1624                        scanFlags, 0);
1625
1626                /**
1627                 * Remove disable package settings for any updated system
1628                 * apps that were removed via an OTA. If they're not a
1629                 * previously-updated app, remove them completely.
1630                 * Otherwise, just revoke their system-level permissions.
1631                 */
1632                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1633                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1634                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1635
1636                    String msg;
1637                    if (deletedPkg == null) {
1638                        msg = "Updated system package " + deletedAppName
1639                                + " no longer exists; wiping its data";
1640                        removeDataDirsLI(deletedAppName);
1641                    } else {
1642                        msg = "Updated system app + " + deletedAppName
1643                                + " no longer present; removing system privileges for "
1644                                + deletedAppName;
1645
1646                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1647
1648                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1649                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1650                    }
1651                    reportSettingsProblem(Log.WARN, msg);
1652                }
1653            }
1654
1655            // Now that we know all of the shared libraries, update all clients to have
1656            // the correct library paths.
1657            updateAllSharedLibrariesLPw();
1658
1659            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1660                // NOTE: We ignore potential failures here during a system scan (like
1661                // the rest of the commands above) because there's precious little we
1662                // can do about it. A settings error is reported, though.
1663                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1664                        false /* force dexopt */, false /* defer dexopt */);
1665            }
1666
1667            // Now that we know all the packages we are keeping,
1668            // read and update their last usage times.
1669            mPackageUsage.readLP();
1670
1671            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1672                    SystemClock.uptimeMillis());
1673            Slog.i(TAG, "Time to scan packages: "
1674                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1675                    + " seconds");
1676
1677            // If the platform SDK has changed since the last time we booted,
1678            // we need to re-grant app permission to catch any new ones that
1679            // appear.  This is really a hack, and means that apps can in some
1680            // cases get permissions that the user didn't initially explicitly
1681            // allow...  it would be nice to have some better way to handle
1682            // this situation.
1683            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1684                    != mSdkVersion;
1685            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1686                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1687                    + "; regranting permissions for internal storage");
1688            mSettings.mInternalSdkPlatform = mSdkVersion;
1689
1690            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1691                    | (regrantPermissions
1692                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1693                            : 0));
1694
1695            // If this is the first boot, and it is a normal boot, then
1696            // we need to initialize the default preferred apps.
1697            if (!mRestoredSettings && !onlyCore) {
1698                mSettings.readDefaultPreferredAppsLPw(this, 0);
1699            }
1700
1701            // If this is first boot after an OTA, and a normal boot, then
1702            // we need to clear code cache directories.
1703            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1704                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1705                for (String pkgName : mSettings.mPackages.keySet()) {
1706                    deleteCodeCacheDirsLI(pkgName);
1707                }
1708                mSettings.mFingerprint = Build.FINGERPRINT;
1709            }
1710
1711            // All the changes are done during package scanning.
1712            mSettings.updateInternalDatabaseVersion();
1713
1714            // can downgrade to reader
1715            mSettings.writeLPr();
1716
1717            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1718                    SystemClock.uptimeMillis());
1719
1720
1721            mRequiredVerifierPackage = getRequiredVerifierLPr();
1722        } // synchronized (mPackages)
1723        } // synchronized (mInstallLock)
1724
1725        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1726
1727        // Now after opening every single application zip, make sure they
1728        // are all flushed.  Not really needed, but keeps things nice and
1729        // tidy.
1730        Runtime.getRuntime().gc();
1731    }
1732
1733    @Override
1734    public boolean isFirstBoot() {
1735        return !mRestoredSettings;
1736    }
1737
1738    @Override
1739    public boolean isOnlyCoreApps() {
1740        return mOnlyCore;
1741    }
1742
1743    private String getRequiredVerifierLPr() {
1744        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1745        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1746                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1747
1748        String requiredVerifier = null;
1749
1750        final int N = receivers.size();
1751        for (int i = 0; i < N; i++) {
1752            final ResolveInfo info = receivers.get(i);
1753
1754            if (info.activityInfo == null) {
1755                continue;
1756            }
1757
1758            final String packageName = info.activityInfo.packageName;
1759
1760            final PackageSetting ps = mSettings.mPackages.get(packageName);
1761            if (ps == null) {
1762                continue;
1763            }
1764
1765            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1766            if (!gp.grantedPermissions
1767                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1768                continue;
1769            }
1770
1771            if (requiredVerifier != null) {
1772                throw new RuntimeException("There can be only one required verifier");
1773            }
1774
1775            requiredVerifier = packageName;
1776        }
1777
1778        return requiredVerifier;
1779    }
1780
1781    @Override
1782    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1783            throws RemoteException {
1784        try {
1785            return super.onTransact(code, data, reply, flags);
1786        } catch (RuntimeException e) {
1787            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1788                Slog.wtf(TAG, "Package Manager Crash", e);
1789            }
1790            throw e;
1791        }
1792    }
1793
1794    void cleanupInstallFailedPackage(PackageSetting ps) {
1795        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1796        removeDataDirsLI(ps.name);
1797        if (ps.codePath != null) {
1798            if (ps.codePath.isDirectory()) {
1799                FileUtils.deleteContents(ps.codePath);
1800            }
1801            ps.codePath.delete();
1802        }
1803        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1804            if (ps.resourcePath.isDirectory()) {
1805                FileUtils.deleteContents(ps.resourcePath);
1806            }
1807            ps.resourcePath.delete();
1808        }
1809        mSettings.removePackageLPw(ps.name);
1810    }
1811
1812    static int[] appendInts(int[] cur, int[] add) {
1813        if (add == null) return cur;
1814        if (cur == null) return add;
1815        final int N = add.length;
1816        for (int i=0; i<N; i++) {
1817            cur = appendInt(cur, add[i]);
1818        }
1819        return cur;
1820    }
1821
1822    static int[] removeInts(int[] cur, int[] rem) {
1823        if (rem == null) return cur;
1824        if (cur == null) return cur;
1825        final int N = rem.length;
1826        for (int i=0; i<N; i++) {
1827            cur = removeInt(cur, rem[i]);
1828        }
1829        return cur;
1830    }
1831
1832    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1833        if (!sUserManager.exists(userId)) return null;
1834        final PackageSetting ps = (PackageSetting) p.mExtras;
1835        if (ps == null) {
1836            return null;
1837        }
1838        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1839        final PackageUserState state = ps.readUserState(userId);
1840        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1841                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1842                state, userId);
1843    }
1844
1845    @Override
1846    public boolean isPackageAvailable(String packageName, int userId) {
1847        if (!sUserManager.exists(userId)) return false;
1848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1849        synchronized (mPackages) {
1850            PackageParser.Package p = mPackages.get(packageName);
1851            if (p != null) {
1852                final PackageSetting ps = (PackageSetting) p.mExtras;
1853                if (ps != null) {
1854                    final PackageUserState state = ps.readUserState(userId);
1855                    if (state != null) {
1856                        return PackageParser.isAvailable(state);
1857                    }
1858                }
1859            }
1860        }
1861        return false;
1862    }
1863
1864    @Override
1865    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1866        if (!sUserManager.exists(userId)) return null;
1867        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1868        // reader
1869        synchronized (mPackages) {
1870            PackageParser.Package p = mPackages.get(packageName);
1871            if (DEBUG_PACKAGE_INFO)
1872                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1873            if (p != null) {
1874                return generatePackageInfo(p, flags, userId);
1875            }
1876            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1877                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1878            }
1879        }
1880        return null;
1881    }
1882
1883    @Override
1884    public String[] currentToCanonicalPackageNames(String[] names) {
1885        String[] out = new String[names.length];
1886        // reader
1887        synchronized (mPackages) {
1888            for (int i=names.length-1; i>=0; i--) {
1889                PackageSetting ps = mSettings.mPackages.get(names[i]);
1890                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1891            }
1892        }
1893        return out;
1894    }
1895
1896    @Override
1897    public String[] canonicalToCurrentPackageNames(String[] names) {
1898        String[] out = new String[names.length];
1899        // reader
1900        synchronized (mPackages) {
1901            for (int i=names.length-1; i>=0; i--) {
1902                String cur = mSettings.mRenamedPackages.get(names[i]);
1903                out[i] = cur != null ? cur : names[i];
1904            }
1905        }
1906        return out;
1907    }
1908
1909    @Override
1910    public int getPackageUid(String packageName, int userId) {
1911        if (!sUserManager.exists(userId)) return -1;
1912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1913        // reader
1914        synchronized (mPackages) {
1915            PackageParser.Package p = mPackages.get(packageName);
1916            if(p != null) {
1917                return UserHandle.getUid(userId, p.applicationInfo.uid);
1918            }
1919            PackageSetting ps = mSettings.mPackages.get(packageName);
1920            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1921                return -1;
1922            }
1923            p = ps.pkg;
1924            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1925        }
1926    }
1927
1928    @Override
1929    public int[] getPackageGids(String packageName) {
1930        // reader
1931        synchronized (mPackages) {
1932            PackageParser.Package p = mPackages.get(packageName);
1933            if (DEBUG_PACKAGE_INFO)
1934                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1935            if (p != null) {
1936                final PackageSetting ps = (PackageSetting)p.mExtras;
1937                return ps.getGids();
1938            }
1939        }
1940        // stupid thing to indicate an error.
1941        return new int[0];
1942    }
1943
1944    static final PermissionInfo generatePermissionInfo(
1945            BasePermission bp, int flags) {
1946        if (bp.perm != null) {
1947            return PackageParser.generatePermissionInfo(bp.perm, flags);
1948        }
1949        PermissionInfo pi = new PermissionInfo();
1950        pi.name = bp.name;
1951        pi.packageName = bp.sourcePackage;
1952        pi.nonLocalizedLabel = bp.name;
1953        pi.protectionLevel = bp.protectionLevel;
1954        return pi;
1955    }
1956
1957    @Override
1958    public PermissionInfo getPermissionInfo(String name, int flags) {
1959        // reader
1960        synchronized (mPackages) {
1961            final BasePermission p = mSettings.mPermissions.get(name);
1962            if (p != null) {
1963                return generatePermissionInfo(p, flags);
1964            }
1965            return null;
1966        }
1967    }
1968
1969    @Override
1970    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1971        // reader
1972        synchronized (mPackages) {
1973            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1974            for (BasePermission p : mSettings.mPermissions.values()) {
1975                if (group == null) {
1976                    if (p.perm == null || p.perm.info.group == null) {
1977                        out.add(generatePermissionInfo(p, flags));
1978                    }
1979                } else {
1980                    if (p.perm != null && group.equals(p.perm.info.group)) {
1981                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1982                    }
1983                }
1984            }
1985
1986            if (out.size() > 0) {
1987                return out;
1988            }
1989            return mPermissionGroups.containsKey(group) ? out : null;
1990        }
1991    }
1992
1993    @Override
1994    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1995        // reader
1996        synchronized (mPackages) {
1997            return PackageParser.generatePermissionGroupInfo(
1998                    mPermissionGroups.get(name), flags);
1999        }
2000    }
2001
2002    @Override
2003    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2004        // reader
2005        synchronized (mPackages) {
2006            final int N = mPermissionGroups.size();
2007            ArrayList<PermissionGroupInfo> out
2008                    = new ArrayList<PermissionGroupInfo>(N);
2009            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2010                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2011            }
2012            return out;
2013        }
2014    }
2015
2016    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2017            int userId) {
2018        if (!sUserManager.exists(userId)) return null;
2019        PackageSetting ps = mSettings.mPackages.get(packageName);
2020        if (ps != null) {
2021            if (ps.pkg == null) {
2022                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2023                        flags, userId);
2024                if (pInfo != null) {
2025                    return pInfo.applicationInfo;
2026                }
2027                return null;
2028            }
2029            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2030                    ps.readUserState(userId), userId);
2031        }
2032        return null;
2033    }
2034
2035    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2036            int userId) {
2037        if (!sUserManager.exists(userId)) return null;
2038        PackageSetting ps = mSettings.mPackages.get(packageName);
2039        if (ps != null) {
2040            PackageParser.Package pkg = ps.pkg;
2041            if (pkg == null) {
2042                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2043                    return null;
2044                }
2045                // Only data remains, so we aren't worried about code paths
2046                pkg = new PackageParser.Package(packageName);
2047                pkg.applicationInfo.packageName = packageName;
2048                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2049                pkg.applicationInfo.dataDir =
2050                        getDataPathForPackage(packageName, 0).getPath();
2051                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2052                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2053            }
2054            return generatePackageInfo(pkg, flags, userId);
2055        }
2056        return null;
2057    }
2058
2059    @Override
2060    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2061        if (!sUserManager.exists(userId)) return null;
2062        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2063        // writer
2064        synchronized (mPackages) {
2065            PackageParser.Package p = mPackages.get(packageName);
2066            if (DEBUG_PACKAGE_INFO) Log.v(
2067                    TAG, "getApplicationInfo " + packageName
2068                    + ": " + p);
2069            if (p != null) {
2070                PackageSetting ps = mSettings.mPackages.get(packageName);
2071                if (ps == null) return null;
2072                // Note: isEnabledLP() does not apply here - always return info
2073                return PackageParser.generateApplicationInfo(
2074                        p, flags, ps.readUserState(userId), userId);
2075            }
2076            if ("android".equals(packageName)||"system".equals(packageName)) {
2077                return mAndroidApplication;
2078            }
2079            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2080                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2081            }
2082        }
2083        return null;
2084    }
2085
2086
2087    @Override
2088    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2089        mContext.enforceCallingOrSelfPermission(
2090                android.Manifest.permission.CLEAR_APP_CACHE, null);
2091        // Queue up an async operation since clearing cache may take a little while.
2092        mHandler.post(new Runnable() {
2093            public void run() {
2094                mHandler.removeCallbacks(this);
2095                int retCode = -1;
2096                synchronized (mInstallLock) {
2097                    retCode = mInstaller.freeCache(freeStorageSize);
2098                    if (retCode < 0) {
2099                        Slog.w(TAG, "Couldn't clear application caches");
2100                    }
2101                }
2102                if (observer != null) {
2103                    try {
2104                        observer.onRemoveCompleted(null, (retCode >= 0));
2105                    } catch (RemoteException e) {
2106                        Slog.w(TAG, "RemoveException when invoking call back");
2107                    }
2108                }
2109            }
2110        });
2111    }
2112
2113    @Override
2114    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2115        mContext.enforceCallingOrSelfPermission(
2116                android.Manifest.permission.CLEAR_APP_CACHE, null);
2117        // Queue up an async operation since clearing cache may take a little while.
2118        mHandler.post(new Runnable() {
2119            public void run() {
2120                mHandler.removeCallbacks(this);
2121                int retCode = -1;
2122                synchronized (mInstallLock) {
2123                    retCode = mInstaller.freeCache(freeStorageSize);
2124                    if (retCode < 0) {
2125                        Slog.w(TAG, "Couldn't clear application caches");
2126                    }
2127                }
2128                if(pi != null) {
2129                    try {
2130                        // Callback via pending intent
2131                        int code = (retCode >= 0) ? 1 : 0;
2132                        pi.sendIntent(null, code, null,
2133                                null, null);
2134                    } catch (SendIntentException e1) {
2135                        Slog.i(TAG, "Failed to send pending intent");
2136                    }
2137                }
2138            }
2139        });
2140    }
2141
2142    void freeStorage(long freeStorageSize) throws IOException {
2143        synchronized (mInstallLock) {
2144            if (mInstaller.freeCache(freeStorageSize) < 0) {
2145                throw new IOException("Failed to free enough space");
2146            }
2147        }
2148    }
2149
2150    @Override
2151    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2152        if (!sUserManager.exists(userId)) return null;
2153        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2154        synchronized (mPackages) {
2155            PackageParser.Activity a = mActivities.mActivities.get(component);
2156
2157            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2158            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2159                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2160                if (ps == null) return null;
2161                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2162                        userId);
2163            }
2164            if (mResolveComponentName.equals(component)) {
2165                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2166                        new PackageUserState(), userId);
2167            }
2168        }
2169        return null;
2170    }
2171
2172    @Override
2173    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2174            String resolvedType) {
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177            if (a == null) {
2178                return false;
2179            }
2180            for (int i=0; i<a.intents.size(); i++) {
2181                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2182                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2183                    return true;
2184                }
2185            }
2186            return false;
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mReceivers.mActivities.get(component);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                TAG, "getReceiverInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2212        synchronized (mPackages) {
2213            PackageParser.Service s = mServices.mServices.get(component);
2214            if (DEBUG_PACKAGE_INFO) Log.v(
2215                TAG, "getServiceInfo " + component + ": " + s);
2216            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2230        synchronized (mPackages) {
2231            PackageParser.Provider p = mProviders.mProviders.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getProviderInfo " + component + ": " + p);
2234            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public String[] getSystemSharedLibraryNames() {
2246        Set<String> libSet;
2247        synchronized (mPackages) {
2248            libSet = mSharedLibraries.keySet();
2249            int size = libSet.size();
2250            if (size > 0) {
2251                String[] libs = new String[size];
2252                libSet.toArray(libs);
2253                return libs;
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public FeatureInfo[] getSystemAvailableFeatures() {
2261        Collection<FeatureInfo> featSet;
2262        synchronized (mPackages) {
2263            featSet = mAvailableFeatures.values();
2264            int size = featSet.size();
2265            if (size > 0) {
2266                FeatureInfo[] features = new FeatureInfo[size+1];
2267                featSet.toArray(features);
2268                FeatureInfo fi = new FeatureInfo();
2269                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2270                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2271                features[size] = fi;
2272                return features;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public boolean hasSystemFeature(String name) {
2280        synchronized (mPackages) {
2281            return mAvailableFeatures.containsKey(name);
2282        }
2283    }
2284
2285    private void checkValidCaller(int uid, int userId) {
2286        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2287            return;
2288
2289        throw new SecurityException("Caller uid=" + uid
2290                + " is not privileged to communicate with user=" + userId);
2291    }
2292
2293    @Override
2294    public int checkPermission(String permName, String pkgName) {
2295        synchronized (mPackages) {
2296            PackageParser.Package p = mPackages.get(pkgName);
2297            if (p != null && p.mExtras != null) {
2298                PackageSetting ps = (PackageSetting)p.mExtras;
2299                if (ps.sharedUser != null) {
2300                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2301                        return PackageManager.PERMISSION_GRANTED;
2302                    }
2303                } else if (ps.grantedPermissions.contains(permName)) {
2304                    return PackageManager.PERMISSION_GRANTED;
2305                }
2306            }
2307        }
2308        return PackageManager.PERMISSION_DENIED;
2309    }
2310
2311    @Override
2312    public int checkUidPermission(String permName, int uid) {
2313        synchronized (mPackages) {
2314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2315            if (obj != null) {
2316                GrantedPermissions gp = (GrantedPermissions)obj;
2317                if (gp.grantedPermissions.contains(permName)) {
2318                    return PackageManager.PERMISSION_GRANTED;
2319                }
2320            } else {
2321                HashSet<String> perms = mSystemPermissions.get(uid);
2322                if (perms != null && perms.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    /**
2331     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2332     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2333     * @param checkShell TODO(yamasani):
2334     * @param message the message to log on security exception
2335     */
2336    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2337            boolean checkShell, String message) {
2338        if (userId < 0) {
2339            throw new IllegalArgumentException("Invalid userId " + userId);
2340        }
2341        if (checkShell) {
2342            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2343        }
2344        if (userId == UserHandle.getUserId(callingUid)) return;
2345        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2346            if (requireFullPermission) {
2347                mContext.enforceCallingOrSelfPermission(
2348                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2349            } else {
2350                try {
2351                    mContext.enforceCallingOrSelfPermission(
2352                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2353                } catch (SecurityException se) {
2354                    mContext.enforceCallingOrSelfPermission(
2355                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2356                }
2357            }
2358        }
2359    }
2360
2361    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2362        if (callingUid == Process.SHELL_UID) {
2363            if (userHandle >= 0
2364                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2365                throw new SecurityException("Shell does not have permission to access user "
2366                        + userHandle);
2367            } else if (userHandle < 0) {
2368                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2369                        + Debug.getCallers(3));
2370            }
2371        }
2372    }
2373
2374    private BasePermission findPermissionTreeLP(String permName) {
2375        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2376            if (permName.startsWith(bp.name) &&
2377                    permName.length() > bp.name.length() &&
2378                    permName.charAt(bp.name.length()) == '.') {
2379                return bp;
2380            }
2381        }
2382        return null;
2383    }
2384
2385    private BasePermission checkPermissionTreeLP(String permName) {
2386        if (permName != null) {
2387            BasePermission bp = findPermissionTreeLP(permName);
2388            if (bp != null) {
2389                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2390                    return bp;
2391                }
2392                throw new SecurityException("Calling uid "
2393                        + Binder.getCallingUid()
2394                        + " is not allowed to add to permission tree "
2395                        + bp.name + " owned by uid " + bp.uid);
2396            }
2397        }
2398        throw new SecurityException("No permission tree found for " + permName);
2399    }
2400
2401    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2402        if (s1 == null) {
2403            return s2 == null;
2404        }
2405        if (s2 == null) {
2406            return false;
2407        }
2408        if (s1.getClass() != s2.getClass()) {
2409            return false;
2410        }
2411        return s1.equals(s2);
2412    }
2413
2414    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2415        if (pi1.icon != pi2.icon) return false;
2416        if (pi1.logo != pi2.logo) return false;
2417        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2418        if (!compareStrings(pi1.name, pi2.name)) return false;
2419        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2420        // We'll take care of setting this one.
2421        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2422        // These are not currently stored in settings.
2423        //if (!compareStrings(pi1.group, pi2.group)) return false;
2424        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2425        //if (pi1.labelRes != pi2.labelRes) return false;
2426        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2427        return true;
2428    }
2429
2430    int permissionInfoFootprint(PermissionInfo info) {
2431        int size = info.name.length();
2432        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2433        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2434        return size;
2435    }
2436
2437    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2438        int size = 0;
2439        for (BasePermission perm : mSettings.mPermissions.values()) {
2440            if (perm.uid == tree.uid) {
2441                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2442            }
2443        }
2444        return size;
2445    }
2446
2447    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2448        // We calculate the max size of permissions defined by this uid and throw
2449        // if that plus the size of 'info' would exceed our stated maximum.
2450        if (tree.uid != Process.SYSTEM_UID) {
2451            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2452            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2453                throw new SecurityException("Permission tree size cap exceeded");
2454            }
2455        }
2456    }
2457
2458    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2459        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2460            throw new SecurityException("Label must be specified in permission");
2461        }
2462        BasePermission tree = checkPermissionTreeLP(info.name);
2463        BasePermission bp = mSettings.mPermissions.get(info.name);
2464        boolean added = bp == null;
2465        boolean changed = true;
2466        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2467        if (added) {
2468            enforcePermissionCapLocked(info, tree);
2469            bp = new BasePermission(info.name, tree.sourcePackage,
2470                    BasePermission.TYPE_DYNAMIC);
2471        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2472            throw new SecurityException(
2473                    "Not allowed to modify non-dynamic permission "
2474                    + info.name);
2475        } else {
2476            if (bp.protectionLevel == fixedLevel
2477                    && bp.perm.owner.equals(tree.perm.owner)
2478                    && bp.uid == tree.uid
2479                    && comparePermissionInfos(bp.perm.info, info)) {
2480                changed = false;
2481            }
2482        }
2483        bp.protectionLevel = fixedLevel;
2484        info = new PermissionInfo(info);
2485        info.protectionLevel = fixedLevel;
2486        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2487        bp.perm.info.packageName = tree.perm.info.packageName;
2488        bp.uid = tree.uid;
2489        if (added) {
2490            mSettings.mPermissions.put(info.name, bp);
2491        }
2492        if (changed) {
2493            if (!async) {
2494                mSettings.writeLPr();
2495            } else {
2496                scheduleWriteSettingsLocked();
2497            }
2498        }
2499        return added;
2500    }
2501
2502    @Override
2503    public boolean addPermission(PermissionInfo info) {
2504        synchronized (mPackages) {
2505            return addPermissionLocked(info, false);
2506        }
2507    }
2508
2509    @Override
2510    public boolean addPermissionAsync(PermissionInfo info) {
2511        synchronized (mPackages) {
2512            return addPermissionLocked(info, true);
2513        }
2514    }
2515
2516    @Override
2517    public void removePermission(String name) {
2518        synchronized (mPackages) {
2519            checkPermissionTreeLP(name);
2520            BasePermission bp = mSettings.mPermissions.get(name);
2521            if (bp != null) {
2522                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2523                    throw new SecurityException(
2524                            "Not allowed to modify non-dynamic permission "
2525                            + name);
2526                }
2527                mSettings.mPermissions.remove(name);
2528                mSettings.writeLPr();
2529            }
2530        }
2531    }
2532
2533    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2534        int index = pkg.requestedPermissions.indexOf(bp.name);
2535        if (index == -1) {
2536            throw new SecurityException("Package " + pkg.packageName
2537                    + " has not requested permission " + bp.name);
2538        }
2539        boolean isNormal =
2540                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2541                        == PermissionInfo.PROTECTION_NORMAL);
2542        boolean isDangerous =
2543                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2544                        == PermissionInfo.PROTECTION_DANGEROUS);
2545        boolean isDevelopment =
2546                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2547
2548        if (!isNormal && !isDangerous && !isDevelopment) {
2549            throw new SecurityException("Permission " + bp.name
2550                    + " is not a changeable permission type");
2551        }
2552
2553        if (isNormal || isDangerous) {
2554            if (pkg.requestedPermissionsRequired.get(index)) {
2555                throw new SecurityException("Can't change " + bp.name
2556                        + ". It is required by the application");
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public void grantPermission(String packageName, String permissionName) {
2563        mContext.enforceCallingOrSelfPermission(
2564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2565        synchronized (mPackages) {
2566            final PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg == null) {
2568                throw new IllegalArgumentException("Unknown package: " + packageName);
2569            }
2570            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2571            if (bp == null) {
2572                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2573            }
2574
2575            checkGrantRevokePermissions(pkg, bp);
2576
2577            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2578            if (ps == null) {
2579                return;
2580            }
2581            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2582            if (gp.grantedPermissions.add(permissionName)) {
2583                if (ps.haveGids) {
2584                    gp.gids = appendInts(gp.gids, bp.gids);
2585                }
2586                mSettings.writeLPr();
2587            }
2588        }
2589    }
2590
2591    @Override
2592    public void revokePermission(String packageName, String permissionName) {
2593        int changedAppId = -1;
2594
2595        synchronized (mPackages) {
2596            final PackageParser.Package pkg = mPackages.get(packageName);
2597            if (pkg == null) {
2598                throw new IllegalArgumentException("Unknown package: " + packageName);
2599            }
2600            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2601                mContext.enforceCallingOrSelfPermission(
2602                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2603            }
2604            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2605            if (bp == null) {
2606                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2607            }
2608
2609            checkGrantRevokePermissions(pkg, bp);
2610
2611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2612            if (ps == null) {
2613                return;
2614            }
2615            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2616            if (gp.grantedPermissions.remove(permissionName)) {
2617                gp.grantedPermissions.remove(permissionName);
2618                if (ps.haveGids) {
2619                    gp.gids = removeInts(gp.gids, bp.gids);
2620                }
2621                mSettings.writeLPr();
2622                changedAppId = ps.appId;
2623            }
2624        }
2625
2626        if (changedAppId >= 0) {
2627            // We changed the perm on someone, kill its processes.
2628            IActivityManager am = ActivityManagerNative.getDefault();
2629            if (am != null) {
2630                final int callingUserId = UserHandle.getCallingUserId();
2631                final long ident = Binder.clearCallingIdentity();
2632                try {
2633                    //XXX we should only revoke for the calling user's app permissions,
2634                    // but for now we impact all users.
2635                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2636                    //        "revoke " + permissionName);
2637                    int[] users = sUserManager.getUserIds();
2638                    for (int user : users) {
2639                        am.killUid(UserHandle.getUid(user, changedAppId),
2640                                "revoke " + permissionName);
2641                    }
2642                } catch (RemoteException e) {
2643                } finally {
2644                    Binder.restoreCallingIdentity(ident);
2645                }
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public boolean isProtectedBroadcast(String actionName) {
2652        synchronized (mPackages) {
2653            return mProtectedBroadcasts.contains(actionName);
2654        }
2655    }
2656
2657    @Override
2658    public int checkSignatures(String pkg1, String pkg2) {
2659        synchronized (mPackages) {
2660            final PackageParser.Package p1 = mPackages.get(pkg1);
2661            final PackageParser.Package p2 = mPackages.get(pkg2);
2662            if (p1 == null || p1.mExtras == null
2663                    || p2 == null || p2.mExtras == null) {
2664                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2665            }
2666            return compareSignatures(p1.mSignatures, p2.mSignatures);
2667        }
2668    }
2669
2670    @Override
2671    public int checkUidSignatures(int uid1, int uid2) {
2672        // Map to base uids.
2673        uid1 = UserHandle.getAppId(uid1);
2674        uid2 = UserHandle.getAppId(uid2);
2675        // reader
2676        synchronized (mPackages) {
2677            Signature[] s1;
2678            Signature[] s2;
2679            Object obj = mSettings.getUserIdLPr(uid1);
2680            if (obj != null) {
2681                if (obj instanceof SharedUserSetting) {
2682                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2683                } else if (obj instanceof PackageSetting) {
2684                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2685                } else {
2686                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2687                }
2688            } else {
2689                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2690            }
2691            obj = mSettings.getUserIdLPr(uid2);
2692            if (obj != null) {
2693                if (obj instanceof SharedUserSetting) {
2694                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2695                } else if (obj instanceof PackageSetting) {
2696                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2697                } else {
2698                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2699                }
2700            } else {
2701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2702            }
2703            return compareSignatures(s1, s2);
2704        }
2705    }
2706
2707    /**
2708     * Compares two sets of signatures. Returns:
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2719     */
2720    static int compareSignatures(Signature[] s1, Signature[] s2) {
2721        if (s1 == null) {
2722            return s2 == null
2723                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2724                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2725        }
2726
2727        if (s2 == null) {
2728            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2729        }
2730
2731        if (s1.length != s2.length) {
2732            return PackageManager.SIGNATURE_NO_MATCH;
2733        }
2734
2735        // Since both signature sets are of size 1, we can compare without HashSets.
2736        if (s1.length == 1) {
2737            return s1[0].equals(s2[0]) ?
2738                    PackageManager.SIGNATURE_MATCH :
2739                    PackageManager.SIGNATURE_NO_MATCH;
2740        }
2741
2742        HashSet<Signature> set1 = new HashSet<Signature>();
2743        for (Signature sig : s1) {
2744            set1.add(sig);
2745        }
2746        HashSet<Signature> set2 = new HashSet<Signature>();
2747        for (Signature sig : s2) {
2748            set2.add(sig);
2749        }
2750        // Make sure s2 contains all signatures in s1.
2751        if (set1.equals(set2)) {
2752            return PackageManager.SIGNATURE_MATCH;
2753        }
2754        return PackageManager.SIGNATURE_NO_MATCH;
2755    }
2756
2757    /**
2758     * If the database version for this type of package (internal storage or
2759     * external storage) is less than the version where package signatures
2760     * were updated, return true.
2761     */
2762    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2763        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2764                DatabaseVersion.SIGNATURE_END_ENTITY))
2765                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2766                        DatabaseVersion.SIGNATURE_END_ENTITY));
2767    }
2768
2769    /**
2770     * Used for backward compatibility to make sure any packages with
2771     * certificate chains get upgraded to the new style. {@code existingSigs}
2772     * will be in the old format (since they were stored on disk from before the
2773     * system upgrade) and {@code scannedSigs} will be in the newer format.
2774     */
2775    private int compareSignaturesCompat(PackageSignatures existingSigs,
2776            PackageParser.Package scannedPkg) {
2777        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2778            return PackageManager.SIGNATURE_NO_MATCH;
2779        }
2780
2781        HashSet<Signature> existingSet = new HashSet<Signature>();
2782        for (Signature sig : existingSigs.mSignatures) {
2783            existingSet.add(sig);
2784        }
2785        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2786        for (Signature sig : scannedPkg.mSignatures) {
2787            try {
2788                Signature[] chainSignatures = sig.getChainSignatures();
2789                for (Signature chainSig : chainSignatures) {
2790                    scannedCompatSet.add(chainSig);
2791                }
2792            } catch (CertificateEncodingException e) {
2793                scannedCompatSet.add(sig);
2794            }
2795        }
2796        /*
2797         * Make sure the expanded scanned set contains all signatures in the
2798         * existing one.
2799         */
2800        if (scannedCompatSet.equals(existingSet)) {
2801            // Migrate the old signatures to the new scheme.
2802            existingSigs.assignSignatures(scannedPkg.mSignatures);
2803            // The new KeySets will be re-added later in the scanning process.
2804            synchronized (mPackages) {
2805                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2806            }
2807            return PackageManager.SIGNATURE_MATCH;
2808        }
2809        return PackageManager.SIGNATURE_NO_MATCH;
2810    }
2811
2812    @Override
2813    public String[] getPackagesForUid(int uid) {
2814        uid = UserHandle.getAppId(uid);
2815        // reader
2816        synchronized (mPackages) {
2817            Object obj = mSettings.getUserIdLPr(uid);
2818            if (obj instanceof SharedUserSetting) {
2819                final SharedUserSetting sus = (SharedUserSetting) obj;
2820                final int N = sus.packages.size();
2821                final String[] res = new String[N];
2822                final Iterator<PackageSetting> it = sus.packages.iterator();
2823                int i = 0;
2824                while (it.hasNext()) {
2825                    res[i++] = it.next().name;
2826                }
2827                return res;
2828            } else if (obj instanceof PackageSetting) {
2829                final PackageSetting ps = (PackageSetting) obj;
2830                return new String[] { ps.name };
2831            }
2832        }
2833        return null;
2834    }
2835
2836    @Override
2837    public String getNameForUid(int uid) {
2838        // reader
2839        synchronized (mPackages) {
2840            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2841            if (obj instanceof SharedUserSetting) {
2842                final SharedUserSetting sus = (SharedUserSetting) obj;
2843                return sus.name + ":" + sus.userId;
2844            } else if (obj instanceof PackageSetting) {
2845                final PackageSetting ps = (PackageSetting) obj;
2846                return ps.name;
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public int getUidForSharedUser(String sharedUserName) {
2854        if(sharedUserName == null) {
2855            return -1;
2856        }
2857        // reader
2858        synchronized (mPackages) {
2859            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2860            if (suid == null) {
2861                return -1;
2862            }
2863            return suid.userId;
2864        }
2865    }
2866
2867    @Override
2868    public int getFlagsForUid(int uid) {
2869        synchronized (mPackages) {
2870            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2871            if (obj instanceof SharedUserSetting) {
2872                final SharedUserSetting sus = (SharedUserSetting) obj;
2873                return sus.pkgFlags;
2874            } else if (obj instanceof PackageSetting) {
2875                final PackageSetting ps = (PackageSetting) obj;
2876                return ps.pkgFlags;
2877            }
2878        }
2879        return 0;
2880    }
2881
2882    @Override
2883    public String[] getAppOpPermissionPackages(String permissionName) {
2884        synchronized (mPackages) {
2885            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2886            if (pkgs == null) {
2887                return null;
2888            }
2889            return pkgs.toArray(new String[pkgs.size()]);
2890        }
2891    }
2892
2893    @Override
2894    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2895            int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2900    }
2901
2902    @Override
2903    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2904            IntentFilter filter, int match, ComponentName activity) {
2905        final int userId = UserHandle.getCallingUserId();
2906        if (DEBUG_PREFERRED) {
2907            Log.v(TAG, "setLastChosenActivity intent=" + intent
2908                + " resolvedType=" + resolvedType
2909                + " flags=" + flags
2910                + " filter=" + filter
2911                + " match=" + match
2912                + " activity=" + activity);
2913            filter.dump(new PrintStreamPrinter(System.out), "    ");
2914        }
2915        intent.setComponent(null);
2916        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2917        // Find any earlier preferred or last chosen entries and nuke them
2918        findPreferredActivity(intent, resolvedType,
2919                flags, query, 0, false, true, false, userId);
2920        // Add the new activity as the last chosen for this filter
2921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2922                "Setting last chosen");
2923    }
2924
2925    @Override
2926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2927        final int userId = UserHandle.getCallingUserId();
2928        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2929        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2931                false, false, false, userId);
2932    }
2933
2934    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2935            int flags, List<ResolveInfo> query, int userId) {
2936        if (query != null) {
2937            final int N = query.size();
2938            if (N == 1) {
2939                return query.get(0);
2940            } else if (N > 1) {
2941                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2942                // If there is more than one activity with the same priority,
2943                // then let the user decide between them.
2944                ResolveInfo r0 = query.get(0);
2945                ResolveInfo r1 = query.get(1);
2946                if (DEBUG_INTENT_MATCHING || debug) {
2947                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2948                            + r1.activityInfo.name + "=" + r1.priority);
2949                }
2950                // If the first activity has a higher priority, or a different
2951                // default, then it is always desireable to pick it.
2952                if (r0.priority != r1.priority
2953                        || r0.preferredOrder != r1.preferredOrder
2954                        || r0.isDefault != r1.isDefault) {
2955                    return query.get(0);
2956                }
2957                // If we have saved a preference for a preferred activity for
2958                // this Intent, use that.
2959                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2960                        flags, query, r0.priority, true, false, debug, userId);
2961                if (ri != null) {
2962                    return ri;
2963                }
2964                if (userId != 0) {
2965                    ri = new ResolveInfo(mResolveInfo);
2966                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2967                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2968                            ri.activityInfo.applicationInfo);
2969                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2970                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2971                    return ri;
2972                }
2973                return mResolveInfo;
2974            }
2975        }
2976        return null;
2977    }
2978
2979    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2980            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2981        final int N = query.size();
2982        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2983                .get(userId);
2984        // Get the list of persistent preferred activities that handle the intent
2985        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2986        List<PersistentPreferredActivity> pprefs = ppir != null
2987                ? ppir.queryIntent(intent, resolvedType,
2988                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2989                : null;
2990        if (pprefs != null && pprefs.size() > 0) {
2991            final int M = pprefs.size();
2992            for (int i=0; i<M; i++) {
2993                final PersistentPreferredActivity ppa = pprefs.get(i);
2994                if (DEBUG_PREFERRED || debug) {
2995                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2996                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2997                            + "\n  component=" + ppa.mComponent);
2998                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2999                }
3000                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3001                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3002                if (DEBUG_PREFERRED || debug) {
3003                    Slog.v(TAG, "Found persistent preferred activity:");
3004                    if (ai != null) {
3005                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3006                    } else {
3007                        Slog.v(TAG, "  null");
3008                    }
3009                }
3010                if (ai == null) {
3011                    // This previously registered persistent preferred activity
3012                    // component is no longer known. Ignore it and do NOT remove it.
3013                    continue;
3014                }
3015                for (int j=0; j<N; j++) {
3016                    final ResolveInfo ri = query.get(j);
3017                    if (!ri.activityInfo.applicationInfo.packageName
3018                            .equals(ai.applicationInfo.packageName)) {
3019                        continue;
3020                    }
3021                    if (!ri.activityInfo.name.equals(ai.name)) {
3022                        continue;
3023                    }
3024                    //  Found a persistent preference that can handle the intent.
3025                    if (DEBUG_PREFERRED || debug) {
3026                        Slog.v(TAG, "Returning persistent preferred activity: " +
3027                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3028                    }
3029                    return ri;
3030                }
3031            }
3032        }
3033        return null;
3034    }
3035
3036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3037            List<ResolveInfo> query, int priority, boolean always,
3038            boolean removeMatches, boolean debug, int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        // writer
3041        synchronized (mPackages) {
3042            if (intent.getSelector() != null) {
3043                intent = intent.getSelector();
3044            }
3045            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3046
3047            // Try to find a matching persistent preferred activity.
3048            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3049                    debug, userId);
3050
3051            // If a persistent preferred activity matched, use it.
3052            if (pri != null) {
3053                return pri;
3054            }
3055
3056            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3057            // Get the list of preferred activities that handle the intent
3058            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3059            List<PreferredActivity> prefs = pir != null
3060                    ? pir.queryIntent(intent, resolvedType,
3061                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3062                    : null;
3063            if (prefs != null && prefs.size() > 0) {
3064                boolean changed = false;
3065                try {
3066                    // First figure out how good the original match set is.
3067                    // We will only allow preferred activities that came
3068                    // from the same match quality.
3069                    int match = 0;
3070
3071                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3072
3073                    final int N = query.size();
3074                    for (int j=0; j<N; j++) {
3075                        final ResolveInfo ri = query.get(j);
3076                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3077                                + ": 0x" + Integer.toHexString(match));
3078                        if (ri.match > match) {
3079                            match = ri.match;
3080                        }
3081                    }
3082
3083                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3084                            + Integer.toHexString(match));
3085
3086                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3087                    final int M = prefs.size();
3088                    for (int i=0; i<M; i++) {
3089                        final PreferredActivity pa = prefs.get(i);
3090                        if (DEBUG_PREFERRED || debug) {
3091                            Slog.v(TAG, "Checking PreferredActivity ds="
3092                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3093                                    + "\n  component=" + pa.mPref.mComponent);
3094                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                        }
3096                        if (pa.mPref.mMatch != match) {
3097                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3098                                    + Integer.toHexString(pa.mPref.mMatch));
3099                            continue;
3100                        }
3101                        // If it's not an "always" type preferred activity and that's what we're
3102                        // looking for, skip it.
3103                        if (always && !pa.mPref.mAlways) {
3104                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3105                            continue;
3106                        }
3107                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3108                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3109                        if (DEBUG_PREFERRED || debug) {
3110                            Slog.v(TAG, "Found preferred activity:");
3111                            if (ai != null) {
3112                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3113                            } else {
3114                                Slog.v(TAG, "  null");
3115                            }
3116                        }
3117                        if (ai == null) {
3118                            // This previously registered preferred activity
3119                            // component is no longer known.  Most likely an update
3120                            // to the app was installed and in the new version this
3121                            // component no longer exists.  Clean it up by removing
3122                            // it from the preferred activities list, and skip it.
3123                            Slog.w(TAG, "Removing dangling preferred activity: "
3124                                    + pa.mPref.mComponent);
3125                            pir.removeFilter(pa);
3126                            changed = true;
3127                            continue;
3128                        }
3129                        for (int j=0; j<N; j++) {
3130                            final ResolveInfo ri = query.get(j);
3131                            if (!ri.activityInfo.applicationInfo.packageName
3132                                    .equals(ai.applicationInfo.packageName)) {
3133                                continue;
3134                            }
3135                            if (!ri.activityInfo.name.equals(ai.name)) {
3136                                continue;
3137                            }
3138
3139                            if (removeMatches) {
3140                                pir.removeFilter(pa);
3141                                changed = true;
3142                                if (DEBUG_PREFERRED) {
3143                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3144                                }
3145                                break;
3146                            }
3147
3148                            // Okay we found a previously set preferred or last chosen app.
3149                            // If the result set is different from when this
3150                            // was created, we need to clear it and re-ask the
3151                            // user their preference, if we're looking for an "always" type entry.
3152                            if (always && !pa.mPref.sameSet(query, priority)) {
3153                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3154                                        + intent + " type " + resolvedType);
3155                                if (DEBUG_PREFERRED) {
3156                                    Slog.v(TAG, "Removing preferred activity since set changed "
3157                                            + pa.mPref.mComponent);
3158                                }
3159                                pir.removeFilter(pa);
3160                                // Re-add the filter as a "last chosen" entry (!always)
3161                                PreferredActivity lastChosen = new PreferredActivity(
3162                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3163                                pir.addFilter(lastChosen);
3164                                changed = true;
3165                                return null;
3166                            }
3167
3168                            // Yay! Either the set matched or we're looking for the last chosen
3169                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3170                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3171                            return ri;
3172                        }
3173                    }
3174                } finally {
3175                    if (changed) {
3176                        if (DEBUG_PREFERRED) {
3177                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3178                        }
3179                        mSettings.writePackageRestrictionsLPr(userId);
3180                    }
3181                }
3182            }
3183        }
3184        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3185        return null;
3186    }
3187
3188    /*
3189     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3190     */
3191    @Override
3192    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3193            int targetUserId) {
3194        mContext.enforceCallingOrSelfPermission(
3195                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3196        List<CrossProfileIntentFilter> matches =
3197                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3198        if (matches != null) {
3199            int size = matches.size();
3200            for (int i = 0; i < size; i++) {
3201                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3202            }
3203        }
3204        return false;
3205    }
3206
3207    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3208            String resolvedType, int userId) {
3209        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3210        if (resolver != null) {
3211            return resolver.queryIntent(intent, resolvedType, false, userId);
3212        }
3213        return null;
3214    }
3215
3216    @Override
3217    public List<ResolveInfo> queryIntentActivities(Intent intent,
3218            String resolvedType, int flags, int userId) {
3219        if (!sUserManager.exists(userId)) return Collections.emptyList();
3220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3221        ComponentName comp = intent.getComponent();
3222        if (comp == null) {
3223            if (intent.getSelector() != null) {
3224                intent = intent.getSelector();
3225                comp = intent.getComponent();
3226            }
3227        }
3228
3229        if (comp != null) {
3230            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3231            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3232            if (ai != null) {
3233                final ResolveInfo ri = new ResolveInfo();
3234                ri.activityInfo = ai;
3235                list.add(ri);
3236            }
3237            return list;
3238        }
3239
3240        // reader
3241        synchronized (mPackages) {
3242            final String pkgName = intent.getPackage();
3243            if (pkgName == null) {
3244                List<CrossProfileIntentFilter> matchingFilters =
3245                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3246                // Check for results that need to skip the current profile.
3247                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3248                        resolvedType, flags, userId);
3249                if (resolveInfo != null) {
3250                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3251                    result.add(resolveInfo);
3252                    return result;
3253                }
3254                // Check for cross profile results.
3255                resolveInfo = queryCrossProfileIntents(
3256                        matchingFilters, intent, resolvedType, flags, userId);
3257
3258                // Check for results in the current profile.
3259                List<ResolveInfo> result = mActivities.queryIntent(
3260                        intent, resolvedType, flags, userId);
3261                if (resolveInfo != null) {
3262                    result.add(resolveInfo);
3263                    Collections.sort(result, mResolvePrioritySorter);
3264                }
3265                return result;
3266            }
3267            final PackageParser.Package pkg = mPackages.get(pkgName);
3268            if (pkg != null) {
3269                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3270                        pkg.activities, userId);
3271            }
3272            return new ArrayList<ResolveInfo>();
3273        }
3274    }
3275
3276    private ResolveInfo querySkipCurrentProfileIntents(
3277            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3278            int flags, int sourceUserId) {
3279        if (matchingFilters != null) {
3280            int size = matchingFilters.size();
3281            for (int i = 0; i < size; i ++) {
3282                CrossProfileIntentFilter filter = matchingFilters.get(i);
3283                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3284                    // Checking if there are activities in the target user that can handle the
3285                    // intent.
3286                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3287                            flags, sourceUserId);
3288                    if (resolveInfo != null) {
3289                        return resolveInfo;
3290                    }
3291                }
3292            }
3293        }
3294        return null;
3295    }
3296
3297    // Return matching ResolveInfo if any for skip current profile intent filters.
3298    private ResolveInfo queryCrossProfileIntents(
3299            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3300            int flags, int sourceUserId) {
3301        if (matchingFilters != null) {
3302            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3303            // match the same intent. For performance reasons, it is better not to
3304            // run queryIntent twice for the same userId
3305            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3306            int size = matchingFilters.size();
3307            for (int i = 0; i < size; i++) {
3308                CrossProfileIntentFilter filter = matchingFilters.get(i);
3309                int targetUserId = filter.getTargetUserId();
3310                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3311                        && !alreadyTriedUserIds.get(targetUserId)) {
3312                    // Checking if there are activities in the target user that can handle the
3313                    // intent.
3314                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3315                            flags, sourceUserId);
3316                    if (resolveInfo != null) return resolveInfo;
3317                    alreadyTriedUserIds.put(targetUserId, true);
3318                }
3319            }
3320        }
3321        return null;
3322    }
3323
3324    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3325            String resolvedType, int flags, int sourceUserId) {
3326        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3327                resolvedType, flags, filter.getTargetUserId());
3328        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3329            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3330        }
3331        return null;
3332    }
3333
3334    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3335            int sourceUserId, int targetUserId) {
3336        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3337        String className;
3338        if (targetUserId == UserHandle.USER_OWNER) {
3339            className = FORWARD_INTENT_TO_USER_OWNER;
3340        } else {
3341            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3342        }
3343        ComponentName forwardingActivityComponentName = new ComponentName(
3344                mAndroidApplication.packageName, className);
3345        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3346                sourceUserId);
3347        if (targetUserId == UserHandle.USER_OWNER) {
3348            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3349            forwardingResolveInfo.noResourceId = true;
3350        }
3351        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3352        forwardingResolveInfo.priority = 0;
3353        forwardingResolveInfo.preferredOrder = 0;
3354        forwardingResolveInfo.match = 0;
3355        forwardingResolveInfo.isDefault = true;
3356        forwardingResolveInfo.filter = filter;
3357        forwardingResolveInfo.targetUserId = targetUserId;
3358        return forwardingResolveInfo;
3359    }
3360
3361    @Override
3362    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3363            Intent[] specifics, String[] specificTypes, Intent intent,
3364            String resolvedType, int flags, int userId) {
3365        if (!sUserManager.exists(userId)) return Collections.emptyList();
3366        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3367                false, "query intent activity options");
3368        final String resultsAction = intent.getAction();
3369
3370        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3371                | PackageManager.GET_RESOLVED_FILTER, userId);
3372
3373        if (DEBUG_INTENT_MATCHING) {
3374            Log.v(TAG, "Query " + intent + ": " + results);
3375        }
3376
3377        int specificsPos = 0;
3378        int N;
3379
3380        // todo: note that the algorithm used here is O(N^2).  This
3381        // isn't a problem in our current environment, but if we start running
3382        // into situations where we have more than 5 or 10 matches then this
3383        // should probably be changed to something smarter...
3384
3385        // First we go through and resolve each of the specific items
3386        // that were supplied, taking care of removing any corresponding
3387        // duplicate items in the generic resolve list.
3388        if (specifics != null) {
3389            for (int i=0; i<specifics.length; i++) {
3390                final Intent sintent = specifics[i];
3391                if (sintent == null) {
3392                    continue;
3393                }
3394
3395                if (DEBUG_INTENT_MATCHING) {
3396                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3397                }
3398
3399                String action = sintent.getAction();
3400                if (resultsAction != null && resultsAction.equals(action)) {
3401                    // If this action was explicitly requested, then don't
3402                    // remove things that have it.
3403                    action = null;
3404                }
3405
3406                ResolveInfo ri = null;
3407                ActivityInfo ai = null;
3408
3409                ComponentName comp = sintent.getComponent();
3410                if (comp == null) {
3411                    ri = resolveIntent(
3412                        sintent,
3413                        specificTypes != null ? specificTypes[i] : null,
3414                            flags, userId);
3415                    if (ri == null) {
3416                        continue;
3417                    }
3418                    if (ri == mResolveInfo) {
3419                        // ACK!  Must do something better with this.
3420                    }
3421                    ai = ri.activityInfo;
3422                    comp = new ComponentName(ai.applicationInfo.packageName,
3423                            ai.name);
3424                } else {
3425                    ai = getActivityInfo(comp, flags, userId);
3426                    if (ai == null) {
3427                        continue;
3428                    }
3429                }
3430
3431                // Look for any generic query activities that are duplicates
3432                // of this specific one, and remove them from the results.
3433                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3434                N = results.size();
3435                int j;
3436                for (j=specificsPos; j<N; j++) {
3437                    ResolveInfo sri = results.get(j);
3438                    if ((sri.activityInfo.name.equals(comp.getClassName())
3439                            && sri.activityInfo.applicationInfo.packageName.equals(
3440                                    comp.getPackageName()))
3441                        || (action != null && sri.filter.matchAction(action))) {
3442                        results.remove(j);
3443                        if (DEBUG_INTENT_MATCHING) Log.v(
3444                            TAG, "Removing duplicate item from " + j
3445                            + " due to specific " + specificsPos);
3446                        if (ri == null) {
3447                            ri = sri;
3448                        }
3449                        j--;
3450                        N--;
3451                    }
3452                }
3453
3454                // Add this specific item to its proper place.
3455                if (ri == null) {
3456                    ri = new ResolveInfo();
3457                    ri.activityInfo = ai;
3458                }
3459                results.add(specificsPos, ri);
3460                ri.specificIndex = i;
3461                specificsPos++;
3462            }
3463        }
3464
3465        // Now we go through the remaining generic results and remove any
3466        // duplicate actions that are found here.
3467        N = results.size();
3468        for (int i=specificsPos; i<N-1; i++) {
3469            final ResolveInfo rii = results.get(i);
3470            if (rii.filter == null) {
3471                continue;
3472            }
3473
3474            // Iterate over all of the actions of this result's intent
3475            // filter...  typically this should be just one.
3476            final Iterator<String> it = rii.filter.actionsIterator();
3477            if (it == null) {
3478                continue;
3479            }
3480            while (it.hasNext()) {
3481                final String action = it.next();
3482                if (resultsAction != null && resultsAction.equals(action)) {
3483                    // If this action was explicitly requested, then don't
3484                    // remove things that have it.
3485                    continue;
3486                }
3487                for (int j=i+1; j<N; j++) {
3488                    final ResolveInfo rij = results.get(j);
3489                    if (rij.filter != null && rij.filter.hasAction(action)) {
3490                        results.remove(j);
3491                        if (DEBUG_INTENT_MATCHING) Log.v(
3492                            TAG, "Removing duplicate item from " + j
3493                            + " due to action " + action + " at " + i);
3494                        j--;
3495                        N--;
3496                    }
3497                }
3498            }
3499
3500            // If the caller didn't request filter information, drop it now
3501            // so we don't have to marshall/unmarshall it.
3502            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3503                rii.filter = null;
3504            }
3505        }
3506
3507        // Filter out the caller activity if so requested.
3508        if (caller != null) {
3509            N = results.size();
3510            for (int i=0; i<N; i++) {
3511                ActivityInfo ainfo = results.get(i).activityInfo;
3512                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3513                        && caller.getClassName().equals(ainfo.name)) {
3514                    results.remove(i);
3515                    break;
3516                }
3517            }
3518        }
3519
3520        // If the caller didn't request filter information,
3521        // drop them now so we don't have to
3522        // marshall/unmarshall it.
3523        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3524            N = results.size();
3525            for (int i=0; i<N; i++) {
3526                results.get(i).filter = null;
3527            }
3528        }
3529
3530        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3531        return results;
3532    }
3533
3534    @Override
3535    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3536            int userId) {
3537        if (!sUserManager.exists(userId)) return Collections.emptyList();
3538        ComponentName comp = intent.getComponent();
3539        if (comp == null) {
3540            if (intent.getSelector() != null) {
3541                intent = intent.getSelector();
3542                comp = intent.getComponent();
3543            }
3544        }
3545        if (comp != null) {
3546            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3547            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3548            if (ai != null) {
3549                ResolveInfo ri = new ResolveInfo();
3550                ri.activityInfo = ai;
3551                list.add(ri);
3552            }
3553            return list;
3554        }
3555
3556        // reader
3557        synchronized (mPackages) {
3558            String pkgName = intent.getPackage();
3559            if (pkgName == null) {
3560                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3561            }
3562            final PackageParser.Package pkg = mPackages.get(pkgName);
3563            if (pkg != null) {
3564                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3565                        userId);
3566            }
3567            return null;
3568        }
3569    }
3570
3571    @Override
3572    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3573        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3574        if (!sUserManager.exists(userId)) return null;
3575        if (query != null) {
3576            if (query.size() >= 1) {
3577                // If there is more than one service with the same priority,
3578                // just arbitrarily pick the first one.
3579                return query.get(0);
3580            }
3581        }
3582        return null;
3583    }
3584
3585    @Override
3586    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3587            int userId) {
3588        if (!sUserManager.exists(userId)) return Collections.emptyList();
3589        ComponentName comp = intent.getComponent();
3590        if (comp == null) {
3591            if (intent.getSelector() != null) {
3592                intent = intent.getSelector();
3593                comp = intent.getComponent();
3594            }
3595        }
3596        if (comp != null) {
3597            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3598            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3599            if (si != null) {
3600                final ResolveInfo ri = new ResolveInfo();
3601                ri.serviceInfo = si;
3602                list.add(ri);
3603            }
3604            return list;
3605        }
3606
3607        // reader
3608        synchronized (mPackages) {
3609            String pkgName = intent.getPackage();
3610            if (pkgName == null) {
3611                return mServices.queryIntent(intent, resolvedType, flags, userId);
3612            }
3613            final PackageParser.Package pkg = mPackages.get(pkgName);
3614            if (pkg != null) {
3615                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3616                        userId);
3617            }
3618            return null;
3619        }
3620    }
3621
3622    @Override
3623    public List<ResolveInfo> queryIntentContentProviders(
3624            Intent intent, String resolvedType, int flags, int userId) {
3625        if (!sUserManager.exists(userId)) return Collections.emptyList();
3626        ComponentName comp = intent.getComponent();
3627        if (comp == null) {
3628            if (intent.getSelector() != null) {
3629                intent = intent.getSelector();
3630                comp = intent.getComponent();
3631            }
3632        }
3633        if (comp != null) {
3634            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3635            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3636            if (pi != null) {
3637                final ResolveInfo ri = new ResolveInfo();
3638                ri.providerInfo = pi;
3639                list.add(ri);
3640            }
3641            return list;
3642        }
3643
3644        // reader
3645        synchronized (mPackages) {
3646            String pkgName = intent.getPackage();
3647            if (pkgName == null) {
3648                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3649            }
3650            final PackageParser.Package pkg = mPackages.get(pkgName);
3651            if (pkg != null) {
3652                return mProviders.queryIntentForPackage(
3653                        intent, resolvedType, flags, pkg.providers, userId);
3654            }
3655            return null;
3656        }
3657    }
3658
3659    @Override
3660    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3661        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3662
3663        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3664
3665        // writer
3666        synchronized (mPackages) {
3667            ArrayList<PackageInfo> list;
3668            if (listUninstalled) {
3669                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3670                for (PackageSetting ps : mSettings.mPackages.values()) {
3671                    PackageInfo pi;
3672                    if (ps.pkg != null) {
3673                        pi = generatePackageInfo(ps.pkg, flags, userId);
3674                    } else {
3675                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3676                    }
3677                    if (pi != null) {
3678                        list.add(pi);
3679                    }
3680                }
3681            } else {
3682                list = new ArrayList<PackageInfo>(mPackages.size());
3683                for (PackageParser.Package p : mPackages.values()) {
3684                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3685                    if (pi != null) {
3686                        list.add(pi);
3687                    }
3688                }
3689            }
3690
3691            return new ParceledListSlice<PackageInfo>(list);
3692        }
3693    }
3694
3695    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3696            String[] permissions, boolean[] tmp, int flags, int userId) {
3697        int numMatch = 0;
3698        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3699        for (int i=0; i<permissions.length; i++) {
3700            if (gp.grantedPermissions.contains(permissions[i])) {
3701                tmp[i] = true;
3702                numMatch++;
3703            } else {
3704                tmp[i] = false;
3705            }
3706        }
3707        if (numMatch == 0) {
3708            return;
3709        }
3710        PackageInfo pi;
3711        if (ps.pkg != null) {
3712            pi = generatePackageInfo(ps.pkg, flags, userId);
3713        } else {
3714            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3715        }
3716        // The above might return null in cases of uninstalled apps or install-state
3717        // skew across users/profiles.
3718        if (pi != null) {
3719            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3720                if (numMatch == permissions.length) {
3721                    pi.requestedPermissions = permissions;
3722                } else {
3723                    pi.requestedPermissions = new String[numMatch];
3724                    numMatch = 0;
3725                    for (int i=0; i<permissions.length; i++) {
3726                        if (tmp[i]) {
3727                            pi.requestedPermissions[numMatch] = permissions[i];
3728                            numMatch++;
3729                        }
3730                    }
3731                }
3732            }
3733            list.add(pi);
3734        }
3735    }
3736
3737    @Override
3738    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3739            String[] permissions, int flags, int userId) {
3740        if (!sUserManager.exists(userId)) return null;
3741        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3742
3743        // writer
3744        synchronized (mPackages) {
3745            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3746            boolean[] tmpBools = new boolean[permissions.length];
3747            if (listUninstalled) {
3748                for (PackageSetting ps : mSettings.mPackages.values()) {
3749                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3750                }
3751            } else {
3752                for (PackageParser.Package pkg : mPackages.values()) {
3753                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3754                    if (ps != null) {
3755                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3756                                userId);
3757                    }
3758                }
3759            }
3760
3761            return new ParceledListSlice<PackageInfo>(list);
3762        }
3763    }
3764
3765    @Override
3766    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3767        if (!sUserManager.exists(userId)) return null;
3768        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3769
3770        // writer
3771        synchronized (mPackages) {
3772            ArrayList<ApplicationInfo> list;
3773            if (listUninstalled) {
3774                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3775                for (PackageSetting ps : mSettings.mPackages.values()) {
3776                    ApplicationInfo ai;
3777                    if (ps.pkg != null) {
3778                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3779                                ps.readUserState(userId), userId);
3780                    } else {
3781                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3782                    }
3783                    if (ai != null) {
3784                        list.add(ai);
3785                    }
3786                }
3787            } else {
3788                list = new ArrayList<ApplicationInfo>(mPackages.size());
3789                for (PackageParser.Package p : mPackages.values()) {
3790                    if (p.mExtras != null) {
3791                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3792                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3793                        if (ai != null) {
3794                            list.add(ai);
3795                        }
3796                    }
3797                }
3798            }
3799
3800            return new ParceledListSlice<ApplicationInfo>(list);
3801        }
3802    }
3803
3804    public List<ApplicationInfo> getPersistentApplications(int flags) {
3805        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3806
3807        // reader
3808        synchronized (mPackages) {
3809            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3810            final int userId = UserHandle.getCallingUserId();
3811            while (i.hasNext()) {
3812                final PackageParser.Package p = i.next();
3813                if (p.applicationInfo != null
3814                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3815                        && (!mSafeMode || isSystemApp(p))) {
3816                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3817                    if (ps != null) {
3818                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3819                                ps.readUserState(userId), userId);
3820                        if (ai != null) {
3821                            finalList.add(ai);
3822                        }
3823                    }
3824                }
3825            }
3826        }
3827
3828        return finalList;
3829    }
3830
3831    @Override
3832    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3833        if (!sUserManager.exists(userId)) return null;
3834        // reader
3835        synchronized (mPackages) {
3836            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3837            PackageSetting ps = provider != null
3838                    ? mSettings.mPackages.get(provider.owner.packageName)
3839                    : null;
3840            return ps != null
3841                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3842                    && (!mSafeMode || (provider.info.applicationInfo.flags
3843                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3844                    ? PackageParser.generateProviderInfo(provider, flags,
3845                            ps.readUserState(userId), userId)
3846                    : null;
3847        }
3848    }
3849
3850    /**
3851     * @deprecated
3852     */
3853    @Deprecated
3854    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3855        // reader
3856        synchronized (mPackages) {
3857            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3858                    .entrySet().iterator();
3859            final int userId = UserHandle.getCallingUserId();
3860            while (i.hasNext()) {
3861                Map.Entry<String, PackageParser.Provider> entry = i.next();
3862                PackageParser.Provider p = entry.getValue();
3863                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3864
3865                if (ps != null && p.syncable
3866                        && (!mSafeMode || (p.info.applicationInfo.flags
3867                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3868                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3869                            ps.readUserState(userId), userId);
3870                    if (info != null) {
3871                        outNames.add(entry.getKey());
3872                        outInfo.add(info);
3873                    }
3874                }
3875            }
3876        }
3877    }
3878
3879    @Override
3880    public List<ProviderInfo> queryContentProviders(String processName,
3881            int uid, int flags) {
3882        ArrayList<ProviderInfo> finalList = null;
3883        // reader
3884        synchronized (mPackages) {
3885            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3886            final int userId = processName != null ?
3887                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3888            while (i.hasNext()) {
3889                final PackageParser.Provider p = i.next();
3890                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3891                if (ps != null && p.info.authority != null
3892                        && (processName == null
3893                                || (p.info.processName.equals(processName)
3894                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3895                        && mSettings.isEnabledLPr(p.info, flags, userId)
3896                        && (!mSafeMode
3897                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3898                    if (finalList == null) {
3899                        finalList = new ArrayList<ProviderInfo>(3);
3900                    }
3901                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3902                            ps.readUserState(userId), userId);
3903                    if (info != null) {
3904                        finalList.add(info);
3905                    }
3906                }
3907            }
3908        }
3909
3910        if (finalList != null) {
3911            Collections.sort(finalList, mProviderInitOrderSorter);
3912        }
3913
3914        return finalList;
3915    }
3916
3917    @Override
3918    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3919            int flags) {
3920        // reader
3921        synchronized (mPackages) {
3922            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3923            return PackageParser.generateInstrumentationInfo(i, flags);
3924        }
3925    }
3926
3927    @Override
3928    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3929            int flags) {
3930        ArrayList<InstrumentationInfo> finalList =
3931            new ArrayList<InstrumentationInfo>();
3932
3933        // reader
3934        synchronized (mPackages) {
3935            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3936            while (i.hasNext()) {
3937                final PackageParser.Instrumentation p = i.next();
3938                if (targetPackage == null
3939                        || targetPackage.equals(p.info.targetPackage)) {
3940                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3941                            flags);
3942                    if (ii != null) {
3943                        finalList.add(ii);
3944                    }
3945                }
3946            }
3947        }
3948
3949        return finalList;
3950    }
3951
3952    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3953        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3954        if (overlays == null) {
3955            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3956            return;
3957        }
3958        for (PackageParser.Package opkg : overlays.values()) {
3959            // Not much to do if idmap fails: we already logged the error
3960            // and we certainly don't want to abort installation of pkg simply
3961            // because an overlay didn't fit properly. For these reasons,
3962            // ignore the return value of createIdmapForPackagePairLI.
3963            createIdmapForPackagePairLI(pkg, opkg);
3964        }
3965    }
3966
3967    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3968            PackageParser.Package opkg) {
3969        if (!opkg.mTrustedOverlay) {
3970            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3971                    opkg.baseCodePath + ": overlay not trusted");
3972            return false;
3973        }
3974        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3975        if (overlaySet == null) {
3976            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3977                    opkg.baseCodePath + " but target package has no known overlays");
3978            return false;
3979        }
3980        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3981        // TODO: generate idmap for split APKs
3982        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3983            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3984                    + opkg.baseCodePath);
3985            return false;
3986        }
3987        PackageParser.Package[] overlayArray =
3988            overlaySet.values().toArray(new PackageParser.Package[0]);
3989        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3990            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3991                return p1.mOverlayPriority - p2.mOverlayPriority;
3992            }
3993        };
3994        Arrays.sort(overlayArray, cmp);
3995
3996        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3997        int i = 0;
3998        for (PackageParser.Package p : overlayArray) {
3999            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4000        }
4001        return true;
4002    }
4003
4004    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4005        final File[] files = dir.listFiles();
4006        if (ArrayUtils.isEmpty(files)) {
4007            Log.d(TAG, "No files in app dir " + dir);
4008            return;
4009        }
4010
4011        if (DEBUG_PACKAGE_SCANNING) {
4012            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4013                    + " flags=0x" + Integer.toHexString(parseFlags));
4014        }
4015
4016        for (File file : files) {
4017            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4018                    && !PackageInstallerService.isStageName(file.getName());
4019            if (!isPackage) {
4020                // Ignore entries which are not packages
4021                continue;
4022            }
4023            try {
4024                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4025                        scanFlags, currentTime, null);
4026            } catch (PackageManagerException e) {
4027                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4028
4029                // Delete invalid userdata apps
4030                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4031                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4032                    Slog.w(TAG, "Deleting invalid package at " + file);
4033                    if (file.isDirectory()) {
4034                        FileUtils.deleteContents(file);
4035                    }
4036                    file.delete();
4037                }
4038            }
4039        }
4040    }
4041
4042    private static File getSettingsProblemFile() {
4043        File dataDir = Environment.getDataDirectory();
4044        File systemDir = new File(dataDir, "system");
4045        File fname = new File(systemDir, "uiderrors.txt");
4046        return fname;
4047    }
4048
4049    static void reportSettingsProblem(int priority, String msg) {
4050        try {
4051            File fname = getSettingsProblemFile();
4052            FileOutputStream out = new FileOutputStream(fname, true);
4053            PrintWriter pw = new FastPrintWriter(out);
4054            SimpleDateFormat formatter = new SimpleDateFormat();
4055            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4056            pw.println(dateString + ": " + msg);
4057            pw.close();
4058            FileUtils.setPermissions(
4059                    fname.toString(),
4060                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4061                    -1, -1);
4062        } catch (java.io.IOException e) {
4063        }
4064        Slog.println(priority, TAG, msg);
4065    }
4066
4067    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4068            PackageParser.Package pkg, File srcFile, int parseFlags)
4069            throws PackageManagerException {
4070        if (ps != null
4071                && ps.codePath.equals(srcFile)
4072                && ps.timeStamp == srcFile.lastModified()
4073                && !isCompatSignatureUpdateNeeded(pkg)) {
4074            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4075            if (ps.signatures.mSignatures != null
4076                    && ps.signatures.mSignatures.length != 0
4077                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4078                // Optimization: reuse the existing cached certificates
4079                // if the package appears to be unchanged.
4080                pkg.mSignatures = ps.signatures.mSignatures;
4081                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4082                synchronized (mPackages) {
4083                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4084                }
4085                return;
4086            }
4087
4088            Slog.w(TAG, "PackageSetting for " + ps.name
4089                    + " is missing signatures.  Collecting certs again to recover them.");
4090        } else {
4091            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4092        }
4093
4094        try {
4095            pp.collectCertificates(pkg, parseFlags);
4096            pp.collectManifestDigest(pkg);
4097        } catch (PackageParserException e) {
4098            throw PackageManagerException.from(e);
4099        }
4100    }
4101
4102    /*
4103     *  Scan a package and return the newly parsed package.
4104     *  Returns null in case of errors and the error code is stored in mLastScanError
4105     */
4106    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4107            long currentTime, UserHandle user) throws PackageManagerException {
4108        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4109        parseFlags |= mDefParseFlags;
4110        PackageParser pp = new PackageParser();
4111        pp.setSeparateProcesses(mSeparateProcesses);
4112        pp.setOnlyCoreApps(mOnlyCore);
4113        pp.setDisplayMetrics(mMetrics);
4114
4115        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4116            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4117        }
4118
4119        final PackageParser.Package pkg;
4120        try {
4121            pkg = pp.parsePackage(scanFile, parseFlags);
4122        } catch (PackageParserException e) {
4123            throw PackageManagerException.from(e);
4124        }
4125
4126        PackageSetting ps = null;
4127        PackageSetting updatedPkg;
4128        // reader
4129        synchronized (mPackages) {
4130            // Look to see if we already know about this package.
4131            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4132            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4133                // This package has been renamed to its original name.  Let's
4134                // use that.
4135                ps = mSettings.peekPackageLPr(oldName);
4136            }
4137            // If there was no original package, see one for the real package name.
4138            if (ps == null) {
4139                ps = mSettings.peekPackageLPr(pkg.packageName);
4140            }
4141            // Check to see if this package could be hiding/updating a system
4142            // package.  Must look for it either under the original or real
4143            // package name depending on our state.
4144            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4145            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4146        }
4147        boolean updatedPkgBetter = false;
4148        // First check if this is a system package that may involve an update
4149        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4150            if (ps != null && !ps.codePath.equals(scanFile)) {
4151                // The path has changed from what was last scanned...  check the
4152                // version of the new path against what we have stored to determine
4153                // what to do.
4154                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4155                if (pkg.mVersionCode < ps.versionCode) {
4156                    // The system package has been updated and the code path does not match
4157                    // Ignore entry. Skip it.
4158                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4159                            + " ignored: updated version " + ps.versionCode
4160                            + " better than this " + pkg.mVersionCode);
4161                    if (!updatedPkg.codePath.equals(scanFile)) {
4162                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4163                                + ps.name + " changing from " + updatedPkg.codePathString
4164                                + " to " + scanFile);
4165                        updatedPkg.codePath = scanFile;
4166                        updatedPkg.codePathString = scanFile.toString();
4167                        // This is the point at which we know that the system-disk APK
4168                        // for this package has moved during a reboot (e.g. due to an OTA),
4169                        // so we need to reevaluate it for privilege policy.
4170                        if (locationIsPrivileged(scanFile)) {
4171                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4172                        }
4173                    }
4174                    updatedPkg.pkg = pkg;
4175                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4176                } else {
4177                    // The current app on the system partition is better than
4178                    // what we have updated to on the data partition; switch
4179                    // back to the system partition version.
4180                    // At this point, its safely assumed that package installation for
4181                    // apps in system partition will go through. If not there won't be a working
4182                    // version of the app
4183                    // writer
4184                    synchronized (mPackages) {
4185                        // Just remove the loaded entries from package lists.
4186                        mPackages.remove(ps.name);
4187                    }
4188                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4189                            + "reverting from " + ps.codePathString
4190                            + ": new version " + pkg.mVersionCode
4191                            + " better than installed " + ps.versionCode);
4192
4193                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4194                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4195                            getAppDexInstructionSets(ps));
4196                    synchronized (mInstallLock) {
4197                        args.cleanUpResourcesLI();
4198                    }
4199                    synchronized (mPackages) {
4200                        mSettings.enableSystemPackageLPw(ps.name);
4201                    }
4202                    updatedPkgBetter = true;
4203                }
4204            }
4205        }
4206
4207        if (updatedPkg != null) {
4208            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4209            // initially
4210            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4211
4212            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4213            // flag set initially
4214            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4215                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4216            }
4217        }
4218
4219        // Verify certificates against what was last scanned
4220        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4221
4222        /*
4223         * A new system app appeared, but we already had a non-system one of the
4224         * same name installed earlier.
4225         */
4226        boolean shouldHideSystemApp = false;
4227        if (updatedPkg == null && ps != null
4228                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4229            /*
4230             * Check to make sure the signatures match first. If they don't,
4231             * wipe the installed application and its data.
4232             */
4233            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4234                    != PackageManager.SIGNATURE_MATCH) {
4235                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4236                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4237                ps = null;
4238            } else {
4239                /*
4240                 * If the newly-added system app is an older version than the
4241                 * already installed version, hide it. It will be scanned later
4242                 * and re-added like an update.
4243                 */
4244                if (pkg.mVersionCode < ps.versionCode) {
4245                    shouldHideSystemApp = true;
4246                } else {
4247                    /*
4248                     * The newly found system app is a newer version that the
4249                     * one previously installed. Simply remove the
4250                     * already-installed application and replace it with our own
4251                     * while keeping the application data.
4252                     */
4253                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4254                            + ps.codePathString + ": new version " + pkg.mVersionCode
4255                            + " better than installed " + ps.versionCode);
4256                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4257                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4258                            getAppDexInstructionSets(ps));
4259                    synchronized (mInstallLock) {
4260                        args.cleanUpResourcesLI();
4261                    }
4262                }
4263            }
4264        }
4265
4266        // The apk is forward locked (not public) if its code and resources
4267        // are kept in different files. (except for app in either system or
4268        // vendor path).
4269        // TODO grab this value from PackageSettings
4270        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4271            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4272                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4273            }
4274        }
4275
4276        // TODO: extend to support forward-locked splits
4277        String resourcePath = null;
4278        String baseResourcePath = null;
4279        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4280            if (ps != null && ps.resourcePathString != null) {
4281                resourcePath = ps.resourcePathString;
4282                baseResourcePath = ps.resourcePathString;
4283            } else {
4284                // Should not happen at all. Just log an error.
4285                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4286            }
4287        } else {
4288            resourcePath = pkg.codePath;
4289            baseResourcePath = pkg.baseCodePath;
4290        }
4291
4292        // Set application objects path explicitly.
4293        pkg.applicationInfo.setCodePath(pkg.codePath);
4294        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4295        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4296        pkg.applicationInfo.setResourcePath(resourcePath);
4297        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4298        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4299
4300        // Note that we invoke the following method only if we are about to unpack an application
4301        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4302                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4303
4304        /*
4305         * If the system app should be overridden by a previously installed
4306         * data, hide the system app now and let the /data/app scan pick it up
4307         * again.
4308         */
4309        if (shouldHideSystemApp) {
4310            synchronized (mPackages) {
4311                /*
4312                 * We have to grant systems permissions before we hide, because
4313                 * grantPermissions will assume the package update is trying to
4314                 * expand its permissions.
4315                 */
4316                grantPermissionsLPw(pkg, true, pkg.packageName);
4317                mSettings.disableSystemPackageLPw(pkg.packageName);
4318            }
4319        }
4320
4321        return scannedPkg;
4322    }
4323
4324    private static String fixProcessName(String defProcessName,
4325            String processName, int uid) {
4326        if (processName == null) {
4327            return defProcessName;
4328        }
4329        return processName;
4330    }
4331
4332    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4333            throws PackageManagerException {
4334        if (pkgSetting.signatures.mSignatures != null) {
4335            // Already existing package. Make sure signatures match
4336            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4337                    == PackageManager.SIGNATURE_MATCH;
4338            if (!match) {
4339                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4340                        == PackageManager.SIGNATURE_MATCH;
4341            }
4342            if (!match) {
4343                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4344                        + pkg.packageName + " signatures do not match the "
4345                        + "previously installed version; ignoring!");
4346            }
4347        }
4348
4349        // Check for shared user signatures
4350        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4351            // Already existing package. Make sure signatures match
4352            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4353                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4354            if (!match) {
4355                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4356                        == PackageManager.SIGNATURE_MATCH;
4357            }
4358            if (!match) {
4359                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4360                        "Package " + pkg.packageName
4361                        + " has no signatures that match those in shared user "
4362                        + pkgSetting.sharedUser.name + "; ignoring!");
4363            }
4364        }
4365    }
4366
4367    /**
4368     * Enforces that only the system UID or root's UID can call a method exposed
4369     * via Binder.
4370     *
4371     * @param message used as message if SecurityException is thrown
4372     * @throws SecurityException if the caller is not system or root
4373     */
4374    private static final void enforceSystemOrRoot(String message) {
4375        final int uid = Binder.getCallingUid();
4376        if (uid != Process.SYSTEM_UID && uid != 0) {
4377            throw new SecurityException(message);
4378        }
4379    }
4380
4381    @Override
4382    public void performBootDexOpt() {
4383        enforceSystemOrRoot("Only the system can request dexopt be performed");
4384
4385        final HashSet<PackageParser.Package> pkgs;
4386        synchronized (mPackages) {
4387            pkgs = mDeferredDexOpt;
4388            mDeferredDexOpt = null;
4389        }
4390
4391        if (pkgs != null) {
4392            // Filter out packages that aren't recently used.
4393            //
4394            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4395            // should do a full dexopt.
4396            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4397                // TODO: add a property to control this?
4398                long dexOptLRUThresholdInMinutes;
4399                if (mLazyDexOpt) {
4400                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4401                } else {
4402                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4403                }
4404                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4405
4406                int total = pkgs.size();
4407                int skipped = 0;
4408                long now = System.currentTimeMillis();
4409                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4410                    PackageParser.Package pkg = i.next();
4411                    long then = pkg.mLastPackageUsageTimeInMills;
4412                    if (then + dexOptLRUThresholdInMills < now) {
4413                        if (DEBUG_DEXOPT) {
4414                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4415                                  ((then == 0) ? "never" : new Date(then)));
4416                        }
4417                        i.remove();
4418                        skipped++;
4419                    }
4420                }
4421                if (DEBUG_DEXOPT) {
4422                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4423                }
4424            }
4425
4426            int i = 0;
4427            for (PackageParser.Package pkg : pkgs) {
4428                i++;
4429                if (DEBUG_DEXOPT) {
4430                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4431                          + ": " + pkg.packageName);
4432                }
4433                if (!isFirstBoot()) {
4434                    try {
4435                        ActivityManagerNative.getDefault().showBootMessage(
4436                                mContext.getResources().getString(
4437                                        R.string.android_upgrading_apk,
4438                                        i, pkgs.size()), true);
4439                    } catch (RemoteException e) {
4440                    }
4441                }
4442                PackageParser.Package p = pkg;
4443                synchronized (mInstallLock) {
4444                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4445                            true /* include dependencies */);
4446                }
4447            }
4448        }
4449    }
4450
4451    @Override
4452    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4453        return performDexOpt(packageName, instructionSet, false);
4454    }
4455
4456    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4457        if (info.primaryCpuAbi == null) {
4458            return getPreferredInstructionSet();
4459        }
4460
4461        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4462    }
4463
4464    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4465        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4466        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4467        if (!dexopt && !updateUsage) {
4468            // We aren't going to dexopt or update usage, so bail early.
4469            return false;
4470        }
4471        PackageParser.Package p;
4472        final String targetInstructionSet;
4473        synchronized (mPackages) {
4474            p = mPackages.get(packageName);
4475            if (p == null) {
4476                return false;
4477            }
4478            if (updateUsage) {
4479                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4480            }
4481            mPackageUsage.write(false);
4482            if (!dexopt) {
4483                // We aren't going to dexopt, so bail early.
4484                return false;
4485            }
4486
4487            targetInstructionSet = instructionSet != null ? instructionSet :
4488                    getPrimaryInstructionSet(p.applicationInfo);
4489            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4490                return false;
4491            }
4492        }
4493
4494        synchronized (mInstallLock) {
4495            final String[] instructionSets = new String[] { targetInstructionSet };
4496            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4497                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4498        }
4499    }
4500
4501    public HashSet<String> getPackagesThatNeedDexOpt() {
4502        HashSet<String> pkgs = null;
4503        synchronized (mPackages) {
4504            for (PackageParser.Package p : mPackages.values()) {
4505                if (DEBUG_DEXOPT) {
4506                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4507                }
4508                if (!p.mDexOptPerformed.isEmpty()) {
4509                    continue;
4510                }
4511                if (pkgs == null) {
4512                    pkgs = new HashSet<String>();
4513                }
4514                pkgs.add(p.packageName);
4515            }
4516        }
4517        return pkgs;
4518    }
4519
4520    public void shutdown() {
4521        mPackageUsage.write(true);
4522    }
4523
4524    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4525             boolean forceDex, boolean defer, HashSet<String> done) {
4526        for (int i=0; i<libs.size(); i++) {
4527            PackageParser.Package libPkg;
4528            String libName;
4529            synchronized (mPackages) {
4530                libName = libs.get(i);
4531                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4532                if (lib != null && lib.apk != null) {
4533                    libPkg = mPackages.get(lib.apk);
4534                } else {
4535                    libPkg = null;
4536                }
4537            }
4538            if (libPkg != null && !done.contains(libName)) {
4539                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4540            }
4541        }
4542    }
4543
4544    static final int DEX_OPT_SKIPPED = 0;
4545    static final int DEX_OPT_PERFORMED = 1;
4546    static final int DEX_OPT_DEFERRED = 2;
4547    static final int DEX_OPT_FAILED = -1;
4548
4549    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4550            boolean forceDex, boolean defer, HashSet<String> done) {
4551        final String[] instructionSets = targetInstructionSets != null ?
4552                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4553
4554        if (done != null) {
4555            done.add(pkg.packageName);
4556            if (pkg.usesLibraries != null) {
4557                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4558            }
4559            if (pkg.usesOptionalLibraries != null) {
4560                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4561            }
4562        }
4563
4564        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4565            return DEX_OPT_SKIPPED;
4566        }
4567
4568        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4569
4570        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4571        boolean performedDexOpt = false;
4572        // There are three basic cases here:
4573        // 1.) we need to dexopt, either because we are forced or it is needed
4574        // 2.) we are defering a needed dexopt
4575        // 3.) we are skipping an unneeded dexopt
4576        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4577        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4578            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4579                continue;
4580            }
4581
4582            for (String path : paths) {
4583                try {
4584                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4585                    // patckage or the one we find does not match the image checksum (i.e. it was
4586                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4587                    // odex file and it matches the checksum of the image but not its base address,
4588                    // meaning we need to move it.
4589                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4590                            pkg.packageName, dexCodeInstructionSet, defer);
4591                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4592                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4593                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4594                                + " vmSafeMode=" + vmSafeMode);
4595                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4596                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4597                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4598
4599                        if (ret < 0) {
4600                            // Don't bother running dexopt again if we failed, it will probably
4601                            // just result in an error again. Also, don't bother dexopting for other
4602                            // paths & ISAs.
4603                            return DEX_OPT_FAILED;
4604                        }
4605
4606                        performedDexOpt = true;
4607                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4608                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4609                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4610                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4611                                pkg.packageName, dexCodeInstructionSet);
4612
4613                        if (ret < 0) {
4614                            // Don't bother running patchoat again if we failed, it will probably
4615                            // just result in an error again. Also, don't bother dexopting for other
4616                            // paths & ISAs.
4617                            return DEX_OPT_FAILED;
4618                        }
4619
4620                        performedDexOpt = true;
4621                    }
4622
4623                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4624                    // paths and instruction sets. We'll deal with them all together when we process
4625                    // our list of deferred dexopts.
4626                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4627                        if (mDeferredDexOpt == null) {
4628                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4629                        }
4630                        mDeferredDexOpt.add(pkg);
4631                        return DEX_OPT_DEFERRED;
4632                    }
4633                } catch (FileNotFoundException e) {
4634                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4635                    return DEX_OPT_FAILED;
4636                } catch (IOException e) {
4637                    Slog.w(TAG, "IOException reading apk: " + path, e);
4638                    return DEX_OPT_FAILED;
4639                } catch (StaleDexCacheError e) {
4640                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4641                    return DEX_OPT_FAILED;
4642                } catch (Exception e) {
4643                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4644                    return DEX_OPT_FAILED;
4645                }
4646            }
4647
4648            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4649            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4650            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4651            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4652            // it.
4653            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4654        }
4655
4656        // If we've gotten here, we're sure that no error occurred and that we haven't
4657        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4658        // we've skipped all of them because they are up to date. In both cases this
4659        // package doesn't need dexopt any longer.
4660        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4661    }
4662
4663    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4664        if (info.primaryCpuAbi != null) {
4665            if (info.secondaryCpuAbi != null) {
4666                return new String[] {
4667                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4668                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4669            } else {
4670                return new String[] {
4671                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4672            }
4673        }
4674
4675        return new String[] { getPreferredInstructionSet() };
4676    }
4677
4678    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4679        if (ps.primaryCpuAbiString != null) {
4680            if (ps.secondaryCpuAbiString != null) {
4681                return new String[] {
4682                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4683                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4684            } else {
4685                return new String[] {
4686                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4687            }
4688        }
4689
4690        return new String[] { getPreferredInstructionSet() };
4691    }
4692
4693    private static String getPreferredInstructionSet() {
4694        if (sPreferredInstructionSet == null) {
4695            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4696        }
4697
4698        return sPreferredInstructionSet;
4699    }
4700
4701    private static List<String> getAllInstructionSets() {
4702        final String[] allAbis = Build.SUPPORTED_ABIS;
4703        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4704
4705        for (String abi : allAbis) {
4706            final String instructionSet = VMRuntime.getInstructionSet(abi);
4707            if (!allInstructionSets.contains(instructionSet)) {
4708                allInstructionSets.add(instructionSet);
4709            }
4710        }
4711
4712        return allInstructionSets;
4713    }
4714
4715    /**
4716     * Returns the instruction set that should be used to compile dex code. In the presence of
4717     * a native bridge this might be different than the one shared libraries use.
4718     */
4719    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4720        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4721        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4722    }
4723
4724    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4725        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4726        for (String instructionSet : instructionSets) {
4727            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4728        }
4729        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4730    }
4731
4732    /**
4733     * Returns deduplicated list of supported instructions for dex code.
4734     */
4735    public static String[] getAllDexCodeInstructionSets() {
4736        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4737        for (int i = 0; i < supportedInstructionSets.length; i++) {
4738            String abi = Build.SUPPORTED_ABIS[i];
4739            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4740        }
4741        return getDexCodeInstructionSets(supportedInstructionSets);
4742    }
4743
4744    @Override
4745    public void forceDexOpt(String packageName) {
4746        enforceSystemOrRoot("forceDexOpt");
4747
4748        PackageParser.Package pkg;
4749        synchronized (mPackages) {
4750            pkg = mPackages.get(packageName);
4751            if (pkg == null) {
4752                throw new IllegalArgumentException("Missing package: " + packageName);
4753            }
4754        }
4755
4756        synchronized (mInstallLock) {
4757            final String[] instructionSets = new String[] {
4758                    getPrimaryInstructionSet(pkg.applicationInfo) };
4759            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4760            if (res != DEX_OPT_PERFORMED) {
4761                throw new IllegalStateException("Failed to dexopt: " + res);
4762            }
4763        }
4764    }
4765
4766    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4767                                boolean forceDex, boolean defer, boolean inclDependencies) {
4768        HashSet<String> done;
4769        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4770            done = new HashSet<String>();
4771            done.add(pkg.packageName);
4772        } else {
4773            done = null;
4774        }
4775        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4776    }
4777
4778    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4779        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4780            Slog.w(TAG, "Unable to update from " + oldPkg.name
4781                    + " to " + newPkg.packageName
4782                    + ": old package not in system partition");
4783            return false;
4784        } else if (mPackages.get(oldPkg.name) != null) {
4785            Slog.w(TAG, "Unable to update from " + oldPkg.name
4786                    + " to " + newPkg.packageName
4787                    + ": old package still exists");
4788            return false;
4789        }
4790        return true;
4791    }
4792
4793    File getDataPathForUser(int userId) {
4794        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4795    }
4796
4797    private File getDataPathForPackage(String packageName, int userId) {
4798        /*
4799         * Until we fully support multiple users, return the directory we
4800         * previously would have. The PackageManagerTests will need to be
4801         * revised when this is changed back..
4802         */
4803        if (userId == 0) {
4804            return new File(mAppDataDir, packageName);
4805        } else {
4806            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4807                + File.separator + packageName);
4808        }
4809    }
4810
4811    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4812        int[] users = sUserManager.getUserIds();
4813        int res = mInstaller.install(packageName, uid, uid, seinfo);
4814        if (res < 0) {
4815            return res;
4816        }
4817        for (int user : users) {
4818            if (user != 0) {
4819                res = mInstaller.createUserData(packageName,
4820                        UserHandle.getUid(user, uid), user, seinfo);
4821                if (res < 0) {
4822                    return res;
4823                }
4824            }
4825        }
4826        return res;
4827    }
4828
4829    private int removeDataDirsLI(String packageName) {
4830        int[] users = sUserManager.getUserIds();
4831        int res = 0;
4832        for (int user : users) {
4833            int resInner = mInstaller.remove(packageName, user);
4834            if (resInner < 0) {
4835                res = resInner;
4836            }
4837        }
4838
4839        return res;
4840    }
4841
4842    private int deleteCodeCacheDirsLI(String packageName) {
4843        int[] users = sUserManager.getUserIds();
4844        int res = 0;
4845        for (int user : users) {
4846            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4847            if (resInner < 0) {
4848                res = resInner;
4849            }
4850        }
4851        return res;
4852    }
4853
4854    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4855            PackageParser.Package changingLib) {
4856        if (file.path != null) {
4857            usesLibraryFiles.add(file.path);
4858            return;
4859        }
4860        PackageParser.Package p = mPackages.get(file.apk);
4861        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4862            // If we are doing this while in the middle of updating a library apk,
4863            // then we need to make sure to use that new apk for determining the
4864            // dependencies here.  (We haven't yet finished committing the new apk
4865            // to the package manager state.)
4866            if (p == null || p.packageName.equals(changingLib.packageName)) {
4867                p = changingLib;
4868            }
4869        }
4870        if (p != null) {
4871            usesLibraryFiles.addAll(p.getAllCodePaths());
4872        }
4873    }
4874
4875    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4876            PackageParser.Package changingLib) throws PackageManagerException {
4877        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4878            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4879            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4880            for (int i=0; i<N; i++) {
4881                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4882                if (file == null) {
4883                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4884                            "Package " + pkg.packageName + " requires unavailable shared library "
4885                            + pkg.usesLibraries.get(i) + "; failing!");
4886                }
4887                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4888            }
4889            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4890            for (int i=0; i<N; i++) {
4891                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4892                if (file == null) {
4893                    Slog.w(TAG, "Package " + pkg.packageName
4894                            + " desires unavailable shared library "
4895                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4896                } else {
4897                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4898                }
4899            }
4900            N = usesLibraryFiles.size();
4901            if (N > 0) {
4902                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4903            } else {
4904                pkg.usesLibraryFiles = null;
4905            }
4906        }
4907    }
4908
4909    private static boolean hasString(List<String> list, List<String> which) {
4910        if (list == null) {
4911            return false;
4912        }
4913        for (int i=list.size()-1; i>=0; i--) {
4914            for (int j=which.size()-1; j>=0; j--) {
4915                if (which.get(j).equals(list.get(i))) {
4916                    return true;
4917                }
4918            }
4919        }
4920        return false;
4921    }
4922
4923    private void updateAllSharedLibrariesLPw() {
4924        for (PackageParser.Package pkg : mPackages.values()) {
4925            try {
4926                updateSharedLibrariesLPw(pkg, null);
4927            } catch (PackageManagerException e) {
4928                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4929            }
4930        }
4931    }
4932
4933    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4934            PackageParser.Package changingPkg) {
4935        ArrayList<PackageParser.Package> res = null;
4936        for (PackageParser.Package pkg : mPackages.values()) {
4937            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4938                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4939                if (res == null) {
4940                    res = new ArrayList<PackageParser.Package>();
4941                }
4942                res.add(pkg);
4943                try {
4944                    updateSharedLibrariesLPw(pkg, changingPkg);
4945                } catch (PackageManagerException e) {
4946                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4947                }
4948            }
4949        }
4950        return res;
4951    }
4952
4953    /**
4954     * Derive the value of the {@code cpuAbiOverride} based on the provided
4955     * value and an optional stored value from the package settings.
4956     */
4957    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4958        String cpuAbiOverride = null;
4959
4960        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4961            cpuAbiOverride = null;
4962        } else if (abiOverride != null) {
4963            cpuAbiOverride = abiOverride;
4964        } else if (settings != null) {
4965            cpuAbiOverride = settings.cpuAbiOverrideString;
4966        }
4967
4968        return cpuAbiOverride;
4969    }
4970
4971    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4972            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4973        boolean success = false;
4974        try {
4975            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4976                    currentTime, user);
4977            success = true;
4978            return res;
4979        } finally {
4980            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4981                removeDataDirsLI(pkg.packageName);
4982            }
4983        }
4984    }
4985
4986    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
4987            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4988        final File scanFile = new File(pkg.codePath);
4989        if (pkg.applicationInfo.getCodePath() == null ||
4990                pkg.applicationInfo.getResourcePath() == null) {
4991            // Bail out. The resource and code paths haven't been set.
4992            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4993                    "Code and resource paths haven't been set correctly");
4994        }
4995
4996        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4997            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4998        }
4999
5000        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5001            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5002        }
5003
5004        if (mCustomResolverComponentName != null &&
5005                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5006            setUpCustomResolverActivity(pkg);
5007        }
5008
5009        if (pkg.packageName.equals("android")) {
5010            synchronized (mPackages) {
5011                if (mAndroidApplication != null) {
5012                    Slog.w(TAG, "*************************************************");
5013                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5014                    Slog.w(TAG, " file=" + scanFile);
5015                    Slog.w(TAG, "*************************************************");
5016                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5017                            "Core android package being redefined.  Skipping.");
5018                }
5019
5020                // Set up information for our fall-back user intent resolution activity.
5021                mPlatformPackage = pkg;
5022                pkg.mVersionCode = mSdkVersion;
5023                mAndroidApplication = pkg.applicationInfo;
5024
5025                if (!mResolverReplaced) {
5026                    mResolveActivity.applicationInfo = mAndroidApplication;
5027                    mResolveActivity.name = ResolverActivity.class.getName();
5028                    mResolveActivity.packageName = mAndroidApplication.packageName;
5029                    mResolveActivity.processName = "system:ui";
5030                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5031                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5032                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5033                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5034                    mResolveActivity.exported = true;
5035                    mResolveActivity.enabled = true;
5036                    mResolveInfo.activityInfo = mResolveActivity;
5037                    mResolveInfo.priority = 0;
5038                    mResolveInfo.preferredOrder = 0;
5039                    mResolveInfo.match = 0;
5040                    mResolveComponentName = new ComponentName(
5041                            mAndroidApplication.packageName, mResolveActivity.name);
5042                }
5043            }
5044        }
5045
5046        if (DEBUG_PACKAGE_SCANNING) {
5047            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5048                Log.d(TAG, "Scanning package " + pkg.packageName);
5049        }
5050
5051        if (mPackages.containsKey(pkg.packageName)
5052                || mSharedLibraries.containsKey(pkg.packageName)) {
5053            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5054                    "Application package " + pkg.packageName
5055                    + " already installed.  Skipping duplicate.");
5056        }
5057
5058        // Initialize package source and resource directories
5059        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5060        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5061
5062        SharedUserSetting suid = null;
5063        PackageSetting pkgSetting = null;
5064
5065        if (!isSystemApp(pkg)) {
5066            // Only system apps can use these features.
5067            pkg.mOriginalPackages = null;
5068            pkg.mRealPackage = null;
5069            pkg.mAdoptPermissions = null;
5070        }
5071
5072        // writer
5073        synchronized (mPackages) {
5074            if (pkg.mSharedUserId != null) {
5075                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5076                if (suid == null) {
5077                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5078                            "Creating application package " + pkg.packageName
5079                            + " for shared user failed");
5080                }
5081                if (DEBUG_PACKAGE_SCANNING) {
5082                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5083                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5084                                + "): packages=" + suid.packages);
5085                }
5086            }
5087
5088            // Check if we are renaming from an original package name.
5089            PackageSetting origPackage = null;
5090            String realName = null;
5091            if (pkg.mOriginalPackages != null) {
5092                // This package may need to be renamed to a previously
5093                // installed name.  Let's check on that...
5094                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5095                if (pkg.mOriginalPackages.contains(renamed)) {
5096                    // This package had originally been installed as the
5097                    // original name, and we have already taken care of
5098                    // transitioning to the new one.  Just update the new
5099                    // one to continue using the old name.
5100                    realName = pkg.mRealPackage;
5101                    if (!pkg.packageName.equals(renamed)) {
5102                        // Callers into this function may have already taken
5103                        // care of renaming the package; only do it here if
5104                        // it is not already done.
5105                        pkg.setPackageName(renamed);
5106                    }
5107
5108                } else {
5109                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5110                        if ((origPackage = mSettings.peekPackageLPr(
5111                                pkg.mOriginalPackages.get(i))) != null) {
5112                            // We do have the package already installed under its
5113                            // original name...  should we use it?
5114                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5115                                // New package is not compatible with original.
5116                                origPackage = null;
5117                                continue;
5118                            } else if (origPackage.sharedUser != null) {
5119                                // Make sure uid is compatible between packages.
5120                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5121                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5122                                            + " to " + pkg.packageName + ": old uid "
5123                                            + origPackage.sharedUser.name
5124                                            + " differs from " + pkg.mSharedUserId);
5125                                    origPackage = null;
5126                                    continue;
5127                                }
5128                            } else {
5129                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5130                                        + pkg.packageName + " to old name " + origPackage.name);
5131                            }
5132                            break;
5133                        }
5134                    }
5135                }
5136            }
5137
5138            if (mTransferedPackages.contains(pkg.packageName)) {
5139                Slog.w(TAG, "Package " + pkg.packageName
5140                        + " was transferred to another, but its .apk remains");
5141            }
5142
5143            // Just create the setting, don't add it yet. For already existing packages
5144            // the PkgSetting exists already and doesn't have to be created.
5145            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5146                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5147                    pkg.applicationInfo.primaryCpuAbi,
5148                    pkg.applicationInfo.secondaryCpuAbi,
5149                    pkg.applicationInfo.flags, user, false);
5150            if (pkgSetting == null) {
5151                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5152                        "Creating application package " + pkg.packageName + " failed");
5153            }
5154
5155            if (pkgSetting.origPackage != null) {
5156                // If we are first transitioning from an original package,
5157                // fix up the new package's name now.  We need to do this after
5158                // looking up the package under its new name, so getPackageLP
5159                // can take care of fiddling things correctly.
5160                pkg.setPackageName(origPackage.name);
5161
5162                // File a report about this.
5163                String msg = "New package " + pkgSetting.realName
5164                        + " renamed to replace old package " + pkgSetting.name;
5165                reportSettingsProblem(Log.WARN, msg);
5166
5167                // Make a note of it.
5168                mTransferedPackages.add(origPackage.name);
5169
5170                // No longer need to retain this.
5171                pkgSetting.origPackage = null;
5172            }
5173
5174            if (realName != null) {
5175                // Make a note of it.
5176                mTransferedPackages.add(pkg.packageName);
5177            }
5178
5179            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5180                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5181            }
5182
5183            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5184                // Check all shared libraries and map to their actual file path.
5185                // We only do this here for apps not on a system dir, because those
5186                // are the only ones that can fail an install due to this.  We
5187                // will take care of the system apps by updating all of their
5188                // library paths after the scan is done.
5189                updateSharedLibrariesLPw(pkg, null);
5190            }
5191
5192            if (mFoundPolicyFile) {
5193                SELinuxMMAC.assignSeinfoValue(pkg);
5194            }
5195
5196            pkg.applicationInfo.uid = pkgSetting.appId;
5197            pkg.mExtras = pkgSetting;
5198            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5199                try {
5200                    verifySignaturesLP(pkgSetting, pkg);
5201                } catch (PackageManagerException e) {
5202                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5203                        throw e;
5204                    }
5205                    // The signature has changed, but this package is in the system
5206                    // image...  let's recover!
5207                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5208                    // However...  if this package is part of a shared user, but it
5209                    // doesn't match the signature of the shared user, let's fail.
5210                    // What this means is that you can't change the signatures
5211                    // associated with an overall shared user, which doesn't seem all
5212                    // that unreasonable.
5213                    if (pkgSetting.sharedUser != null) {
5214                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5215                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5216                            throw new PackageManagerException(
5217                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5218                                            "Signature mismatch for shared user : "
5219                                            + pkgSetting.sharedUser);
5220                        }
5221                    }
5222                    // File a report about this.
5223                    String msg = "System package " + pkg.packageName
5224                        + " signature changed; retaining data.";
5225                    reportSettingsProblem(Log.WARN, msg);
5226                }
5227            } else {
5228                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5229                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5230                            + pkg.packageName + " upgrade keys do not match the "
5231                            + "previously installed version");
5232                } else {
5233                    // signatures may have changed as result of upgrade
5234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5235                }
5236            }
5237            // Verify that this new package doesn't have any content providers
5238            // that conflict with existing packages.  Only do this if the
5239            // package isn't already installed, since we don't want to break
5240            // things that are installed.
5241            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5242                final int N = pkg.providers.size();
5243                int i;
5244                for (i=0; i<N; i++) {
5245                    PackageParser.Provider p = pkg.providers.get(i);
5246                    if (p.info.authority != null) {
5247                        String names[] = p.info.authority.split(";");
5248                        for (int j = 0; j < names.length; j++) {
5249                            if (mProvidersByAuthority.containsKey(names[j])) {
5250                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5251                                final String otherPackageName =
5252                                        ((other != null && other.getComponentName() != null) ?
5253                                                other.getComponentName().getPackageName() : "?");
5254                                throw new PackageManagerException(
5255                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5256                                                "Can't install because provider name " + names[j]
5257                                                + " (in package " + pkg.applicationInfo.packageName
5258                                                + ") is already used by " + otherPackageName);
5259                            }
5260                        }
5261                    }
5262                }
5263            }
5264
5265            if (pkg.mAdoptPermissions != null) {
5266                // This package wants to adopt ownership of permissions from
5267                // another package.
5268                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5269                    final String origName = pkg.mAdoptPermissions.get(i);
5270                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5271                    if (orig != null) {
5272                        if (verifyPackageUpdateLPr(orig, pkg)) {
5273                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5274                                    + pkg.packageName);
5275                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5276                        }
5277                    }
5278                }
5279            }
5280        }
5281
5282        final String pkgName = pkg.packageName;
5283
5284        final long scanFileTime = scanFile.lastModified();
5285        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5286        pkg.applicationInfo.processName = fixProcessName(
5287                pkg.applicationInfo.packageName,
5288                pkg.applicationInfo.processName,
5289                pkg.applicationInfo.uid);
5290
5291        File dataPath;
5292        if (mPlatformPackage == pkg) {
5293            // The system package is special.
5294            dataPath = new File(Environment.getDataDirectory(), "system");
5295
5296            pkg.applicationInfo.dataDir = dataPath.getPath();
5297
5298        } else {
5299            // This is a normal package, need to make its data directory.
5300            dataPath = getDataPathForPackage(pkg.packageName, 0);
5301
5302            boolean uidError = false;
5303            if (dataPath.exists()) {
5304                int currentUid = 0;
5305                try {
5306                    StructStat stat = Os.stat(dataPath.getPath());
5307                    currentUid = stat.st_uid;
5308                } catch (ErrnoException e) {
5309                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5310                }
5311
5312                // If we have mismatched owners for the data path, we have a problem.
5313                if (currentUid != pkg.applicationInfo.uid) {
5314                    boolean recovered = false;
5315                    if (currentUid == 0) {
5316                        // The directory somehow became owned by root.  Wow.
5317                        // This is probably because the system was stopped while
5318                        // installd was in the middle of messing with its libs
5319                        // directory.  Ask installd to fix that.
5320                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5321                                pkg.applicationInfo.uid);
5322                        if (ret >= 0) {
5323                            recovered = true;
5324                            String msg = "Package " + pkg.packageName
5325                                    + " unexpectedly changed to uid 0; recovered to " +
5326                                    + pkg.applicationInfo.uid;
5327                            reportSettingsProblem(Log.WARN, msg);
5328                        }
5329                    }
5330                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5331                            || (scanFlags&SCAN_BOOTING) != 0)) {
5332                        // If this is a system app, we can at least delete its
5333                        // current data so the application will still work.
5334                        int ret = removeDataDirsLI(pkgName);
5335                        if (ret >= 0) {
5336                            // TODO: Kill the processes first
5337                            // Old data gone!
5338                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5339                                    ? "System package " : "Third party package ";
5340                            String msg = prefix + pkg.packageName
5341                                    + " has changed from uid: "
5342                                    + currentUid + " to "
5343                                    + pkg.applicationInfo.uid + "; old data erased";
5344                            reportSettingsProblem(Log.WARN, msg);
5345                            recovered = true;
5346
5347                            // And now re-install the app.
5348                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5349                                                   pkg.applicationInfo.seinfo);
5350                            if (ret == -1) {
5351                                // Ack should not happen!
5352                                msg = prefix + pkg.packageName
5353                                        + " could not have data directory re-created after delete.";
5354                                reportSettingsProblem(Log.WARN, msg);
5355                                throw new PackageManagerException(
5356                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5357                            }
5358                        }
5359                        if (!recovered) {
5360                            mHasSystemUidErrors = true;
5361                        }
5362                    } else if (!recovered) {
5363                        // If we allow this install to proceed, we will be broken.
5364                        // Abort, abort!
5365                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5366                                "scanPackageLI");
5367                    }
5368                    if (!recovered) {
5369                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5370                            + pkg.applicationInfo.uid + "/fs_"
5371                            + currentUid;
5372                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5373                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5374                        String msg = "Package " + pkg.packageName
5375                                + " has mismatched uid: "
5376                                + currentUid + " on disk, "
5377                                + pkg.applicationInfo.uid + " in settings";
5378                        // writer
5379                        synchronized (mPackages) {
5380                            mSettings.mReadMessages.append(msg);
5381                            mSettings.mReadMessages.append('\n');
5382                            uidError = true;
5383                            if (!pkgSetting.uidError) {
5384                                reportSettingsProblem(Log.ERROR, msg);
5385                            }
5386                        }
5387                    }
5388                }
5389                pkg.applicationInfo.dataDir = dataPath.getPath();
5390                if (mShouldRestoreconData) {
5391                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5392                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5393                                pkg.applicationInfo.uid);
5394                }
5395            } else {
5396                if (DEBUG_PACKAGE_SCANNING) {
5397                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5398                        Log.v(TAG, "Want this data dir: " + dataPath);
5399                }
5400                //invoke installer to do the actual installation
5401                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5402                                           pkg.applicationInfo.seinfo);
5403                if (ret < 0) {
5404                    // Error from installer
5405                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5406                            "Unable to create data dirs [errorCode=" + ret + "]");
5407                }
5408
5409                if (dataPath.exists()) {
5410                    pkg.applicationInfo.dataDir = dataPath.getPath();
5411                } else {
5412                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5413                    pkg.applicationInfo.dataDir = null;
5414                }
5415            }
5416
5417            pkgSetting.uidError = uidError;
5418        }
5419
5420        final String path = scanFile.getPath();
5421        final String codePath = pkg.applicationInfo.getCodePath();
5422        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5423        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5424            setBundledAppAbisAndRoots(pkg, pkgSetting);
5425
5426            // If we haven't found any native libraries for the app, check if it has
5427            // renderscript code. We'll need to force the app to 32 bit if it has
5428            // renderscript bitcode.
5429            if (pkg.applicationInfo.primaryCpuAbi == null
5430                    && pkg.applicationInfo.secondaryCpuAbi == null
5431                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5432                NativeLibraryHelper.Handle handle = null;
5433                try {
5434                    handle = NativeLibraryHelper.Handle.create(scanFile);
5435                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5436                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5437                    }
5438                } catch (IOException ioe) {
5439                    Slog.w(TAG, "Error scanning system app : " + ioe);
5440                } finally {
5441                    IoUtils.closeQuietly(handle);
5442                }
5443            }
5444
5445            setNativeLibraryPaths(pkg);
5446        } else {
5447            // TODO: We can probably be smarter about this stuff. For installed apps,
5448            // we can calculate this information at install time once and for all. For
5449            // system apps, we can probably assume that this information doesn't change
5450            // after the first boot scan. As things stand, we do lots of unnecessary work.
5451
5452            // Give ourselves some initial paths; we'll come back for another
5453            // pass once we've determined ABI below.
5454            setNativeLibraryPaths(pkg);
5455
5456            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5457            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5458            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5459
5460            NativeLibraryHelper.Handle handle = null;
5461            try {
5462                handle = NativeLibraryHelper.Handle.create(scanFile);
5463                // TODO(multiArch): This can be null for apps that didn't go through the
5464                // usual installation process. We can calculate it again, like we
5465                // do during install time.
5466                //
5467                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5468                // unnecessary.
5469                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5470
5471                // Null out the abis so that they can be recalculated.
5472                pkg.applicationInfo.primaryCpuAbi = null;
5473                pkg.applicationInfo.secondaryCpuAbi = null;
5474                if (isMultiArch(pkg.applicationInfo)) {
5475                    // Warn if we've set an abiOverride for multi-lib packages..
5476                    // By definition, we need to copy both 32 and 64 bit libraries for
5477                    // such packages.
5478                    if (pkg.cpuAbiOverride != null
5479                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5480                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5481                    }
5482
5483                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5484                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5485                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5486                        if (isAsec) {
5487                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5488                        } else {
5489                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5490                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5491                                    useIsaSpecificSubdirs);
5492                        }
5493                    }
5494
5495                    maybeThrowExceptionForMultiArchCopy(
5496                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5497
5498                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5499                        if (isAsec) {
5500                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5501                        } else {
5502                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5503                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5504                                    useIsaSpecificSubdirs);
5505                        }
5506                    }
5507
5508                    maybeThrowExceptionForMultiArchCopy(
5509                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5510
5511                    if (abi64 >= 0) {
5512                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5513                    }
5514
5515                    if (abi32 >= 0) {
5516                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5517                        if (abi64 >= 0) {
5518                            pkg.applicationInfo.secondaryCpuAbi = abi;
5519                        } else {
5520                            pkg.applicationInfo.primaryCpuAbi = abi;
5521                        }
5522                    }
5523                } else {
5524                    String[] abiList = (cpuAbiOverride != null) ?
5525                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5526
5527                    // Enable gross and lame hacks for apps that are built with old
5528                    // SDK tools. We must scan their APKs for renderscript bitcode and
5529                    // not launch them if it's present. Don't bother checking on devices
5530                    // that don't have 64 bit support.
5531                    boolean needsRenderScriptOverride = false;
5532                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5533                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5534                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5535                        needsRenderScriptOverride = true;
5536                    }
5537
5538                    final int copyRet;
5539                    if (isAsec) {
5540                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5541                    } else {
5542                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5543                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5544                    }
5545
5546                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5547                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5548                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5549                    }
5550
5551                    if (copyRet >= 0) {
5552                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5553                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5554                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5555                    } else if (needsRenderScriptOverride) {
5556                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5557                    }
5558                }
5559            } catch (IOException ioe) {
5560                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5561            } finally {
5562                IoUtils.closeQuietly(handle);
5563            }
5564
5565            // Now that we've calculated the ABIs and determined if it's an internal app,
5566            // we will go ahead and populate the nativeLibraryPath.
5567            setNativeLibraryPaths(pkg);
5568
5569            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5570            final int[] userIds = sUserManager.getUserIds();
5571            synchronized (mInstallLock) {
5572                // Create a native library symlink only if we have native libraries
5573                // and if the native libraries are 32 bit libraries. We do not provide
5574                // this symlink for 64 bit libraries.
5575                if (pkg.applicationInfo.primaryCpuAbi != null &&
5576                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5577                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5578                    for (int userId : userIds) {
5579                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5580                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5581                                    "Failed linking native library dir (user=" + userId + ")");
5582                        }
5583                    }
5584                }
5585            }
5586        }
5587
5588        // This is a special case for the "system" package, where the ABI is
5589        // dictated by the zygote configuration (and init.rc). We should keep track
5590        // of this ABI so that we can deal with "normal" applications that run under
5591        // the same UID correctly.
5592        if (mPlatformPackage == pkg) {
5593            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5594                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5595        }
5596
5597        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5598        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5599        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5600        // Copy the derived override back to the parsed package, so that we can
5601        // update the package settings accordingly.
5602        pkg.cpuAbiOverride = cpuAbiOverride;
5603
5604        if (DEBUG_ABI_SELECTION) {
5605            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5606                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5607                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5608        }
5609
5610        // Push the derived path down into PackageSettings so we know what to
5611        // clean up at uninstall time.
5612        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5613
5614        if (DEBUG_ABI_SELECTION) {
5615            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5616                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5617                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5618        }
5619
5620        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5621            // We don't do this here during boot because we can do it all
5622            // at once after scanning all existing packages.
5623            //
5624            // We also do this *before* we perform dexopt on this package, so that
5625            // we can avoid redundant dexopts, and also to make sure we've got the
5626            // code and package path correct.
5627            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5628                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5629        }
5630
5631        if ((scanFlags & SCAN_NO_DEX) == 0) {
5632            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5633                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5634                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5635            }
5636        }
5637
5638        if (mFactoryTest && pkg.requestedPermissions.contains(
5639                android.Manifest.permission.FACTORY_TEST)) {
5640            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5641        }
5642
5643        ArrayList<PackageParser.Package> clientLibPkgs = null;
5644
5645        // writer
5646        synchronized (mPackages) {
5647            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5648                // Only system apps can add new shared libraries.
5649                if (pkg.libraryNames != null) {
5650                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5651                        String name = pkg.libraryNames.get(i);
5652                        boolean allowed = false;
5653                        if (isUpdatedSystemApp(pkg)) {
5654                            // New library entries can only be added through the
5655                            // system image.  This is important to get rid of a lot
5656                            // of nasty edge cases: for example if we allowed a non-
5657                            // system update of the app to add a library, then uninstalling
5658                            // the update would make the library go away, and assumptions
5659                            // we made such as through app install filtering would now
5660                            // have allowed apps on the device which aren't compatible
5661                            // with it.  Better to just have the restriction here, be
5662                            // conservative, and create many fewer cases that can negatively
5663                            // impact the user experience.
5664                            final PackageSetting sysPs = mSettings
5665                                    .getDisabledSystemPkgLPr(pkg.packageName);
5666                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5667                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5668                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5669                                        allowed = true;
5670                                        allowed = true;
5671                                        break;
5672                                    }
5673                                }
5674                            }
5675                        } else {
5676                            allowed = true;
5677                        }
5678                        if (allowed) {
5679                            if (!mSharedLibraries.containsKey(name)) {
5680                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5681                            } else if (!name.equals(pkg.packageName)) {
5682                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5683                                        + name + " already exists; skipping");
5684                            }
5685                        } else {
5686                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5687                                    + name + " that is not declared on system image; skipping");
5688                        }
5689                    }
5690                    if ((scanFlags&SCAN_BOOTING) == 0) {
5691                        // If we are not booting, we need to update any applications
5692                        // that are clients of our shared library.  If we are booting,
5693                        // this will all be done once the scan is complete.
5694                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5695                    }
5696                }
5697            }
5698        }
5699
5700        // We also need to dexopt any apps that are dependent on this library.  Note that
5701        // if these fail, we should abort the install since installing the library will
5702        // result in some apps being broken.
5703        if (clientLibPkgs != null) {
5704            if ((scanFlags & SCAN_NO_DEX) == 0) {
5705                for (int i = 0; i < clientLibPkgs.size(); i++) {
5706                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5707                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5708                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5709                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5710                                "scanPackageLI failed to dexopt clientLibPkgs");
5711                    }
5712                }
5713            }
5714        }
5715
5716        // Request the ActivityManager to kill the process(only for existing packages)
5717        // so that we do not end up in a confused state while the user is still using the older
5718        // version of the application while the new one gets installed.
5719        if ((scanFlags & SCAN_REPLACING) != 0) {
5720            killApplication(pkg.applicationInfo.packageName,
5721                        pkg.applicationInfo.uid, "update pkg");
5722        }
5723
5724        // Also need to kill any apps that are dependent on the library.
5725        if (clientLibPkgs != null) {
5726            for (int i=0; i<clientLibPkgs.size(); i++) {
5727                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5728                killApplication(clientPkg.applicationInfo.packageName,
5729                        clientPkg.applicationInfo.uid, "update lib");
5730            }
5731        }
5732
5733        // writer
5734        synchronized (mPackages) {
5735            // We don't expect installation to fail beyond this point
5736
5737            // Add the new setting to mSettings
5738            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5739            // Add the new setting to mPackages
5740            mPackages.put(pkg.applicationInfo.packageName, pkg);
5741            // Make sure we don't accidentally delete its data.
5742            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5743            while (iter.hasNext()) {
5744                PackageCleanItem item = iter.next();
5745                if (pkgName.equals(item.packageName)) {
5746                    iter.remove();
5747                }
5748            }
5749
5750            // Take care of first install / last update times.
5751            if (currentTime != 0) {
5752                if (pkgSetting.firstInstallTime == 0) {
5753                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5754                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5755                    pkgSetting.lastUpdateTime = currentTime;
5756                }
5757            } else if (pkgSetting.firstInstallTime == 0) {
5758                // We need *something*.  Take time time stamp of the file.
5759                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5760            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5761                if (scanFileTime != pkgSetting.timeStamp) {
5762                    // A package on the system image has changed; consider this
5763                    // to be an update.
5764                    pkgSetting.lastUpdateTime = scanFileTime;
5765                }
5766            }
5767
5768            // Add the package's KeySets to the global KeySetManagerService
5769            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5770            try {
5771                // Old KeySetData no longer valid.
5772                ksms.removeAppKeySetDataLPw(pkg.packageName);
5773                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5774                if (pkg.mKeySetMapping != null) {
5775                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5776                            pkg.mKeySetMapping.entrySet()) {
5777                        if (entry.getValue() != null) {
5778                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5779                                                          entry.getValue(), entry.getKey());
5780                        }
5781                    }
5782                    if (pkg.mUpgradeKeySets != null) {
5783                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5784                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5785                        }
5786                    }
5787                }
5788            } catch (NullPointerException e) {
5789                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5790            } catch (IllegalArgumentException e) {
5791                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5792            }
5793
5794            int N = pkg.providers.size();
5795            StringBuilder r = null;
5796            int i;
5797            for (i=0; i<N; i++) {
5798                PackageParser.Provider p = pkg.providers.get(i);
5799                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5800                        p.info.processName, pkg.applicationInfo.uid);
5801                mProviders.addProvider(p);
5802                p.syncable = p.info.isSyncable;
5803                if (p.info.authority != null) {
5804                    String names[] = p.info.authority.split(";");
5805                    p.info.authority = null;
5806                    for (int j = 0; j < names.length; j++) {
5807                        if (j == 1 && p.syncable) {
5808                            // We only want the first authority for a provider to possibly be
5809                            // syncable, so if we already added this provider using a different
5810                            // authority clear the syncable flag. We copy the provider before
5811                            // changing it because the mProviders object contains a reference
5812                            // to a provider that we don't want to change.
5813                            // Only do this for the second authority since the resulting provider
5814                            // object can be the same for all future authorities for this provider.
5815                            p = new PackageParser.Provider(p);
5816                            p.syncable = false;
5817                        }
5818                        if (!mProvidersByAuthority.containsKey(names[j])) {
5819                            mProvidersByAuthority.put(names[j], p);
5820                            if (p.info.authority == null) {
5821                                p.info.authority = names[j];
5822                            } else {
5823                                p.info.authority = p.info.authority + ";" + names[j];
5824                            }
5825                            if (DEBUG_PACKAGE_SCANNING) {
5826                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5827                                    Log.d(TAG, "Registered content provider: " + names[j]
5828                                            + ", className = " + p.info.name + ", isSyncable = "
5829                                            + p.info.isSyncable);
5830                            }
5831                        } else {
5832                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5833                            Slog.w(TAG, "Skipping provider name " + names[j] +
5834                                    " (in package " + pkg.applicationInfo.packageName +
5835                                    "): name already used by "
5836                                    + ((other != null && other.getComponentName() != null)
5837                                            ? other.getComponentName().getPackageName() : "?"));
5838                        }
5839                    }
5840                }
5841                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5842                    if (r == null) {
5843                        r = new StringBuilder(256);
5844                    } else {
5845                        r.append(' ');
5846                    }
5847                    r.append(p.info.name);
5848                }
5849            }
5850            if (r != null) {
5851                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5852            }
5853
5854            N = pkg.services.size();
5855            r = null;
5856            for (i=0; i<N; i++) {
5857                PackageParser.Service s = pkg.services.get(i);
5858                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5859                        s.info.processName, pkg.applicationInfo.uid);
5860                mServices.addService(s);
5861                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5862                    if (r == null) {
5863                        r = new StringBuilder(256);
5864                    } else {
5865                        r.append(' ');
5866                    }
5867                    r.append(s.info.name);
5868                }
5869            }
5870            if (r != null) {
5871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5872            }
5873
5874            N = pkg.receivers.size();
5875            r = null;
5876            for (i=0; i<N; i++) {
5877                PackageParser.Activity a = pkg.receivers.get(i);
5878                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5879                        a.info.processName, pkg.applicationInfo.uid);
5880                mReceivers.addActivity(a, "receiver");
5881                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5882                    if (r == null) {
5883                        r = new StringBuilder(256);
5884                    } else {
5885                        r.append(' ');
5886                    }
5887                    r.append(a.info.name);
5888                }
5889            }
5890            if (r != null) {
5891                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5892            }
5893
5894            N = pkg.activities.size();
5895            r = null;
5896            for (i=0; i<N; i++) {
5897                PackageParser.Activity a = pkg.activities.get(i);
5898                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5899                        a.info.processName, pkg.applicationInfo.uid);
5900                mActivities.addActivity(a, "activity");
5901                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5902                    if (r == null) {
5903                        r = new StringBuilder(256);
5904                    } else {
5905                        r.append(' ');
5906                    }
5907                    r.append(a.info.name);
5908                }
5909            }
5910            if (r != null) {
5911                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5912            }
5913
5914            N = pkg.permissionGroups.size();
5915            r = null;
5916            for (i=0; i<N; i++) {
5917                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5918                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5919                if (cur == null) {
5920                    mPermissionGroups.put(pg.info.name, pg);
5921                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5922                        if (r == null) {
5923                            r = new StringBuilder(256);
5924                        } else {
5925                            r.append(' ');
5926                        }
5927                        r.append(pg.info.name);
5928                    }
5929                } else {
5930                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5931                            + pg.info.packageName + " ignored: original from "
5932                            + cur.info.packageName);
5933                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5934                        if (r == null) {
5935                            r = new StringBuilder(256);
5936                        } else {
5937                            r.append(' ');
5938                        }
5939                        r.append("DUP:");
5940                        r.append(pg.info.name);
5941                    }
5942                }
5943            }
5944            if (r != null) {
5945                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5946            }
5947
5948            N = pkg.permissions.size();
5949            r = null;
5950            for (i=0; i<N; i++) {
5951                PackageParser.Permission p = pkg.permissions.get(i);
5952                HashMap<String, BasePermission> permissionMap =
5953                        p.tree ? mSettings.mPermissionTrees
5954                        : mSettings.mPermissions;
5955                p.group = mPermissionGroups.get(p.info.group);
5956                if (p.info.group == null || p.group != null) {
5957                    BasePermission bp = permissionMap.get(p.info.name);
5958
5959                    // Allow system apps to redefine non-system permissions
5960                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5961                        final boolean currentOwnerIsSystem = (bp.perm != null
5962                                && isSystemApp(bp.perm.owner));
5963                        if (isSystemApp(p.owner) && !currentOwnerIsSystem) {
5964                            String msg = "New decl " + p.owner + " of permission  "
5965                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
5966                            reportSettingsProblem(Log.WARN, msg);
5967                            bp = null;
5968                        }
5969                    }
5970
5971                    if (bp == null) {
5972                        bp = new BasePermission(p.info.name, p.info.packageName,
5973                                BasePermission.TYPE_NORMAL);
5974                        permissionMap.put(p.info.name, bp);
5975                    }
5976
5977                    if (bp.perm == null) {
5978                        if (bp.sourcePackage == null
5979                                || bp.sourcePackage.equals(p.info.packageName)) {
5980                            BasePermission tree = findPermissionTreeLP(p.info.name);
5981                            if (tree == null
5982                                    || tree.sourcePackage.equals(p.info.packageName)) {
5983                                bp.packageSetting = pkgSetting;
5984                                bp.perm = p;
5985                                bp.uid = pkg.applicationInfo.uid;
5986                                bp.sourcePackage = p.info.packageName;
5987                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5988                                    if (r == null) {
5989                                        r = new StringBuilder(256);
5990                                    } else {
5991                                        r.append(' ');
5992                                    }
5993                                    r.append(p.info.name);
5994                                }
5995                            } else {
5996                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5997                                        + p.info.packageName + " ignored: base tree "
5998                                        + tree.name + " is from package "
5999                                        + tree.sourcePackage);
6000                            }
6001                        } else {
6002                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6003                                    + p.info.packageName + " ignored: original from "
6004                                    + bp.sourcePackage);
6005                        }
6006                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6007                        if (r == null) {
6008                            r = new StringBuilder(256);
6009                        } else {
6010                            r.append(' ');
6011                        }
6012                        r.append("DUP:");
6013                        r.append(p.info.name);
6014                    }
6015                    if (bp.perm == p) {
6016                        bp.protectionLevel = p.info.protectionLevel;
6017                    }
6018                } else {
6019                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6020                            + p.info.packageName + " ignored: no group "
6021                            + p.group);
6022                }
6023            }
6024            if (r != null) {
6025                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6026            }
6027
6028            N = pkg.instrumentation.size();
6029            r = null;
6030            for (i=0; i<N; i++) {
6031                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6032                a.info.packageName = pkg.applicationInfo.packageName;
6033                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6034                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6035                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6036                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6037                a.info.dataDir = pkg.applicationInfo.dataDir;
6038
6039                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6040                // need other information about the application, like the ABI and what not ?
6041                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6042                mInstrumentation.put(a.getComponentName(), a);
6043                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6044                    if (r == null) {
6045                        r = new StringBuilder(256);
6046                    } else {
6047                        r.append(' ');
6048                    }
6049                    r.append(a.info.name);
6050                }
6051            }
6052            if (r != null) {
6053                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6054            }
6055
6056            if (pkg.protectedBroadcasts != null) {
6057                N = pkg.protectedBroadcasts.size();
6058                for (i=0; i<N; i++) {
6059                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6060                }
6061            }
6062
6063            pkgSetting.setTimeStamp(scanFileTime);
6064
6065            // Create idmap files for pairs of (packages, overlay packages).
6066            // Note: "android", ie framework-res.apk, is handled by native layers.
6067            if (pkg.mOverlayTarget != null) {
6068                // This is an overlay package.
6069                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6070                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6071                        mOverlays.put(pkg.mOverlayTarget,
6072                                new HashMap<String, PackageParser.Package>());
6073                    }
6074                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6075                    map.put(pkg.packageName, pkg);
6076                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6077                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6078                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6079                                "scanPackageLI failed to createIdmap");
6080                    }
6081                }
6082            } else if (mOverlays.containsKey(pkg.packageName) &&
6083                    !pkg.packageName.equals("android")) {
6084                // This is a regular package, with one or more known overlay packages.
6085                createIdmapsForPackageLI(pkg);
6086            }
6087        }
6088
6089        return pkg;
6090    }
6091
6092    /**
6093     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6094     * i.e, so that all packages can be run inside a single process if required.
6095     *
6096     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6097     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6098     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6099     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6100     * updating a package that belongs to a shared user.
6101     *
6102     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6103     * adds unnecessary complexity.
6104     */
6105    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6106            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6107        String requiredInstructionSet = null;
6108        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6109            requiredInstructionSet = VMRuntime.getInstructionSet(
6110                     scannedPackage.applicationInfo.primaryCpuAbi);
6111        }
6112
6113        PackageSetting requirer = null;
6114        for (PackageSetting ps : packagesForUser) {
6115            // If packagesForUser contains scannedPackage, we skip it. This will happen
6116            // when scannedPackage is an update of an existing package. Without this check,
6117            // we will never be able to change the ABI of any package belonging to a shared
6118            // user, even if it's compatible with other packages.
6119            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6120                if (ps.primaryCpuAbiString == null) {
6121                    continue;
6122                }
6123
6124                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6125                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6126                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6127                    // this but there's not much we can do.
6128                    String errorMessage = "Instruction set mismatch, "
6129                            + ((requirer == null) ? "[caller]" : requirer)
6130                            + " requires " + requiredInstructionSet + " whereas " + ps
6131                            + " requires " + instructionSet;
6132                    Slog.w(TAG, errorMessage);
6133                }
6134
6135                if (requiredInstructionSet == null) {
6136                    requiredInstructionSet = instructionSet;
6137                    requirer = ps;
6138                }
6139            }
6140        }
6141
6142        if (requiredInstructionSet != null) {
6143            String adjustedAbi;
6144            if (requirer != null) {
6145                // requirer != null implies that either scannedPackage was null or that scannedPackage
6146                // did not require an ABI, in which case we have to adjust scannedPackage to match
6147                // the ABI of the set (which is the same as requirer's ABI)
6148                adjustedAbi = requirer.primaryCpuAbiString;
6149                if (scannedPackage != null) {
6150                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6151                }
6152            } else {
6153                // requirer == null implies that we're updating all ABIs in the set to
6154                // match scannedPackage.
6155                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6156            }
6157
6158            for (PackageSetting ps : packagesForUser) {
6159                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6160                    if (ps.primaryCpuAbiString != null) {
6161                        continue;
6162                    }
6163
6164                    ps.primaryCpuAbiString = adjustedAbi;
6165                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6166                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6167                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6168
6169                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6170                                deferDexOpt, true) == DEX_OPT_FAILED) {
6171                            ps.primaryCpuAbiString = null;
6172                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6173                            return;
6174                        } else {
6175                            mInstaller.rmdex(ps.codePathString,
6176                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6177                        }
6178                    }
6179                }
6180            }
6181        }
6182    }
6183
6184    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6185        synchronized (mPackages) {
6186            mResolverReplaced = true;
6187            // Set up information for custom user intent resolution activity.
6188            mResolveActivity.applicationInfo = pkg.applicationInfo;
6189            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6190            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6191            mResolveActivity.processName = null;
6192            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6193            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6194                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6195            mResolveActivity.theme = 0;
6196            mResolveActivity.exported = true;
6197            mResolveActivity.enabled = true;
6198            mResolveInfo.activityInfo = mResolveActivity;
6199            mResolveInfo.priority = 0;
6200            mResolveInfo.preferredOrder = 0;
6201            mResolveInfo.match = 0;
6202            mResolveComponentName = mCustomResolverComponentName;
6203            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6204                    mResolveComponentName);
6205        }
6206    }
6207
6208    private static String calculateBundledApkRoot(final String codePathString) {
6209        final File codePath = new File(codePathString);
6210        final File codeRoot;
6211        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6212            codeRoot = Environment.getRootDirectory();
6213        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6214            codeRoot = Environment.getOemDirectory();
6215        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6216            codeRoot = Environment.getVendorDirectory();
6217        } else {
6218            // Unrecognized code path; take its top real segment as the apk root:
6219            // e.g. /something/app/blah.apk => /something
6220            try {
6221                File f = codePath.getCanonicalFile();
6222                File parent = f.getParentFile();    // non-null because codePath is a file
6223                File tmp;
6224                while ((tmp = parent.getParentFile()) != null) {
6225                    f = parent;
6226                    parent = tmp;
6227                }
6228                codeRoot = f;
6229                Slog.w(TAG, "Unrecognized code path "
6230                        + codePath + " - using " + codeRoot);
6231            } catch (IOException e) {
6232                // Can't canonicalize the code path -- shenanigans?
6233                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6234                return Environment.getRootDirectory().getPath();
6235            }
6236        }
6237        return codeRoot.getPath();
6238    }
6239
6240    /**
6241     * Derive and set the location of native libraries for the given package,
6242     * which varies depending on where and how the package was installed.
6243     */
6244    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6245        final ApplicationInfo info = pkg.applicationInfo;
6246        final String codePath = pkg.codePath;
6247        final File codeFile = new File(codePath);
6248        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6249        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6250
6251        info.nativeLibraryRootDir = null;
6252        info.nativeLibraryRootRequiresIsa = false;
6253        info.nativeLibraryDir = null;
6254        info.secondaryNativeLibraryDir = null;
6255
6256        if (isApkFile(codeFile)) {
6257            // Monolithic install
6258            if (bundledApp) {
6259                // If "/system/lib64/apkname" exists, assume that is the per-package
6260                // native library directory to use; otherwise use "/system/lib/apkname".
6261                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6262                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6263                        getPrimaryInstructionSet(info));
6264
6265                // This is a bundled system app so choose the path based on the ABI.
6266                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6267                // is just the default path.
6268                final String apkName = deriveCodePathName(codePath);
6269                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6270                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6271                        apkName).getAbsolutePath();
6272
6273                if (info.secondaryCpuAbi != null) {
6274                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6275                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6276                            secondaryLibDir, apkName).getAbsolutePath();
6277                }
6278            } else if (asecApp) {
6279                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6280                        .getAbsolutePath();
6281            } else {
6282                final String apkName = deriveCodePathName(codePath);
6283                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6284                        .getAbsolutePath();
6285            }
6286
6287            info.nativeLibraryRootRequiresIsa = false;
6288            info.nativeLibraryDir = info.nativeLibraryRootDir;
6289        } else {
6290            // Cluster install
6291            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6292            info.nativeLibraryRootRequiresIsa = true;
6293
6294            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6295                    getPrimaryInstructionSet(info)).getAbsolutePath();
6296
6297            if (info.secondaryCpuAbi != null) {
6298                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6299                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6300            }
6301        }
6302    }
6303
6304    /**
6305     * Calculate the abis and roots for a bundled app. These can uniquely
6306     * be determined from the contents of the system partition, i.e whether
6307     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6308     * of this information, and instead assume that the system was built
6309     * sensibly.
6310     */
6311    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6312                                           PackageSetting pkgSetting) {
6313        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6314
6315        // If "/system/lib64/apkname" exists, assume that is the per-package
6316        // native library directory to use; otherwise use "/system/lib/apkname".
6317        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6318        setBundledAppAbi(pkg, apkRoot, apkName);
6319        // pkgSetting might be null during rescan following uninstall of updates
6320        // to a bundled app, so accommodate that possibility.  The settings in
6321        // that case will be established later from the parsed package.
6322        //
6323        // If the settings aren't null, sync them up with what we've just derived.
6324        // note that apkRoot isn't stored in the package settings.
6325        if (pkgSetting != null) {
6326            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6327            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6328        }
6329    }
6330
6331    /**
6332     * Deduces the ABI of a bundled app and sets the relevant fields on the
6333     * parsed pkg object.
6334     *
6335     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6336     *        under which system libraries are installed.
6337     * @param apkName the name of the installed package.
6338     */
6339    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6340        final File codeFile = new File(pkg.codePath);
6341
6342        final boolean has64BitLibs;
6343        final boolean has32BitLibs;
6344        if (isApkFile(codeFile)) {
6345            // Monolithic install
6346            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6347            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6348        } else {
6349            // Cluster install
6350            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6351            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6352                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6353                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6354                has64BitLibs = (new File(rootDir, isa)).exists();
6355            } else {
6356                has64BitLibs = false;
6357            }
6358            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6359                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6360                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6361                has32BitLibs = (new File(rootDir, isa)).exists();
6362            } else {
6363                has32BitLibs = false;
6364            }
6365        }
6366
6367        if (has64BitLibs && !has32BitLibs) {
6368            // The package has 64 bit libs, but not 32 bit libs. Its primary
6369            // ABI should be 64 bit. We can safely assume here that the bundled
6370            // native libraries correspond to the most preferred ABI in the list.
6371
6372            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6373            pkg.applicationInfo.secondaryCpuAbi = null;
6374        } else if (has32BitLibs && !has64BitLibs) {
6375            // The package has 32 bit libs but not 64 bit libs. Its primary
6376            // ABI should be 32 bit.
6377
6378            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6379            pkg.applicationInfo.secondaryCpuAbi = null;
6380        } else if (has32BitLibs && has64BitLibs) {
6381            // The application has both 64 and 32 bit bundled libraries. We check
6382            // here that the app declares multiArch support, and warn if it doesn't.
6383            //
6384            // We will be lenient here and record both ABIs. The primary will be the
6385            // ABI that's higher on the list, i.e, a device that's configured to prefer
6386            // 64 bit apps will see a 64 bit primary ABI,
6387
6388            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6389                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6390            }
6391
6392            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6393                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6394                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6395            } else {
6396                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6397                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6398            }
6399        } else {
6400            pkg.applicationInfo.primaryCpuAbi = null;
6401            pkg.applicationInfo.secondaryCpuAbi = null;
6402        }
6403    }
6404
6405    private void killApplication(String pkgName, int appId, String reason) {
6406        // Request the ActivityManager to kill the process(only for existing packages)
6407        // so that we do not end up in a confused state while the user is still using the older
6408        // version of the application while the new one gets installed.
6409        IActivityManager am = ActivityManagerNative.getDefault();
6410        if (am != null) {
6411            try {
6412                am.killApplicationWithAppId(pkgName, appId, reason);
6413            } catch (RemoteException e) {
6414            }
6415        }
6416    }
6417
6418    void removePackageLI(PackageSetting ps, boolean chatty) {
6419        if (DEBUG_INSTALL) {
6420            if (chatty)
6421                Log.d(TAG, "Removing package " + ps.name);
6422        }
6423
6424        // writer
6425        synchronized (mPackages) {
6426            mPackages.remove(ps.name);
6427            final PackageParser.Package pkg = ps.pkg;
6428            if (pkg != null) {
6429                cleanPackageDataStructuresLILPw(pkg, chatty);
6430            }
6431        }
6432    }
6433
6434    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6435        if (DEBUG_INSTALL) {
6436            if (chatty)
6437                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6438        }
6439
6440        // writer
6441        synchronized (mPackages) {
6442            mPackages.remove(pkg.applicationInfo.packageName);
6443            cleanPackageDataStructuresLILPw(pkg, chatty);
6444        }
6445    }
6446
6447    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6448        int N = pkg.providers.size();
6449        StringBuilder r = null;
6450        int i;
6451        for (i=0; i<N; i++) {
6452            PackageParser.Provider p = pkg.providers.get(i);
6453            mProviders.removeProvider(p);
6454            if (p.info.authority == null) {
6455
6456                /* There was another ContentProvider with this authority when
6457                 * this app was installed so this authority is null,
6458                 * Ignore it as we don't have to unregister the provider.
6459                 */
6460                continue;
6461            }
6462            String names[] = p.info.authority.split(";");
6463            for (int j = 0; j < names.length; j++) {
6464                if (mProvidersByAuthority.get(names[j]) == p) {
6465                    mProvidersByAuthority.remove(names[j]);
6466                    if (DEBUG_REMOVE) {
6467                        if (chatty)
6468                            Log.d(TAG, "Unregistered content provider: " + names[j]
6469                                    + ", className = " + p.info.name + ", isSyncable = "
6470                                    + p.info.isSyncable);
6471                    }
6472                }
6473            }
6474            if (DEBUG_REMOVE && chatty) {
6475                if (r == null) {
6476                    r = new StringBuilder(256);
6477                } else {
6478                    r.append(' ');
6479                }
6480                r.append(p.info.name);
6481            }
6482        }
6483        if (r != null) {
6484            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6485        }
6486
6487        N = pkg.services.size();
6488        r = null;
6489        for (i=0; i<N; i++) {
6490            PackageParser.Service s = pkg.services.get(i);
6491            mServices.removeService(s);
6492            if (chatty) {
6493                if (r == null) {
6494                    r = new StringBuilder(256);
6495                } else {
6496                    r.append(' ');
6497                }
6498                r.append(s.info.name);
6499            }
6500        }
6501        if (r != null) {
6502            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6503        }
6504
6505        N = pkg.receivers.size();
6506        r = null;
6507        for (i=0; i<N; i++) {
6508            PackageParser.Activity a = pkg.receivers.get(i);
6509            mReceivers.removeActivity(a, "receiver");
6510            if (DEBUG_REMOVE && chatty) {
6511                if (r == null) {
6512                    r = new StringBuilder(256);
6513                } else {
6514                    r.append(' ');
6515                }
6516                r.append(a.info.name);
6517            }
6518        }
6519        if (r != null) {
6520            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6521        }
6522
6523        N = pkg.activities.size();
6524        r = null;
6525        for (i=0; i<N; i++) {
6526            PackageParser.Activity a = pkg.activities.get(i);
6527            mActivities.removeActivity(a, "activity");
6528            if (DEBUG_REMOVE && chatty) {
6529                if (r == null) {
6530                    r = new StringBuilder(256);
6531                } else {
6532                    r.append(' ');
6533                }
6534                r.append(a.info.name);
6535            }
6536        }
6537        if (r != null) {
6538            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6539        }
6540
6541        N = pkg.permissions.size();
6542        r = null;
6543        for (i=0; i<N; i++) {
6544            PackageParser.Permission p = pkg.permissions.get(i);
6545            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6546            if (bp == null) {
6547                bp = mSettings.mPermissionTrees.get(p.info.name);
6548            }
6549            if (bp != null && bp.perm == p) {
6550                bp.perm = null;
6551                if (DEBUG_REMOVE && chatty) {
6552                    if (r == null) {
6553                        r = new StringBuilder(256);
6554                    } else {
6555                        r.append(' ');
6556                    }
6557                    r.append(p.info.name);
6558                }
6559            }
6560            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6561                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6562                if (appOpPerms != null) {
6563                    appOpPerms.remove(pkg.packageName);
6564                }
6565            }
6566        }
6567        if (r != null) {
6568            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6569        }
6570
6571        N = pkg.requestedPermissions.size();
6572        r = null;
6573        for (i=0; i<N; i++) {
6574            String perm = pkg.requestedPermissions.get(i);
6575            BasePermission bp = mSettings.mPermissions.get(perm);
6576            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6577                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6578                if (appOpPerms != null) {
6579                    appOpPerms.remove(pkg.packageName);
6580                    if (appOpPerms.isEmpty()) {
6581                        mAppOpPermissionPackages.remove(perm);
6582                    }
6583                }
6584            }
6585        }
6586        if (r != null) {
6587            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6588        }
6589
6590        N = pkg.instrumentation.size();
6591        r = null;
6592        for (i=0; i<N; i++) {
6593            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6594            mInstrumentation.remove(a.getComponentName());
6595            if (DEBUG_REMOVE && chatty) {
6596                if (r == null) {
6597                    r = new StringBuilder(256);
6598                } else {
6599                    r.append(' ');
6600                }
6601                r.append(a.info.name);
6602            }
6603        }
6604        if (r != null) {
6605            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6606        }
6607
6608        r = null;
6609        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6610            // Only system apps can hold shared libraries.
6611            if (pkg.libraryNames != null) {
6612                for (i=0; i<pkg.libraryNames.size(); i++) {
6613                    String name = pkg.libraryNames.get(i);
6614                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6615                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6616                        mSharedLibraries.remove(name);
6617                        if (DEBUG_REMOVE && chatty) {
6618                            if (r == null) {
6619                                r = new StringBuilder(256);
6620                            } else {
6621                                r.append(' ');
6622                            }
6623                            r.append(name);
6624                        }
6625                    }
6626                }
6627            }
6628        }
6629        if (r != null) {
6630            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6631        }
6632    }
6633
6634    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6635        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6636            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6637                return true;
6638            }
6639        }
6640        return false;
6641    }
6642
6643    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6644    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6645    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6646
6647    private void updatePermissionsLPw(String changingPkg,
6648            PackageParser.Package pkgInfo, int flags) {
6649        // Make sure there are no dangling permission trees.
6650        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6651        while (it.hasNext()) {
6652            final BasePermission bp = it.next();
6653            if (bp.packageSetting == null) {
6654                // We may not yet have parsed the package, so just see if
6655                // we still know about its settings.
6656                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6657            }
6658            if (bp.packageSetting == null) {
6659                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6660                        + " from package " + bp.sourcePackage);
6661                it.remove();
6662            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6663                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6664                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6665                            + " from package " + bp.sourcePackage);
6666                    flags |= UPDATE_PERMISSIONS_ALL;
6667                    it.remove();
6668                }
6669            }
6670        }
6671
6672        // Make sure all dynamic permissions have been assigned to a package,
6673        // and make sure there are no dangling permissions.
6674        it = mSettings.mPermissions.values().iterator();
6675        while (it.hasNext()) {
6676            final BasePermission bp = it.next();
6677            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6678                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6679                        + bp.name + " pkg=" + bp.sourcePackage
6680                        + " info=" + bp.pendingInfo);
6681                if (bp.packageSetting == null && bp.pendingInfo != null) {
6682                    final BasePermission tree = findPermissionTreeLP(bp.name);
6683                    if (tree != null && tree.perm != null) {
6684                        bp.packageSetting = tree.packageSetting;
6685                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6686                                new PermissionInfo(bp.pendingInfo));
6687                        bp.perm.info.packageName = tree.perm.info.packageName;
6688                        bp.perm.info.name = bp.name;
6689                        bp.uid = tree.uid;
6690                    }
6691                }
6692            }
6693            if (bp.packageSetting == null) {
6694                // We may not yet have parsed the package, so just see if
6695                // we still know about its settings.
6696                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6697            }
6698            if (bp.packageSetting == null) {
6699                Slog.w(TAG, "Removing dangling permission: " + bp.name
6700                        + " from package " + bp.sourcePackage);
6701                it.remove();
6702            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6703                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6704                    Slog.i(TAG, "Removing old permission: " + bp.name
6705                            + " from package " + bp.sourcePackage);
6706                    flags |= UPDATE_PERMISSIONS_ALL;
6707                    it.remove();
6708                }
6709            }
6710        }
6711
6712        // Now update the permissions for all packages, in particular
6713        // replace the granted permissions of the system packages.
6714        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6715            for (PackageParser.Package pkg : mPackages.values()) {
6716                if (pkg != pkgInfo) {
6717                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6718                            changingPkg);
6719                }
6720            }
6721        }
6722
6723        if (pkgInfo != null) {
6724            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6725        }
6726    }
6727
6728    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6729            String packageOfInterest) {
6730        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6731        if (ps == null) {
6732            return;
6733        }
6734        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6735        HashSet<String> origPermissions = gp.grantedPermissions;
6736        boolean changedPermission = false;
6737
6738        if (replace) {
6739            ps.permissionsFixed = false;
6740            if (gp == ps) {
6741                origPermissions = new HashSet<String>(gp.grantedPermissions);
6742                gp.grantedPermissions.clear();
6743                gp.gids = mGlobalGids;
6744            }
6745        }
6746
6747        if (gp.gids == null) {
6748            gp.gids = mGlobalGids;
6749        }
6750
6751        final int N = pkg.requestedPermissions.size();
6752        for (int i=0; i<N; i++) {
6753            final String name = pkg.requestedPermissions.get(i);
6754            final boolean required = pkg.requestedPermissionsRequired.get(i);
6755            final BasePermission bp = mSettings.mPermissions.get(name);
6756            if (DEBUG_INSTALL) {
6757                if (gp != ps) {
6758                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6759                }
6760            }
6761
6762            if (bp == null || bp.packageSetting == null) {
6763                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6764                    Slog.w(TAG, "Unknown permission " + name
6765                            + " in package " + pkg.packageName);
6766                }
6767                continue;
6768            }
6769
6770            final String perm = bp.name;
6771            boolean allowed;
6772            boolean allowedSig = false;
6773            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6774                // Keep track of app op permissions.
6775                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6776                if (pkgs == null) {
6777                    pkgs = new ArraySet<>();
6778                    mAppOpPermissionPackages.put(bp.name, pkgs);
6779                }
6780                pkgs.add(pkg.packageName);
6781            }
6782            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6783            if (level == PermissionInfo.PROTECTION_NORMAL
6784                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6785                // We grant a normal or dangerous permission if any of the following
6786                // are true:
6787                // 1) The permission is required
6788                // 2) The permission is optional, but was granted in the past
6789                // 3) The permission is optional, but was requested by an
6790                //    app in /system (not /data)
6791                //
6792                // Otherwise, reject the permission.
6793                allowed = (required || origPermissions.contains(perm)
6794                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6795            } else if (bp.packageSetting == null) {
6796                // This permission is invalid; skip it.
6797                allowed = false;
6798            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6799                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6800                if (allowed) {
6801                    allowedSig = true;
6802                }
6803            } else {
6804                allowed = false;
6805            }
6806            if (DEBUG_INSTALL) {
6807                if (gp != ps) {
6808                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6809                }
6810            }
6811            if (allowed) {
6812                if (!isSystemApp(ps) && ps.permissionsFixed) {
6813                    // If this is an existing, non-system package, then
6814                    // we can't add any new permissions to it.
6815                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6816                        // Except...  if this is a permission that was added
6817                        // to the platform (note: need to only do this when
6818                        // updating the platform).
6819                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6820                    }
6821                }
6822                if (allowed) {
6823                    if (!gp.grantedPermissions.contains(perm)) {
6824                        changedPermission = true;
6825                        gp.grantedPermissions.add(perm);
6826                        gp.gids = appendInts(gp.gids, bp.gids);
6827                    } else if (!ps.haveGids) {
6828                        gp.gids = appendInts(gp.gids, bp.gids);
6829                    }
6830                } else {
6831                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6832                        Slog.w(TAG, "Not granting permission " + perm
6833                                + " to package " + pkg.packageName
6834                                + " because it was previously installed without");
6835                    }
6836                }
6837            } else {
6838                if (gp.grantedPermissions.remove(perm)) {
6839                    changedPermission = true;
6840                    gp.gids = removeInts(gp.gids, bp.gids);
6841                    Slog.i(TAG, "Un-granting permission " + perm
6842                            + " from package " + pkg.packageName
6843                            + " (protectionLevel=" + bp.protectionLevel
6844                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6845                            + ")");
6846                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6847                    // Don't print warning for app op permissions, since it is fine for them
6848                    // not to be granted, there is a UI for the user to decide.
6849                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6850                        Slog.w(TAG, "Not granting permission " + perm
6851                                + " to package " + pkg.packageName
6852                                + " (protectionLevel=" + bp.protectionLevel
6853                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6854                                + ")");
6855                    }
6856                }
6857            }
6858        }
6859
6860        if ((changedPermission || replace) && !ps.permissionsFixed &&
6861                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6862            // This is the first that we have heard about this package, so the
6863            // permissions we have now selected are fixed until explicitly
6864            // changed.
6865            ps.permissionsFixed = true;
6866        }
6867        ps.haveGids = true;
6868    }
6869
6870    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6871        boolean allowed = false;
6872        final int NP = PackageParser.NEW_PERMISSIONS.length;
6873        for (int ip=0; ip<NP; ip++) {
6874            final PackageParser.NewPermissionInfo npi
6875                    = PackageParser.NEW_PERMISSIONS[ip];
6876            if (npi.name.equals(perm)
6877                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6878                allowed = true;
6879                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6880                        + pkg.packageName);
6881                break;
6882            }
6883        }
6884        return allowed;
6885    }
6886
6887    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6888                                          BasePermission bp, HashSet<String> origPermissions) {
6889        boolean allowed;
6890        allowed = (compareSignatures(
6891                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6892                        == PackageManager.SIGNATURE_MATCH)
6893                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6894                        == PackageManager.SIGNATURE_MATCH);
6895        if (!allowed && (bp.protectionLevel
6896                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6897            if (isSystemApp(pkg)) {
6898                // For updated system applications, a system permission
6899                // is granted only if it had been defined by the original application.
6900                if (isUpdatedSystemApp(pkg)) {
6901                    final PackageSetting sysPs = mSettings
6902                            .getDisabledSystemPkgLPr(pkg.packageName);
6903                    final GrantedPermissions origGp = sysPs.sharedUser != null
6904                            ? sysPs.sharedUser : sysPs;
6905
6906                    if (origGp.grantedPermissions.contains(perm)) {
6907                        // If the original was granted this permission, we take
6908                        // that grant decision as read and propagate it to the
6909                        // update.
6910                        allowed = true;
6911                    } else {
6912                        // The system apk may have been updated with an older
6913                        // version of the one on the data partition, but which
6914                        // granted a new system permission that it didn't have
6915                        // before.  In this case we do want to allow the app to
6916                        // now get the new permission if the ancestral apk is
6917                        // privileged to get it.
6918                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6919                            for (int j=0;
6920                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6921                                if (perm.equals(
6922                                        sysPs.pkg.requestedPermissions.get(j))) {
6923                                    allowed = true;
6924                                    break;
6925                                }
6926                            }
6927                        }
6928                    }
6929                } else {
6930                    allowed = isPrivilegedApp(pkg);
6931                }
6932            }
6933        }
6934        if (!allowed && (bp.protectionLevel
6935                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6936            // For development permissions, a development permission
6937            // is granted only if it was already granted.
6938            allowed = origPermissions.contains(perm);
6939        }
6940        return allowed;
6941    }
6942
6943    final class ActivityIntentResolver
6944            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6945        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6946                boolean defaultOnly, int userId) {
6947            if (!sUserManager.exists(userId)) return null;
6948            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6949            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6950        }
6951
6952        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6953                int userId) {
6954            if (!sUserManager.exists(userId)) return null;
6955            mFlags = flags;
6956            return super.queryIntent(intent, resolvedType,
6957                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6958        }
6959
6960        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6961                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6962            if (!sUserManager.exists(userId)) return null;
6963            if (packageActivities == null) {
6964                return null;
6965            }
6966            mFlags = flags;
6967            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6968            final int N = packageActivities.size();
6969            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6970                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6971
6972            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6973            for (int i = 0; i < N; ++i) {
6974                intentFilters = packageActivities.get(i).intents;
6975                if (intentFilters != null && intentFilters.size() > 0) {
6976                    PackageParser.ActivityIntentInfo[] array =
6977                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6978                    intentFilters.toArray(array);
6979                    listCut.add(array);
6980                }
6981            }
6982            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6983        }
6984
6985        public final void addActivity(PackageParser.Activity a, String type) {
6986            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6987            mActivities.put(a.getComponentName(), a);
6988            if (DEBUG_SHOW_INFO)
6989                Log.v(
6990                TAG, "  " + type + " " +
6991                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6992            if (DEBUG_SHOW_INFO)
6993                Log.v(TAG, "    Class=" + a.info.name);
6994            final int NI = a.intents.size();
6995            for (int j=0; j<NI; j++) {
6996                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6997                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6998                    intent.setPriority(0);
6999                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7000                            + a.className + " with priority > 0, forcing to 0");
7001                }
7002                if (DEBUG_SHOW_INFO) {
7003                    Log.v(TAG, "    IntentFilter:");
7004                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7005                }
7006                if (!intent.debugCheck()) {
7007                    Log.w(TAG, "==> For Activity " + a.info.name);
7008                }
7009                addFilter(intent);
7010            }
7011        }
7012
7013        public final void removeActivity(PackageParser.Activity a, String type) {
7014            mActivities.remove(a.getComponentName());
7015            if (DEBUG_SHOW_INFO) {
7016                Log.v(TAG, "  " + type + " "
7017                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7018                                : a.info.name) + ":");
7019                Log.v(TAG, "    Class=" + a.info.name);
7020            }
7021            final int NI = a.intents.size();
7022            for (int j=0; j<NI; j++) {
7023                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7024                if (DEBUG_SHOW_INFO) {
7025                    Log.v(TAG, "    IntentFilter:");
7026                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7027                }
7028                removeFilter(intent);
7029            }
7030        }
7031
7032        @Override
7033        protected boolean allowFilterResult(
7034                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7035            ActivityInfo filterAi = filter.activity.info;
7036            for (int i=dest.size()-1; i>=0; i--) {
7037                ActivityInfo destAi = dest.get(i).activityInfo;
7038                if (destAi.name == filterAi.name
7039                        && destAi.packageName == filterAi.packageName) {
7040                    return false;
7041                }
7042            }
7043            return true;
7044        }
7045
7046        @Override
7047        protected ActivityIntentInfo[] newArray(int size) {
7048            return new ActivityIntentInfo[size];
7049        }
7050
7051        @Override
7052        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7053            if (!sUserManager.exists(userId)) return true;
7054            PackageParser.Package p = filter.activity.owner;
7055            if (p != null) {
7056                PackageSetting ps = (PackageSetting)p.mExtras;
7057                if (ps != null) {
7058                    // System apps are never considered stopped for purposes of
7059                    // filtering, because there may be no way for the user to
7060                    // actually re-launch them.
7061                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7062                            && ps.getStopped(userId);
7063                }
7064            }
7065            return false;
7066        }
7067
7068        @Override
7069        protected boolean isPackageForFilter(String packageName,
7070                PackageParser.ActivityIntentInfo info) {
7071            return packageName.equals(info.activity.owner.packageName);
7072        }
7073
7074        @Override
7075        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7076                int match, int userId) {
7077            if (!sUserManager.exists(userId)) return null;
7078            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7079                return null;
7080            }
7081            final PackageParser.Activity activity = info.activity;
7082            if (mSafeMode && (activity.info.applicationInfo.flags
7083                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7084                return null;
7085            }
7086            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7087            if (ps == null) {
7088                return null;
7089            }
7090            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7091                    ps.readUserState(userId), userId);
7092            if (ai == null) {
7093                return null;
7094            }
7095            final ResolveInfo res = new ResolveInfo();
7096            res.activityInfo = ai;
7097            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7098                res.filter = info;
7099            }
7100            res.priority = info.getPriority();
7101            res.preferredOrder = activity.owner.mPreferredOrder;
7102            //System.out.println("Result: " + res.activityInfo.className +
7103            //                   " = " + res.priority);
7104            res.match = match;
7105            res.isDefault = info.hasDefault;
7106            res.labelRes = info.labelRes;
7107            res.nonLocalizedLabel = info.nonLocalizedLabel;
7108            if (userNeedsBadging(userId)) {
7109                res.noResourceId = true;
7110            } else {
7111                res.icon = info.icon;
7112            }
7113            res.system = isSystemApp(res.activityInfo.applicationInfo);
7114            return res;
7115        }
7116
7117        @Override
7118        protected void sortResults(List<ResolveInfo> results) {
7119            Collections.sort(results, mResolvePrioritySorter);
7120        }
7121
7122        @Override
7123        protected void dumpFilter(PrintWriter out, String prefix,
7124                PackageParser.ActivityIntentInfo filter) {
7125            out.print(prefix); out.print(
7126                    Integer.toHexString(System.identityHashCode(filter.activity)));
7127                    out.print(' ');
7128                    filter.activity.printComponentShortName(out);
7129                    out.print(" filter ");
7130                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7131        }
7132
7133//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7134//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7135//            final List<ResolveInfo> retList = Lists.newArrayList();
7136//            while (i.hasNext()) {
7137//                final ResolveInfo resolveInfo = i.next();
7138//                if (isEnabledLP(resolveInfo.activityInfo)) {
7139//                    retList.add(resolveInfo);
7140//                }
7141//            }
7142//            return retList;
7143//        }
7144
7145        // Keys are String (activity class name), values are Activity.
7146        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7147                = new HashMap<ComponentName, PackageParser.Activity>();
7148        private int mFlags;
7149    }
7150
7151    private final class ServiceIntentResolver
7152            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7153        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7154                boolean defaultOnly, int userId) {
7155            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7156            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7157        }
7158
7159        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7160                int userId) {
7161            if (!sUserManager.exists(userId)) return null;
7162            mFlags = flags;
7163            return super.queryIntent(intent, resolvedType,
7164                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7165        }
7166
7167        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7168                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7169            if (!sUserManager.exists(userId)) return null;
7170            if (packageServices == null) {
7171                return null;
7172            }
7173            mFlags = flags;
7174            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7175            final int N = packageServices.size();
7176            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7177                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7178
7179            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7180            for (int i = 0; i < N; ++i) {
7181                intentFilters = packageServices.get(i).intents;
7182                if (intentFilters != null && intentFilters.size() > 0) {
7183                    PackageParser.ServiceIntentInfo[] array =
7184                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7185                    intentFilters.toArray(array);
7186                    listCut.add(array);
7187                }
7188            }
7189            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7190        }
7191
7192        public final void addService(PackageParser.Service s) {
7193            mServices.put(s.getComponentName(), s);
7194            if (DEBUG_SHOW_INFO) {
7195                Log.v(TAG, "  "
7196                        + (s.info.nonLocalizedLabel != null
7197                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7198                Log.v(TAG, "    Class=" + s.info.name);
7199            }
7200            final int NI = s.intents.size();
7201            int j;
7202            for (j=0; j<NI; j++) {
7203                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7204                if (DEBUG_SHOW_INFO) {
7205                    Log.v(TAG, "    IntentFilter:");
7206                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7207                }
7208                if (!intent.debugCheck()) {
7209                    Log.w(TAG, "==> For Service " + s.info.name);
7210                }
7211                addFilter(intent);
7212            }
7213        }
7214
7215        public final void removeService(PackageParser.Service s) {
7216            mServices.remove(s.getComponentName());
7217            if (DEBUG_SHOW_INFO) {
7218                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7219                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7220                Log.v(TAG, "    Class=" + s.info.name);
7221            }
7222            final int NI = s.intents.size();
7223            int j;
7224            for (j=0; j<NI; j++) {
7225                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7226                if (DEBUG_SHOW_INFO) {
7227                    Log.v(TAG, "    IntentFilter:");
7228                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7229                }
7230                removeFilter(intent);
7231            }
7232        }
7233
7234        @Override
7235        protected boolean allowFilterResult(
7236                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7237            ServiceInfo filterSi = filter.service.info;
7238            for (int i=dest.size()-1; i>=0; i--) {
7239                ServiceInfo destAi = dest.get(i).serviceInfo;
7240                if (destAi.name == filterSi.name
7241                        && destAi.packageName == filterSi.packageName) {
7242                    return false;
7243                }
7244            }
7245            return true;
7246        }
7247
7248        @Override
7249        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7250            return new PackageParser.ServiceIntentInfo[size];
7251        }
7252
7253        @Override
7254        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7255            if (!sUserManager.exists(userId)) return true;
7256            PackageParser.Package p = filter.service.owner;
7257            if (p != null) {
7258                PackageSetting ps = (PackageSetting)p.mExtras;
7259                if (ps != null) {
7260                    // System apps are never considered stopped for purposes of
7261                    // filtering, because there may be no way for the user to
7262                    // actually re-launch them.
7263                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7264                            && ps.getStopped(userId);
7265                }
7266            }
7267            return false;
7268        }
7269
7270        @Override
7271        protected boolean isPackageForFilter(String packageName,
7272                PackageParser.ServiceIntentInfo info) {
7273            return packageName.equals(info.service.owner.packageName);
7274        }
7275
7276        @Override
7277        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7278                int match, int userId) {
7279            if (!sUserManager.exists(userId)) return null;
7280            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7281            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7282                return null;
7283            }
7284            final PackageParser.Service service = info.service;
7285            if (mSafeMode && (service.info.applicationInfo.flags
7286                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7287                return null;
7288            }
7289            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7290            if (ps == null) {
7291                return null;
7292            }
7293            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7294                    ps.readUserState(userId), userId);
7295            if (si == null) {
7296                return null;
7297            }
7298            final ResolveInfo res = new ResolveInfo();
7299            res.serviceInfo = si;
7300            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7301                res.filter = filter;
7302            }
7303            res.priority = info.getPriority();
7304            res.preferredOrder = service.owner.mPreferredOrder;
7305            //System.out.println("Result: " + res.activityInfo.className +
7306            //                   " = " + res.priority);
7307            res.match = match;
7308            res.isDefault = info.hasDefault;
7309            res.labelRes = info.labelRes;
7310            res.nonLocalizedLabel = info.nonLocalizedLabel;
7311            res.icon = info.icon;
7312            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7313            return res;
7314        }
7315
7316        @Override
7317        protected void sortResults(List<ResolveInfo> results) {
7318            Collections.sort(results, mResolvePrioritySorter);
7319        }
7320
7321        @Override
7322        protected void dumpFilter(PrintWriter out, String prefix,
7323                PackageParser.ServiceIntentInfo filter) {
7324            out.print(prefix); out.print(
7325                    Integer.toHexString(System.identityHashCode(filter.service)));
7326                    out.print(' ');
7327                    filter.service.printComponentShortName(out);
7328                    out.print(" filter ");
7329                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7330        }
7331
7332//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7333//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7334//            final List<ResolveInfo> retList = Lists.newArrayList();
7335//            while (i.hasNext()) {
7336//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7337//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7338//                    retList.add(resolveInfo);
7339//                }
7340//            }
7341//            return retList;
7342//        }
7343
7344        // Keys are String (activity class name), values are Activity.
7345        private final HashMap<ComponentName, PackageParser.Service> mServices
7346                = new HashMap<ComponentName, PackageParser.Service>();
7347        private int mFlags;
7348    };
7349
7350    private final class ProviderIntentResolver
7351            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7352        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7353                boolean defaultOnly, int userId) {
7354            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7355            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7356        }
7357
7358        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7359                int userId) {
7360            if (!sUserManager.exists(userId))
7361                return null;
7362            mFlags = flags;
7363            return super.queryIntent(intent, resolvedType,
7364                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7365        }
7366
7367        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7368                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7369            if (!sUserManager.exists(userId))
7370                return null;
7371            if (packageProviders == null) {
7372                return null;
7373            }
7374            mFlags = flags;
7375            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7376            final int N = packageProviders.size();
7377            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7378                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7379
7380            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7381            for (int i = 0; i < N; ++i) {
7382                intentFilters = packageProviders.get(i).intents;
7383                if (intentFilters != null && intentFilters.size() > 0) {
7384                    PackageParser.ProviderIntentInfo[] array =
7385                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7386                    intentFilters.toArray(array);
7387                    listCut.add(array);
7388                }
7389            }
7390            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7391        }
7392
7393        public final void addProvider(PackageParser.Provider p) {
7394            if (mProviders.containsKey(p.getComponentName())) {
7395                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7396                return;
7397            }
7398
7399            mProviders.put(p.getComponentName(), p);
7400            if (DEBUG_SHOW_INFO) {
7401                Log.v(TAG, "  "
7402                        + (p.info.nonLocalizedLabel != null
7403                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7404                Log.v(TAG, "    Class=" + p.info.name);
7405            }
7406            final int NI = p.intents.size();
7407            int j;
7408            for (j = 0; j < NI; j++) {
7409                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7410                if (DEBUG_SHOW_INFO) {
7411                    Log.v(TAG, "    IntentFilter:");
7412                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7413                }
7414                if (!intent.debugCheck()) {
7415                    Log.w(TAG, "==> For Provider " + p.info.name);
7416                }
7417                addFilter(intent);
7418            }
7419        }
7420
7421        public final void removeProvider(PackageParser.Provider p) {
7422            mProviders.remove(p.getComponentName());
7423            if (DEBUG_SHOW_INFO) {
7424                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7425                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7426                Log.v(TAG, "    Class=" + p.info.name);
7427            }
7428            final int NI = p.intents.size();
7429            int j;
7430            for (j = 0; j < NI; j++) {
7431                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7432                if (DEBUG_SHOW_INFO) {
7433                    Log.v(TAG, "    IntentFilter:");
7434                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7435                }
7436                removeFilter(intent);
7437            }
7438        }
7439
7440        @Override
7441        protected boolean allowFilterResult(
7442                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7443            ProviderInfo filterPi = filter.provider.info;
7444            for (int i = dest.size() - 1; i >= 0; i--) {
7445                ProviderInfo destPi = dest.get(i).providerInfo;
7446                if (destPi.name == filterPi.name
7447                        && destPi.packageName == filterPi.packageName) {
7448                    return false;
7449                }
7450            }
7451            return true;
7452        }
7453
7454        @Override
7455        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7456            return new PackageParser.ProviderIntentInfo[size];
7457        }
7458
7459        @Override
7460        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7461            if (!sUserManager.exists(userId))
7462                return true;
7463            PackageParser.Package p = filter.provider.owner;
7464            if (p != null) {
7465                PackageSetting ps = (PackageSetting) p.mExtras;
7466                if (ps != null) {
7467                    // System apps are never considered stopped for purposes of
7468                    // filtering, because there may be no way for the user to
7469                    // actually re-launch them.
7470                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7471                            && ps.getStopped(userId);
7472                }
7473            }
7474            return false;
7475        }
7476
7477        @Override
7478        protected boolean isPackageForFilter(String packageName,
7479                PackageParser.ProviderIntentInfo info) {
7480            return packageName.equals(info.provider.owner.packageName);
7481        }
7482
7483        @Override
7484        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7485                int match, int userId) {
7486            if (!sUserManager.exists(userId))
7487                return null;
7488            final PackageParser.ProviderIntentInfo info = filter;
7489            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7490                return null;
7491            }
7492            final PackageParser.Provider provider = info.provider;
7493            if (mSafeMode && (provider.info.applicationInfo.flags
7494                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7495                return null;
7496            }
7497            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7498            if (ps == null) {
7499                return null;
7500            }
7501            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7502                    ps.readUserState(userId), userId);
7503            if (pi == null) {
7504                return null;
7505            }
7506            final ResolveInfo res = new ResolveInfo();
7507            res.providerInfo = pi;
7508            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7509                res.filter = filter;
7510            }
7511            res.priority = info.getPriority();
7512            res.preferredOrder = provider.owner.mPreferredOrder;
7513            res.match = match;
7514            res.isDefault = info.hasDefault;
7515            res.labelRes = info.labelRes;
7516            res.nonLocalizedLabel = info.nonLocalizedLabel;
7517            res.icon = info.icon;
7518            res.system = isSystemApp(res.providerInfo.applicationInfo);
7519            return res;
7520        }
7521
7522        @Override
7523        protected void sortResults(List<ResolveInfo> results) {
7524            Collections.sort(results, mResolvePrioritySorter);
7525        }
7526
7527        @Override
7528        protected void dumpFilter(PrintWriter out, String prefix,
7529                PackageParser.ProviderIntentInfo filter) {
7530            out.print(prefix);
7531            out.print(
7532                    Integer.toHexString(System.identityHashCode(filter.provider)));
7533            out.print(' ');
7534            filter.provider.printComponentShortName(out);
7535            out.print(" filter ");
7536            out.println(Integer.toHexString(System.identityHashCode(filter)));
7537        }
7538
7539        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7540                = new HashMap<ComponentName, PackageParser.Provider>();
7541        private int mFlags;
7542    };
7543
7544    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7545            new Comparator<ResolveInfo>() {
7546        public int compare(ResolveInfo r1, ResolveInfo r2) {
7547            int v1 = r1.priority;
7548            int v2 = r2.priority;
7549            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7550            if (v1 != v2) {
7551                return (v1 > v2) ? -1 : 1;
7552            }
7553            v1 = r1.preferredOrder;
7554            v2 = r2.preferredOrder;
7555            if (v1 != v2) {
7556                return (v1 > v2) ? -1 : 1;
7557            }
7558            if (r1.isDefault != r2.isDefault) {
7559                return r1.isDefault ? -1 : 1;
7560            }
7561            v1 = r1.match;
7562            v2 = r2.match;
7563            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7564            if (v1 != v2) {
7565                return (v1 > v2) ? -1 : 1;
7566            }
7567            if (r1.system != r2.system) {
7568                return r1.system ? -1 : 1;
7569            }
7570            return 0;
7571        }
7572    };
7573
7574    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7575            new Comparator<ProviderInfo>() {
7576        public int compare(ProviderInfo p1, ProviderInfo p2) {
7577            final int v1 = p1.initOrder;
7578            final int v2 = p2.initOrder;
7579            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7580        }
7581    };
7582
7583    static final void sendPackageBroadcast(String action, String pkg,
7584            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7585            int[] userIds) {
7586        IActivityManager am = ActivityManagerNative.getDefault();
7587        if (am != null) {
7588            try {
7589                if (userIds == null) {
7590                    userIds = am.getRunningUserIds();
7591                }
7592                for (int id : userIds) {
7593                    final Intent intent = new Intent(action,
7594                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7595                    if (extras != null) {
7596                        intent.putExtras(extras);
7597                    }
7598                    if (targetPkg != null) {
7599                        intent.setPackage(targetPkg);
7600                    }
7601                    // Modify the UID when posting to other users
7602                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7603                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7604                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7605                        intent.putExtra(Intent.EXTRA_UID, uid);
7606                    }
7607                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7608                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7609                    if (DEBUG_BROADCASTS) {
7610                        RuntimeException here = new RuntimeException("here");
7611                        here.fillInStackTrace();
7612                        Slog.d(TAG, "Sending to user " + id + ": "
7613                                + intent.toShortString(false, true, false, false)
7614                                + " " + intent.getExtras(), here);
7615                    }
7616                    am.broadcastIntent(null, intent, null, finishedReceiver,
7617                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7618                            finishedReceiver != null, false, id);
7619                }
7620            } catch (RemoteException ex) {
7621            }
7622        }
7623    }
7624
7625    /**
7626     * Check if the external storage media is available. This is true if there
7627     * is a mounted external storage medium or if the external storage is
7628     * emulated.
7629     */
7630    private boolean isExternalMediaAvailable() {
7631        return mMediaMounted || Environment.isExternalStorageEmulated();
7632    }
7633
7634    @Override
7635    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7636        // writer
7637        synchronized (mPackages) {
7638            if (!isExternalMediaAvailable()) {
7639                // If the external storage is no longer mounted at this point,
7640                // the caller may not have been able to delete all of this
7641                // packages files and can not delete any more.  Bail.
7642                return null;
7643            }
7644            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7645            if (lastPackage != null) {
7646                pkgs.remove(lastPackage);
7647            }
7648            if (pkgs.size() > 0) {
7649                return pkgs.get(0);
7650            }
7651        }
7652        return null;
7653    }
7654
7655    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7656        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7657                userId, andCode ? 1 : 0, packageName);
7658        if (mSystemReady) {
7659            msg.sendToTarget();
7660        } else {
7661            if (mPostSystemReadyMessages == null) {
7662                mPostSystemReadyMessages = new ArrayList<>();
7663            }
7664            mPostSystemReadyMessages.add(msg);
7665        }
7666    }
7667
7668    void startCleaningPackages() {
7669        // reader
7670        synchronized (mPackages) {
7671            if (!isExternalMediaAvailable()) {
7672                return;
7673            }
7674            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7675                return;
7676            }
7677        }
7678        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7679        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7680        IActivityManager am = ActivityManagerNative.getDefault();
7681        if (am != null) {
7682            try {
7683                am.startService(null, intent, null, UserHandle.USER_OWNER);
7684            } catch (RemoteException e) {
7685            }
7686        }
7687    }
7688
7689    @Override
7690    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7691            int installFlags, String installerPackageName, VerificationParams verificationParams,
7692            String packageAbiOverride) {
7693        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7694                packageAbiOverride, UserHandle.getCallingUserId());
7695    }
7696
7697    @Override
7698    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7699            int installFlags, String installerPackageName, VerificationParams verificationParams,
7700            String packageAbiOverride, int userId) {
7701        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7702
7703        final int callingUid = Binder.getCallingUid();
7704        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7705
7706        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7707            try {
7708                if (observer != null) {
7709                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7710                }
7711            } catch (RemoteException re) {
7712            }
7713            return;
7714        }
7715
7716        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7717            installFlags |= PackageManager.INSTALL_FROM_ADB;
7718
7719        } else {
7720            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7721            // about installerPackageName.
7722
7723            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7724            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7725        }
7726
7727        UserHandle user;
7728        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7729            user = UserHandle.ALL;
7730        } else {
7731            user = new UserHandle(userId);
7732        }
7733
7734        verificationParams.setInstallerUid(callingUid);
7735
7736        final File originFile = new File(originPath);
7737        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7738
7739        final Message msg = mHandler.obtainMessage(INIT_COPY);
7740        msg.obj = new InstallParams(origin, observer, installFlags,
7741                installerPackageName, verificationParams, user, packageAbiOverride);
7742        mHandler.sendMessage(msg);
7743    }
7744
7745    void installStage(String packageName, File stagedDir, String stagedCid,
7746            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7747            String installerPackageName, int installerUid, UserHandle user) {
7748        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7749                params.referrerUri, installerUid, null);
7750
7751        final OriginInfo origin;
7752        if (stagedDir != null) {
7753            origin = OriginInfo.fromStagedFile(stagedDir);
7754        } else {
7755            origin = OriginInfo.fromStagedContainer(stagedCid);
7756        }
7757
7758        final Message msg = mHandler.obtainMessage(INIT_COPY);
7759        msg.obj = new InstallParams(origin, observer, params.installFlags,
7760                installerPackageName, verifParams, user, params.abiOverride);
7761        mHandler.sendMessage(msg);
7762    }
7763
7764    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7765        Bundle extras = new Bundle(1);
7766        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7767
7768        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7769                packageName, extras, null, null, new int[] {userId});
7770        try {
7771            IActivityManager am = ActivityManagerNative.getDefault();
7772            final boolean isSystem =
7773                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7774            if (isSystem && am.isUserRunning(userId, false)) {
7775                // The just-installed/enabled app is bundled on the system, so presumed
7776                // to be able to run automatically without needing an explicit launch.
7777                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7778                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7779                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7780                        .setPackage(packageName);
7781                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7782                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7783            }
7784        } catch (RemoteException e) {
7785            // shouldn't happen
7786            Slog.w(TAG, "Unable to bootstrap installed package", e);
7787        }
7788    }
7789
7790    @Override
7791    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7792            int userId) {
7793        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7794        PackageSetting pkgSetting;
7795        final int uid = Binder.getCallingUid();
7796        enforceCrossUserPermission(uid, userId, true, true,
7797                "setApplicationHiddenSetting for user " + userId);
7798
7799        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7800            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7801            return false;
7802        }
7803
7804        long callingId = Binder.clearCallingIdentity();
7805        try {
7806            boolean sendAdded = false;
7807            boolean sendRemoved = false;
7808            // writer
7809            synchronized (mPackages) {
7810                pkgSetting = mSettings.mPackages.get(packageName);
7811                if (pkgSetting == null) {
7812                    return false;
7813                }
7814                if (pkgSetting.getHidden(userId) != hidden) {
7815                    pkgSetting.setHidden(hidden, userId);
7816                    mSettings.writePackageRestrictionsLPr(userId);
7817                    if (hidden) {
7818                        sendRemoved = true;
7819                    } else {
7820                        sendAdded = true;
7821                    }
7822                }
7823            }
7824            if (sendAdded) {
7825                sendPackageAddedForUser(packageName, pkgSetting, userId);
7826                return true;
7827            }
7828            if (sendRemoved) {
7829                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7830                        "hiding pkg");
7831                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7832            }
7833        } finally {
7834            Binder.restoreCallingIdentity(callingId);
7835        }
7836        return false;
7837    }
7838
7839    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7840            int userId) {
7841        final PackageRemovedInfo info = new PackageRemovedInfo();
7842        info.removedPackage = packageName;
7843        info.removedUsers = new int[] {userId};
7844        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7845        info.sendBroadcast(false, false, false);
7846    }
7847
7848    /**
7849     * Returns true if application is not found or there was an error. Otherwise it returns
7850     * the hidden state of the package for the given user.
7851     */
7852    @Override
7853    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7854        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7855        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7856                false, "getApplicationHidden for user " + userId);
7857        PackageSetting pkgSetting;
7858        long callingId = Binder.clearCallingIdentity();
7859        try {
7860            // writer
7861            synchronized (mPackages) {
7862                pkgSetting = mSettings.mPackages.get(packageName);
7863                if (pkgSetting == null) {
7864                    return true;
7865                }
7866                return pkgSetting.getHidden(userId);
7867            }
7868        } finally {
7869            Binder.restoreCallingIdentity(callingId);
7870        }
7871    }
7872
7873    /**
7874     * @hide
7875     */
7876    @Override
7877    public int installExistingPackageAsUser(String packageName, int userId) {
7878        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7879                null);
7880        PackageSetting pkgSetting;
7881        final int uid = Binder.getCallingUid();
7882        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7883                + userId);
7884        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7885            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7886        }
7887
7888        long callingId = Binder.clearCallingIdentity();
7889        try {
7890            boolean sendAdded = false;
7891            Bundle extras = new Bundle(1);
7892
7893            // writer
7894            synchronized (mPackages) {
7895                pkgSetting = mSettings.mPackages.get(packageName);
7896                if (pkgSetting == null) {
7897                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7898                }
7899                if (!pkgSetting.getInstalled(userId)) {
7900                    pkgSetting.setInstalled(true, userId);
7901                    pkgSetting.setHidden(false, userId);
7902                    mSettings.writePackageRestrictionsLPr(userId);
7903                    sendAdded = true;
7904                }
7905            }
7906
7907            if (sendAdded) {
7908                sendPackageAddedForUser(packageName, pkgSetting, userId);
7909            }
7910        } finally {
7911            Binder.restoreCallingIdentity(callingId);
7912        }
7913
7914        return PackageManager.INSTALL_SUCCEEDED;
7915    }
7916
7917    boolean isUserRestricted(int userId, String restrictionKey) {
7918        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7919        if (restrictions.getBoolean(restrictionKey, false)) {
7920            Log.w(TAG, "User is restricted: " + restrictionKey);
7921            return true;
7922        }
7923        return false;
7924    }
7925
7926    @Override
7927    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7928        mContext.enforceCallingOrSelfPermission(
7929                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7930                "Only package verification agents can verify applications");
7931
7932        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7933        final PackageVerificationResponse response = new PackageVerificationResponse(
7934                verificationCode, Binder.getCallingUid());
7935        msg.arg1 = id;
7936        msg.obj = response;
7937        mHandler.sendMessage(msg);
7938    }
7939
7940    @Override
7941    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7942            long millisecondsToDelay) {
7943        mContext.enforceCallingOrSelfPermission(
7944                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7945                "Only package verification agents can extend verification timeouts");
7946
7947        final PackageVerificationState state = mPendingVerification.get(id);
7948        final PackageVerificationResponse response = new PackageVerificationResponse(
7949                verificationCodeAtTimeout, Binder.getCallingUid());
7950
7951        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7952            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7953        }
7954        if (millisecondsToDelay < 0) {
7955            millisecondsToDelay = 0;
7956        }
7957        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7958                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7959            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7960        }
7961
7962        if ((state != null) && !state.timeoutExtended()) {
7963            state.extendTimeout();
7964
7965            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7966            msg.arg1 = id;
7967            msg.obj = response;
7968            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7969        }
7970    }
7971
7972    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7973            int verificationCode, UserHandle user) {
7974        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7975        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7976        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7977        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7978        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7979
7980        mContext.sendBroadcastAsUser(intent, user,
7981                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7982    }
7983
7984    private ComponentName matchComponentForVerifier(String packageName,
7985            List<ResolveInfo> receivers) {
7986        ActivityInfo targetReceiver = null;
7987
7988        final int NR = receivers.size();
7989        for (int i = 0; i < NR; i++) {
7990            final ResolveInfo info = receivers.get(i);
7991            if (info.activityInfo == null) {
7992                continue;
7993            }
7994
7995            if (packageName.equals(info.activityInfo.packageName)) {
7996                targetReceiver = info.activityInfo;
7997                break;
7998            }
7999        }
8000
8001        if (targetReceiver == null) {
8002            return null;
8003        }
8004
8005        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8006    }
8007
8008    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8009            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8010        if (pkgInfo.verifiers.length == 0) {
8011            return null;
8012        }
8013
8014        final int N = pkgInfo.verifiers.length;
8015        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8016        for (int i = 0; i < N; i++) {
8017            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8018
8019            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8020                    receivers);
8021            if (comp == null) {
8022                continue;
8023            }
8024
8025            final int verifierUid = getUidForVerifier(verifierInfo);
8026            if (verifierUid == -1) {
8027                continue;
8028            }
8029
8030            if (DEBUG_VERIFY) {
8031                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8032                        + " with the correct signature");
8033            }
8034            sufficientVerifiers.add(comp);
8035            verificationState.addSufficientVerifier(verifierUid);
8036        }
8037
8038        return sufficientVerifiers;
8039    }
8040
8041    private int getUidForVerifier(VerifierInfo verifierInfo) {
8042        synchronized (mPackages) {
8043            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8044            if (pkg == null) {
8045                return -1;
8046            } else if (pkg.mSignatures.length != 1) {
8047                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8048                        + " has more than one signature; ignoring");
8049                return -1;
8050            }
8051
8052            /*
8053             * If the public key of the package's signature does not match
8054             * our expected public key, then this is a different package and
8055             * we should skip.
8056             */
8057
8058            final byte[] expectedPublicKey;
8059            try {
8060                final Signature verifierSig = pkg.mSignatures[0];
8061                final PublicKey publicKey = verifierSig.getPublicKey();
8062                expectedPublicKey = publicKey.getEncoded();
8063            } catch (CertificateException e) {
8064                return -1;
8065            }
8066
8067            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8068
8069            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8070                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8071                        + " does not have the expected public key; ignoring");
8072                return -1;
8073            }
8074
8075            return pkg.applicationInfo.uid;
8076        }
8077    }
8078
8079    @Override
8080    public void finishPackageInstall(int token) {
8081        enforceSystemOrRoot("Only the system is allowed to finish installs");
8082
8083        if (DEBUG_INSTALL) {
8084            Slog.v(TAG, "BM finishing package install for " + token);
8085        }
8086
8087        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8088        mHandler.sendMessage(msg);
8089    }
8090
8091    /**
8092     * Get the verification agent timeout.
8093     *
8094     * @return verification timeout in milliseconds
8095     */
8096    private long getVerificationTimeout() {
8097        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8098                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8099                DEFAULT_VERIFICATION_TIMEOUT);
8100    }
8101
8102    /**
8103     * Get the default verification agent response code.
8104     *
8105     * @return default verification response code
8106     */
8107    private int getDefaultVerificationResponse() {
8108        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8109                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8110                DEFAULT_VERIFICATION_RESPONSE);
8111    }
8112
8113    /**
8114     * Check whether or not package verification has been enabled.
8115     *
8116     * @return true if verification should be performed
8117     */
8118    private boolean isVerificationEnabled(int userId, int installFlags) {
8119        if (!DEFAULT_VERIFY_ENABLE) {
8120            return false;
8121        }
8122
8123        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8124
8125        // Check if installing from ADB
8126        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8127            // Do not run verification in a test harness environment
8128            if (ActivityManager.isRunningInTestHarness()) {
8129                return false;
8130            }
8131            if (ensureVerifyAppsEnabled) {
8132                return true;
8133            }
8134            // Check if the developer does not want package verification for ADB installs
8135            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8136                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8137                return false;
8138            }
8139        }
8140
8141        if (ensureVerifyAppsEnabled) {
8142            return true;
8143        }
8144
8145        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8146                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8147    }
8148
8149    /**
8150     * Get the "allow unknown sources" setting.
8151     *
8152     * @return the current "allow unknown sources" setting
8153     */
8154    private int getUnknownSourcesSettings() {
8155        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8156                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8157                -1);
8158    }
8159
8160    @Override
8161    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8162        final int uid = Binder.getCallingUid();
8163        // writer
8164        synchronized (mPackages) {
8165            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8166            if (targetPackageSetting == null) {
8167                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8168            }
8169
8170            PackageSetting installerPackageSetting;
8171            if (installerPackageName != null) {
8172                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8173                if (installerPackageSetting == null) {
8174                    throw new IllegalArgumentException("Unknown installer package: "
8175                            + installerPackageName);
8176                }
8177            } else {
8178                installerPackageSetting = null;
8179            }
8180
8181            Signature[] callerSignature;
8182            Object obj = mSettings.getUserIdLPr(uid);
8183            if (obj != null) {
8184                if (obj instanceof SharedUserSetting) {
8185                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8186                } else if (obj instanceof PackageSetting) {
8187                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8188                } else {
8189                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8190                }
8191            } else {
8192                throw new SecurityException("Unknown calling uid " + uid);
8193            }
8194
8195            // Verify: can't set installerPackageName to a package that is
8196            // not signed with the same cert as the caller.
8197            if (installerPackageSetting != null) {
8198                if (compareSignatures(callerSignature,
8199                        installerPackageSetting.signatures.mSignatures)
8200                        != PackageManager.SIGNATURE_MATCH) {
8201                    throw new SecurityException(
8202                            "Caller does not have same cert as new installer package "
8203                            + installerPackageName);
8204                }
8205            }
8206
8207            // Verify: if target already has an installer package, it must
8208            // be signed with the same cert as the caller.
8209            if (targetPackageSetting.installerPackageName != null) {
8210                PackageSetting setting = mSettings.mPackages.get(
8211                        targetPackageSetting.installerPackageName);
8212                // If the currently set package isn't valid, then it's always
8213                // okay to change it.
8214                if (setting != null) {
8215                    if (compareSignatures(callerSignature,
8216                            setting.signatures.mSignatures)
8217                            != PackageManager.SIGNATURE_MATCH) {
8218                        throw new SecurityException(
8219                                "Caller does not have same cert as old installer package "
8220                                + targetPackageSetting.installerPackageName);
8221                    }
8222                }
8223            }
8224
8225            // Okay!
8226            targetPackageSetting.installerPackageName = installerPackageName;
8227            scheduleWriteSettingsLocked();
8228        }
8229    }
8230
8231    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8232        // Queue up an async operation since the package installation may take a little while.
8233        mHandler.post(new Runnable() {
8234            public void run() {
8235                mHandler.removeCallbacks(this);
8236                 // Result object to be returned
8237                PackageInstalledInfo res = new PackageInstalledInfo();
8238                res.returnCode = currentStatus;
8239                res.uid = -1;
8240                res.pkg = null;
8241                res.removedInfo = new PackageRemovedInfo();
8242                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8243                    args.doPreInstall(res.returnCode);
8244                    synchronized (mInstallLock) {
8245                        installPackageLI(args, res);
8246                    }
8247                    args.doPostInstall(res.returnCode, res.uid);
8248                }
8249
8250                // A restore should be performed at this point if (a) the install
8251                // succeeded, (b) the operation is not an update, and (c) the new
8252                // package has not opted out of backup participation.
8253                final boolean update = res.removedInfo.removedPackage != null;
8254                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8255                boolean doRestore = !update
8256                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8257
8258                // Set up the post-install work request bookkeeping.  This will be used
8259                // and cleaned up by the post-install event handling regardless of whether
8260                // there's a restore pass performed.  Token values are >= 1.
8261                int token;
8262                if (mNextInstallToken < 0) mNextInstallToken = 1;
8263                token = mNextInstallToken++;
8264
8265                PostInstallData data = new PostInstallData(args, res);
8266                mRunningInstalls.put(token, data);
8267                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8268
8269                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8270                    // Pass responsibility to the Backup Manager.  It will perform a
8271                    // restore if appropriate, then pass responsibility back to the
8272                    // Package Manager to run the post-install observer callbacks
8273                    // and broadcasts.
8274                    IBackupManager bm = IBackupManager.Stub.asInterface(
8275                            ServiceManager.getService(Context.BACKUP_SERVICE));
8276                    if (bm != null) {
8277                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8278                                + " to BM for possible restore");
8279                        try {
8280                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8281                        } catch (RemoteException e) {
8282                            // can't happen; the backup manager is local
8283                        } catch (Exception e) {
8284                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8285                            doRestore = false;
8286                        }
8287                    } else {
8288                        Slog.e(TAG, "Backup Manager not found!");
8289                        doRestore = false;
8290                    }
8291                }
8292
8293                if (!doRestore) {
8294                    // No restore possible, or the Backup Manager was mysteriously not
8295                    // available -- just fire the post-install work request directly.
8296                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8297                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8298                    mHandler.sendMessage(msg);
8299                }
8300            }
8301        });
8302    }
8303
8304    private abstract class HandlerParams {
8305        private static final int MAX_RETRIES = 4;
8306
8307        /**
8308         * Number of times startCopy() has been attempted and had a non-fatal
8309         * error.
8310         */
8311        private int mRetries = 0;
8312
8313        /** User handle for the user requesting the information or installation. */
8314        private final UserHandle mUser;
8315
8316        HandlerParams(UserHandle user) {
8317            mUser = user;
8318        }
8319
8320        UserHandle getUser() {
8321            return mUser;
8322        }
8323
8324        final boolean startCopy() {
8325            boolean res;
8326            try {
8327                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8328
8329                if (++mRetries > MAX_RETRIES) {
8330                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8331                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8332                    handleServiceError();
8333                    return false;
8334                } else {
8335                    handleStartCopy();
8336                    res = true;
8337                }
8338            } catch (RemoteException e) {
8339                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8340                mHandler.sendEmptyMessage(MCS_RECONNECT);
8341                res = false;
8342            }
8343            handleReturnCode();
8344            return res;
8345        }
8346
8347        final void serviceError() {
8348            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8349            handleServiceError();
8350            handleReturnCode();
8351        }
8352
8353        abstract void handleStartCopy() throws RemoteException;
8354        abstract void handleServiceError();
8355        abstract void handleReturnCode();
8356    }
8357
8358    class MeasureParams extends HandlerParams {
8359        private final PackageStats mStats;
8360        private boolean mSuccess;
8361
8362        private final IPackageStatsObserver mObserver;
8363
8364        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8365            super(new UserHandle(stats.userHandle));
8366            mObserver = observer;
8367            mStats = stats;
8368        }
8369
8370        @Override
8371        public String toString() {
8372            return "MeasureParams{"
8373                + Integer.toHexString(System.identityHashCode(this))
8374                + " " + mStats.packageName + "}";
8375        }
8376
8377        @Override
8378        void handleStartCopy() throws RemoteException {
8379            synchronized (mInstallLock) {
8380                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8381            }
8382
8383            if (mSuccess) {
8384                final boolean mounted;
8385                if (Environment.isExternalStorageEmulated()) {
8386                    mounted = true;
8387                } else {
8388                    final String status = Environment.getExternalStorageState();
8389                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8390                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8391                }
8392
8393                if (mounted) {
8394                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8395
8396                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8397                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8398
8399                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8400                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8401
8402                    // Always subtract cache size, since it's a subdirectory
8403                    mStats.externalDataSize -= mStats.externalCacheSize;
8404
8405                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8406                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8407
8408                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8409                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8410                }
8411            }
8412        }
8413
8414        @Override
8415        void handleReturnCode() {
8416            if (mObserver != null) {
8417                try {
8418                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8419                } catch (RemoteException e) {
8420                    Slog.i(TAG, "Observer no longer exists.");
8421                }
8422            }
8423        }
8424
8425        @Override
8426        void handleServiceError() {
8427            Slog.e(TAG, "Could not measure application " + mStats.packageName
8428                            + " external storage");
8429        }
8430    }
8431
8432    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8433            throws RemoteException {
8434        long result = 0;
8435        for (File path : paths) {
8436            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8437        }
8438        return result;
8439    }
8440
8441    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8442        for (File path : paths) {
8443            try {
8444                mcs.clearDirectory(path.getAbsolutePath());
8445            } catch (RemoteException e) {
8446            }
8447        }
8448    }
8449
8450    static class OriginInfo {
8451        /**
8452         * Location where install is coming from, before it has been
8453         * copied/renamed into place. This could be a single monolithic APK
8454         * file, or a cluster directory. This location may be untrusted.
8455         */
8456        final File file;
8457        final String cid;
8458
8459        /**
8460         * Flag indicating that {@link #file} or {@link #cid} has already been
8461         * staged, meaning downstream users don't need to defensively copy the
8462         * contents.
8463         */
8464        final boolean staged;
8465
8466        /**
8467         * Flag indicating that {@link #file} or {@link #cid} is an already
8468         * installed app that is being moved.
8469         */
8470        final boolean existing;
8471
8472        final String resolvedPath;
8473        final File resolvedFile;
8474
8475        static OriginInfo fromNothing() {
8476            return new OriginInfo(null, null, false, false);
8477        }
8478
8479        static OriginInfo fromUntrustedFile(File file) {
8480            return new OriginInfo(file, null, false, false);
8481        }
8482
8483        static OriginInfo fromExistingFile(File file) {
8484            return new OriginInfo(file, null, false, true);
8485        }
8486
8487        static OriginInfo fromStagedFile(File file) {
8488            return new OriginInfo(file, null, true, false);
8489        }
8490
8491        static OriginInfo fromStagedContainer(String cid) {
8492            return new OriginInfo(null, cid, true, false);
8493        }
8494
8495        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8496            this.file = file;
8497            this.cid = cid;
8498            this.staged = staged;
8499            this.existing = existing;
8500
8501            if (cid != null) {
8502                resolvedPath = PackageHelper.getSdDir(cid);
8503                resolvedFile = new File(resolvedPath);
8504            } else if (file != null) {
8505                resolvedPath = file.getAbsolutePath();
8506                resolvedFile = file;
8507            } else {
8508                resolvedPath = null;
8509                resolvedFile = null;
8510            }
8511        }
8512    }
8513
8514    class InstallParams extends HandlerParams {
8515        final OriginInfo origin;
8516        final IPackageInstallObserver2 observer;
8517        int installFlags;
8518        final String installerPackageName;
8519        final VerificationParams verificationParams;
8520        private InstallArgs mArgs;
8521        private int mRet;
8522        final String packageAbiOverride;
8523
8524        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8525                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8526                String packageAbiOverride) {
8527            super(user);
8528            this.origin = origin;
8529            this.observer = observer;
8530            this.installFlags = installFlags;
8531            this.installerPackageName = installerPackageName;
8532            this.verificationParams = verificationParams;
8533            this.packageAbiOverride = packageAbiOverride;
8534        }
8535
8536        @Override
8537        public String toString() {
8538            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8539                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8540        }
8541
8542        public ManifestDigest getManifestDigest() {
8543            if (verificationParams == null) {
8544                return null;
8545            }
8546            return verificationParams.getManifestDigest();
8547        }
8548
8549        private int installLocationPolicy(PackageInfoLite pkgLite) {
8550            String packageName = pkgLite.packageName;
8551            int installLocation = pkgLite.installLocation;
8552            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8553            // reader
8554            synchronized (mPackages) {
8555                PackageParser.Package pkg = mPackages.get(packageName);
8556                if (pkg != null) {
8557                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8558                        // Check for downgrading.
8559                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8560                            if (pkgLite.versionCode < pkg.mVersionCode) {
8561                                Slog.w(TAG, "Can't install update of " + packageName
8562                                        + " update version " + pkgLite.versionCode
8563                                        + " is older than installed version "
8564                                        + pkg.mVersionCode);
8565                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8566                            }
8567                        }
8568                        // Check for updated system application.
8569                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8570                            if (onSd) {
8571                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8572                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8573                            }
8574                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8575                        } else {
8576                            if (onSd) {
8577                                // Install flag overrides everything.
8578                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8579                            }
8580                            // If current upgrade specifies particular preference
8581                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8582                                // Application explicitly specified internal.
8583                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8584                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8585                                // App explictly prefers external. Let policy decide
8586                            } else {
8587                                // Prefer previous location
8588                                if (isExternal(pkg)) {
8589                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8590                                }
8591                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8592                            }
8593                        }
8594                    } else {
8595                        // Invalid install. Return error code
8596                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8597                    }
8598                }
8599            }
8600            // All the special cases have been taken care of.
8601            // Return result based on recommended install location.
8602            if (onSd) {
8603                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8604            }
8605            return pkgLite.recommendedInstallLocation;
8606        }
8607
8608        /*
8609         * Invoke remote method to get package information and install
8610         * location values. Override install location based on default
8611         * policy if needed and then create install arguments based
8612         * on the install location.
8613         */
8614        public void handleStartCopy() throws RemoteException {
8615            int ret = PackageManager.INSTALL_SUCCEEDED;
8616
8617            // If we're already staged, we've firmly committed to an install location
8618            if (origin.staged) {
8619                if (origin.file != null) {
8620                    installFlags |= PackageManager.INSTALL_INTERNAL;
8621                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8622                } else if (origin.cid != null) {
8623                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8624                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8625                } else {
8626                    throw new IllegalStateException("Invalid stage location");
8627                }
8628            }
8629
8630            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8631            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8632
8633            PackageInfoLite pkgLite = null;
8634
8635            if (onInt && onSd) {
8636                // Check if both bits are set.
8637                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8638                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8639            } else {
8640                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8641                        packageAbiOverride);
8642
8643                /*
8644                 * If we have too little free space, try to free cache
8645                 * before giving up.
8646                 */
8647                if (!origin.staged && pkgLite.recommendedInstallLocation
8648                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8649                    // TODO: focus freeing disk space on the target device
8650                    final StorageManager storage = StorageManager.from(mContext);
8651                    final long lowThreshold = storage.getStorageLowBytes(
8652                            Environment.getDataDirectory());
8653
8654                    final long sizeBytes = mContainerService.calculateInstalledSize(
8655                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8656
8657                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8658                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8659                                installFlags, packageAbiOverride);
8660                    }
8661
8662                    /*
8663                     * The cache free must have deleted the file we
8664                     * downloaded to install.
8665                     *
8666                     * TODO: fix the "freeCache" call to not delete
8667                     *       the file we care about.
8668                     */
8669                    if (pkgLite.recommendedInstallLocation
8670                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8671                        pkgLite.recommendedInstallLocation
8672                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8673                    }
8674                }
8675            }
8676
8677            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8678                int loc = pkgLite.recommendedInstallLocation;
8679                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8680                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8681                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8682                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8683                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8684                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8685                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8686                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8687                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8688                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8689                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8690                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8691                } else {
8692                    // Override with defaults if needed.
8693                    loc = installLocationPolicy(pkgLite);
8694                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8695                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8696                    } else if (!onSd && !onInt) {
8697                        // Override install location with flags
8698                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8699                            // Set the flag to install on external media.
8700                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8701                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8702                        } else {
8703                            // Make sure the flag for installing on external
8704                            // media is unset
8705                            installFlags |= PackageManager.INSTALL_INTERNAL;
8706                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8707                        }
8708                    }
8709                }
8710            }
8711
8712            final InstallArgs args = createInstallArgs(this);
8713            mArgs = args;
8714
8715            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8716                 /*
8717                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8718                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8719                 */
8720                int userIdentifier = getUser().getIdentifier();
8721                if (userIdentifier == UserHandle.USER_ALL
8722                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8723                    userIdentifier = UserHandle.USER_OWNER;
8724                }
8725
8726                /*
8727                 * Determine if we have any installed package verifiers. If we
8728                 * do, then we'll defer to them to verify the packages.
8729                 */
8730                final int requiredUid = mRequiredVerifierPackage == null ? -1
8731                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8732                if (!origin.existing && requiredUid != -1
8733                        && isVerificationEnabled(userIdentifier, installFlags)) {
8734                    final Intent verification = new Intent(
8735                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8736                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8737                            PACKAGE_MIME_TYPE);
8738                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8739
8740                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8741                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8742                            0 /* TODO: Which userId? */);
8743
8744                    if (DEBUG_VERIFY) {
8745                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8746                                + verification.toString() + " with " + pkgLite.verifiers.length
8747                                + " optional verifiers");
8748                    }
8749
8750                    final int verificationId = mPendingVerificationToken++;
8751
8752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8753
8754                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8755                            installerPackageName);
8756
8757                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8758                            installFlags);
8759
8760                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8761                            pkgLite.packageName);
8762
8763                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8764                            pkgLite.versionCode);
8765
8766                    if (verificationParams != null) {
8767                        if (verificationParams.getVerificationURI() != null) {
8768                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8769                                 verificationParams.getVerificationURI());
8770                        }
8771                        if (verificationParams.getOriginatingURI() != null) {
8772                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8773                                  verificationParams.getOriginatingURI());
8774                        }
8775                        if (verificationParams.getReferrer() != null) {
8776                            verification.putExtra(Intent.EXTRA_REFERRER,
8777                                  verificationParams.getReferrer());
8778                        }
8779                        if (verificationParams.getOriginatingUid() >= 0) {
8780                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8781                                  verificationParams.getOriginatingUid());
8782                        }
8783                        if (verificationParams.getInstallerUid() >= 0) {
8784                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8785                                  verificationParams.getInstallerUid());
8786                        }
8787                    }
8788
8789                    final PackageVerificationState verificationState = new PackageVerificationState(
8790                            requiredUid, args);
8791
8792                    mPendingVerification.append(verificationId, verificationState);
8793
8794                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8795                            receivers, verificationState);
8796
8797                    /*
8798                     * If any sufficient verifiers were listed in the package
8799                     * manifest, attempt to ask them.
8800                     */
8801                    if (sufficientVerifiers != null) {
8802                        final int N = sufficientVerifiers.size();
8803                        if (N == 0) {
8804                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8805                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8806                        } else {
8807                            for (int i = 0; i < N; i++) {
8808                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8809
8810                                final Intent sufficientIntent = new Intent(verification);
8811                                sufficientIntent.setComponent(verifierComponent);
8812
8813                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8814                            }
8815                        }
8816                    }
8817
8818                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8819                            mRequiredVerifierPackage, receivers);
8820                    if (ret == PackageManager.INSTALL_SUCCEEDED
8821                            && mRequiredVerifierPackage != null) {
8822                        /*
8823                         * Send the intent to the required verification agent,
8824                         * but only start the verification timeout after the
8825                         * target BroadcastReceivers have run.
8826                         */
8827                        verification.setComponent(requiredVerifierComponent);
8828                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8829                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8830                                new BroadcastReceiver() {
8831                                    @Override
8832                                    public void onReceive(Context context, Intent intent) {
8833                                        final Message msg = mHandler
8834                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8835                                        msg.arg1 = verificationId;
8836                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8837                                    }
8838                                }, null, 0, null, null);
8839
8840                        /*
8841                         * We don't want the copy to proceed until verification
8842                         * succeeds, so null out this field.
8843                         */
8844                        mArgs = null;
8845                    }
8846                } else {
8847                    /*
8848                     * No package verification is enabled, so immediately start
8849                     * the remote call to initiate copy using temporary file.
8850                     */
8851                    ret = args.copyApk(mContainerService, true);
8852                }
8853            }
8854
8855            mRet = ret;
8856        }
8857
8858        @Override
8859        void handleReturnCode() {
8860            // If mArgs is null, then MCS couldn't be reached. When it
8861            // reconnects, it will try again to install. At that point, this
8862            // will succeed.
8863            if (mArgs != null) {
8864                processPendingInstall(mArgs, mRet);
8865            }
8866        }
8867
8868        @Override
8869        void handleServiceError() {
8870            mArgs = createInstallArgs(this);
8871            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8872        }
8873
8874        public boolean isForwardLocked() {
8875            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8876        }
8877    }
8878
8879    /**
8880     * Used during creation of InstallArgs
8881     *
8882     * @param installFlags package installation flags
8883     * @return true if should be installed on external storage
8884     */
8885    private static boolean installOnSd(int installFlags) {
8886        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8887            return false;
8888        }
8889        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8890            return true;
8891        }
8892        return false;
8893    }
8894
8895    /**
8896     * Used during creation of InstallArgs
8897     *
8898     * @param installFlags package installation flags
8899     * @return true if should be installed as forward locked
8900     */
8901    private static boolean installForwardLocked(int installFlags) {
8902        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8903    }
8904
8905    private InstallArgs createInstallArgs(InstallParams params) {
8906        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8907            return new AsecInstallArgs(params);
8908        } else {
8909            return new FileInstallArgs(params);
8910        }
8911    }
8912
8913    /**
8914     * Create args that describe an existing installed package. Typically used
8915     * when cleaning up old installs, or used as a move source.
8916     */
8917    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8918            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8919        final boolean isInAsec;
8920        if (installOnSd(installFlags)) {
8921            /* Apps on SD card are always in ASEC containers. */
8922            isInAsec = true;
8923        } else if (installForwardLocked(installFlags)
8924                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8925            /*
8926             * Forward-locked apps are only in ASEC containers if they're the
8927             * new style
8928             */
8929            isInAsec = true;
8930        } else {
8931            isInAsec = false;
8932        }
8933
8934        if (isInAsec) {
8935            return new AsecInstallArgs(codePath, instructionSets,
8936                    installOnSd(installFlags), installForwardLocked(installFlags));
8937        } else {
8938            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8939                    instructionSets);
8940        }
8941    }
8942
8943    static abstract class InstallArgs {
8944        /** @see InstallParams#origin */
8945        final OriginInfo origin;
8946
8947        final IPackageInstallObserver2 observer;
8948        // Always refers to PackageManager flags only
8949        final int installFlags;
8950        final String installerPackageName;
8951        final ManifestDigest manifestDigest;
8952        final UserHandle user;
8953        final String abiOverride;
8954
8955        // The list of instruction sets supported by this app. This is currently
8956        // only used during the rmdex() phase to clean up resources. We can get rid of this
8957        // if we move dex files under the common app path.
8958        /* nullable */ String[] instructionSets;
8959
8960        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8961                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8962                String[] instructionSets, String abiOverride) {
8963            this.origin = origin;
8964            this.installFlags = installFlags;
8965            this.observer = observer;
8966            this.installerPackageName = installerPackageName;
8967            this.manifestDigest = manifestDigest;
8968            this.user = user;
8969            this.instructionSets = instructionSets;
8970            this.abiOverride = abiOverride;
8971        }
8972
8973        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8974        abstract int doPreInstall(int status);
8975
8976        /**
8977         * Rename package into final resting place. All paths on the given
8978         * scanned package should be updated to reflect the rename.
8979         */
8980        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8981        abstract int doPostInstall(int status, int uid);
8982
8983        /** @see PackageSettingBase#codePathString */
8984        abstract String getCodePath();
8985        /** @see PackageSettingBase#resourcePathString */
8986        abstract String getResourcePath();
8987        abstract String getLegacyNativeLibraryPath();
8988
8989        // Need installer lock especially for dex file removal.
8990        abstract void cleanUpResourcesLI();
8991        abstract boolean doPostDeleteLI(boolean delete);
8992        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8993
8994        /**
8995         * Called before the source arguments are copied. This is used mostly
8996         * for MoveParams when it needs to read the source file to put it in the
8997         * destination.
8998         */
8999        int doPreCopy() {
9000            return PackageManager.INSTALL_SUCCEEDED;
9001        }
9002
9003        /**
9004         * Called after the source arguments are copied. This is used mostly for
9005         * MoveParams when it needs to read the source file to put it in the
9006         * destination.
9007         *
9008         * @return
9009         */
9010        int doPostCopy(int uid) {
9011            return PackageManager.INSTALL_SUCCEEDED;
9012        }
9013
9014        protected boolean isFwdLocked() {
9015            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9016        }
9017
9018        protected boolean isExternal() {
9019            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9020        }
9021
9022        UserHandle getUser() {
9023            return user;
9024        }
9025    }
9026
9027    /**
9028     * Logic to handle installation of non-ASEC applications, including copying
9029     * and renaming logic.
9030     */
9031    class FileInstallArgs extends InstallArgs {
9032        private File codeFile;
9033        private File resourceFile;
9034        private File legacyNativeLibraryPath;
9035
9036        // Example topology:
9037        // /data/app/com.example/base.apk
9038        // /data/app/com.example/split_foo.apk
9039        // /data/app/com.example/lib/arm/libfoo.so
9040        // /data/app/com.example/lib/arm64/libfoo.so
9041        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9042
9043        /** New install */
9044        FileInstallArgs(InstallParams params) {
9045            super(params.origin, params.observer, params.installFlags,
9046                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9047                    null /* instruction sets */, params.packageAbiOverride);
9048            if (isFwdLocked()) {
9049                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9050            }
9051        }
9052
9053        /** Existing install */
9054        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9055                String[] instructionSets) {
9056            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9057            this.codeFile = (codePath != null) ? new File(codePath) : null;
9058            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9059            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9060                    new File(legacyNativeLibraryPath) : null;
9061        }
9062
9063        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9064            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9065                    isFwdLocked(), abiOverride);
9066
9067            final StorageManager storage = StorageManager.from(mContext);
9068            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9069        }
9070
9071        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9072            if (origin.staged) {
9073                Slog.d(TAG, origin.file + " already staged; skipping copy");
9074                codeFile = origin.file;
9075                resourceFile = origin.file;
9076                return PackageManager.INSTALL_SUCCEEDED;
9077            }
9078
9079            try {
9080                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9081                codeFile = tempDir;
9082                resourceFile = tempDir;
9083            } catch (IOException e) {
9084                Slog.w(TAG, "Failed to create copy file: " + e);
9085                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9086            }
9087
9088            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9089                @Override
9090                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9091                    if (!FileUtils.isValidExtFilename(name)) {
9092                        throw new IllegalArgumentException("Invalid filename: " + name);
9093                    }
9094                    try {
9095                        final File file = new File(codeFile, name);
9096                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9097                                O_RDWR | O_CREAT, 0644);
9098                        Os.chmod(file.getAbsolutePath(), 0644);
9099                        return new ParcelFileDescriptor(fd);
9100                    } catch (ErrnoException e) {
9101                        throw new RemoteException("Failed to open: " + e.getMessage());
9102                    }
9103                }
9104            };
9105
9106            int ret = PackageManager.INSTALL_SUCCEEDED;
9107            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9108            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9109                Slog.e(TAG, "Failed to copy package");
9110                return ret;
9111            }
9112
9113            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9114            NativeLibraryHelper.Handle handle = null;
9115            try {
9116                handle = NativeLibraryHelper.Handle.create(codeFile);
9117                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9118                        abiOverride);
9119            } catch (IOException e) {
9120                Slog.e(TAG, "Copying native libraries failed", e);
9121                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9122            } finally {
9123                IoUtils.closeQuietly(handle);
9124            }
9125
9126            return ret;
9127        }
9128
9129        int doPreInstall(int status) {
9130            if (status != PackageManager.INSTALL_SUCCEEDED) {
9131                cleanUp();
9132            }
9133            return status;
9134        }
9135
9136        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9137            if (status != PackageManager.INSTALL_SUCCEEDED) {
9138                cleanUp();
9139                return false;
9140            } else {
9141                final File beforeCodeFile = codeFile;
9142                final File afterCodeFile = getNextCodePath(pkg.packageName);
9143
9144                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9145                try {
9146                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9147                } catch (ErrnoException e) {
9148                    Slog.d(TAG, "Failed to rename", e);
9149                    return false;
9150                }
9151
9152                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9153                    Slog.d(TAG, "Failed to restorecon");
9154                    return false;
9155                }
9156
9157                // Reflect the rename internally
9158                codeFile = afterCodeFile;
9159                resourceFile = afterCodeFile;
9160
9161                // Reflect the rename in scanned details
9162                pkg.codePath = afterCodeFile.getAbsolutePath();
9163                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9164                        pkg.baseCodePath);
9165                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9166                        pkg.splitCodePaths);
9167
9168                // Reflect the rename in app info
9169                pkg.applicationInfo.setCodePath(pkg.codePath);
9170                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9171                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9172                pkg.applicationInfo.setResourcePath(pkg.codePath);
9173                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9174                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9175
9176                return true;
9177            }
9178        }
9179
9180        int doPostInstall(int status, int uid) {
9181            if (status != PackageManager.INSTALL_SUCCEEDED) {
9182                cleanUp();
9183            }
9184            return status;
9185        }
9186
9187        @Override
9188        String getCodePath() {
9189            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9190        }
9191
9192        @Override
9193        String getResourcePath() {
9194            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9195        }
9196
9197        @Override
9198        String getLegacyNativeLibraryPath() {
9199            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9200        }
9201
9202        private boolean cleanUp() {
9203            if (codeFile == null || !codeFile.exists()) {
9204                return false;
9205            }
9206
9207            if (codeFile.isDirectory()) {
9208                FileUtils.deleteContents(codeFile);
9209            }
9210            codeFile.delete();
9211
9212            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9213                resourceFile.delete();
9214            }
9215
9216            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9217                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9218                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9219                }
9220                legacyNativeLibraryPath.delete();
9221            }
9222
9223            return true;
9224        }
9225
9226        void cleanUpResourcesLI() {
9227            // Try enumerating all code paths before deleting
9228            List<String> allCodePaths = Collections.EMPTY_LIST;
9229            if (codeFile != null && codeFile.exists()) {
9230                try {
9231                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9232                    allCodePaths = pkg.getAllCodePaths();
9233                } catch (PackageParserException e) {
9234                    // Ignored; we tried our best
9235                }
9236            }
9237
9238            cleanUp();
9239
9240            if (!allCodePaths.isEmpty()) {
9241                if (instructionSets == null) {
9242                    throw new IllegalStateException("instructionSet == null");
9243                }
9244                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9245                for (String codePath : allCodePaths) {
9246                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9247                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9248                        if (retCode < 0) {
9249                            Slog.w(TAG, "Couldn't remove dex file for package: "
9250                                    + " at location " + codePath + ", retcode=" + retCode);
9251                            // we don't consider this to be a failure of the core package deletion
9252                        }
9253                    }
9254                }
9255            }
9256        }
9257
9258        boolean doPostDeleteLI(boolean delete) {
9259            // XXX err, shouldn't we respect the delete flag?
9260            cleanUpResourcesLI();
9261            return true;
9262        }
9263    }
9264
9265    private boolean isAsecExternal(String cid) {
9266        final String asecPath = PackageHelper.getSdFilesystem(cid);
9267        return !asecPath.startsWith(mAsecInternalPath);
9268    }
9269
9270    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9271            PackageManagerException {
9272        if (copyRet < 0) {
9273            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9274                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9275                throw new PackageManagerException(copyRet, message);
9276            }
9277        }
9278    }
9279
9280    /**
9281     * Extract the MountService "container ID" from the full code path of an
9282     * .apk.
9283     */
9284    static String cidFromCodePath(String fullCodePath) {
9285        int eidx = fullCodePath.lastIndexOf("/");
9286        String subStr1 = fullCodePath.substring(0, eidx);
9287        int sidx = subStr1.lastIndexOf("/");
9288        return subStr1.substring(sidx+1, eidx);
9289    }
9290
9291    /**
9292     * Logic to handle installation of ASEC applications, including copying and
9293     * renaming logic.
9294     */
9295    class AsecInstallArgs extends InstallArgs {
9296        static final String RES_FILE_NAME = "pkg.apk";
9297        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9298
9299        String cid;
9300        String packagePath;
9301        String resourcePath;
9302        String legacyNativeLibraryDir;
9303
9304        /** New install */
9305        AsecInstallArgs(InstallParams params) {
9306            super(params.origin, params.observer, params.installFlags,
9307                    params.installerPackageName, params.getManifestDigest(),
9308                    params.getUser(), null /* instruction sets */,
9309                    params.packageAbiOverride);
9310        }
9311
9312        /** Existing install */
9313        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9314                        boolean isExternal, boolean isForwardLocked) {
9315            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9316                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9317                    instructionSets, null);
9318            // Hackily pretend we're still looking at a full code path
9319            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9320                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9321            }
9322
9323            // Extract cid from fullCodePath
9324            int eidx = fullCodePath.lastIndexOf("/");
9325            String subStr1 = fullCodePath.substring(0, eidx);
9326            int sidx = subStr1.lastIndexOf("/");
9327            cid = subStr1.substring(sidx+1, eidx);
9328            setMountPath(subStr1);
9329        }
9330
9331        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9332            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9333                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9334                    instructionSets, null);
9335            this.cid = cid;
9336            setMountPath(PackageHelper.getSdDir(cid));
9337        }
9338
9339        void createCopyFile() {
9340            cid = mInstallerService.allocateExternalStageCidLegacy();
9341        }
9342
9343        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9344            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9345                    abiOverride);
9346
9347            final File target;
9348            if (isExternal()) {
9349                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9350            } else {
9351                target = Environment.getDataDirectory();
9352            }
9353
9354            final StorageManager storage = StorageManager.from(mContext);
9355            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9356        }
9357
9358        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9359            if (origin.staged) {
9360                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9361                cid = origin.cid;
9362                setMountPath(PackageHelper.getSdDir(cid));
9363                return PackageManager.INSTALL_SUCCEEDED;
9364            }
9365
9366            if (temp) {
9367                createCopyFile();
9368            } else {
9369                /*
9370                 * Pre-emptively destroy the container since it's destroyed if
9371                 * copying fails due to it existing anyway.
9372                 */
9373                PackageHelper.destroySdDir(cid);
9374            }
9375
9376            final String newMountPath = imcs.copyPackageToContainer(
9377                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9378                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9379
9380            if (newMountPath != null) {
9381                setMountPath(newMountPath);
9382                return PackageManager.INSTALL_SUCCEEDED;
9383            } else {
9384                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9385            }
9386        }
9387
9388        @Override
9389        String getCodePath() {
9390            return packagePath;
9391        }
9392
9393        @Override
9394        String getResourcePath() {
9395            return resourcePath;
9396        }
9397
9398        @Override
9399        String getLegacyNativeLibraryPath() {
9400            return legacyNativeLibraryDir;
9401        }
9402
9403        int doPreInstall(int status) {
9404            if (status != PackageManager.INSTALL_SUCCEEDED) {
9405                // Destroy container
9406                PackageHelper.destroySdDir(cid);
9407            } else {
9408                boolean mounted = PackageHelper.isContainerMounted(cid);
9409                if (!mounted) {
9410                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9411                            Process.SYSTEM_UID);
9412                    if (newMountPath != null) {
9413                        setMountPath(newMountPath);
9414                    } else {
9415                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9416                    }
9417                }
9418            }
9419            return status;
9420        }
9421
9422        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9423            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9424            String newMountPath = null;
9425            if (PackageHelper.isContainerMounted(cid)) {
9426                // Unmount the container
9427                if (!PackageHelper.unMountSdDir(cid)) {
9428                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9429                    return false;
9430                }
9431            }
9432            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9433                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9434                        " which might be stale. Will try to clean up.");
9435                // Clean up the stale container and proceed to recreate.
9436                if (!PackageHelper.destroySdDir(newCacheId)) {
9437                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9438                    return false;
9439                }
9440                // Successfully cleaned up stale container. Try to rename again.
9441                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9442                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9443                            + " inspite of cleaning it up.");
9444                    return false;
9445                }
9446            }
9447            if (!PackageHelper.isContainerMounted(newCacheId)) {
9448                Slog.w(TAG, "Mounting container " + newCacheId);
9449                newMountPath = PackageHelper.mountSdDir(newCacheId,
9450                        getEncryptKey(), Process.SYSTEM_UID);
9451            } else {
9452                newMountPath = PackageHelper.getSdDir(newCacheId);
9453            }
9454            if (newMountPath == null) {
9455                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9456                return false;
9457            }
9458            Log.i(TAG, "Succesfully renamed " + cid +
9459                    " to " + newCacheId +
9460                    " at new path: " + newMountPath);
9461            cid = newCacheId;
9462
9463            final File beforeCodeFile = new File(packagePath);
9464            setMountPath(newMountPath);
9465            final File afterCodeFile = new File(packagePath);
9466
9467            // Reflect the rename in scanned details
9468            pkg.codePath = afterCodeFile.getAbsolutePath();
9469            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9470                    pkg.baseCodePath);
9471            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9472                    pkg.splitCodePaths);
9473
9474            // Reflect the rename in app info
9475            pkg.applicationInfo.setCodePath(pkg.codePath);
9476            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9477            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9478            pkg.applicationInfo.setResourcePath(pkg.codePath);
9479            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9480            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9481
9482            return true;
9483        }
9484
9485        private void setMountPath(String mountPath) {
9486            final File mountFile = new File(mountPath);
9487
9488            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9489            if (monolithicFile.exists()) {
9490                packagePath = monolithicFile.getAbsolutePath();
9491                if (isFwdLocked()) {
9492                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9493                } else {
9494                    resourcePath = packagePath;
9495                }
9496            } else {
9497                packagePath = mountFile.getAbsolutePath();
9498                resourcePath = packagePath;
9499            }
9500
9501            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9502        }
9503
9504        int doPostInstall(int status, int uid) {
9505            if (status != PackageManager.INSTALL_SUCCEEDED) {
9506                cleanUp();
9507            } else {
9508                final int groupOwner;
9509                final String protectedFile;
9510                if (isFwdLocked()) {
9511                    groupOwner = UserHandle.getSharedAppGid(uid);
9512                    protectedFile = RES_FILE_NAME;
9513                } else {
9514                    groupOwner = -1;
9515                    protectedFile = null;
9516                }
9517
9518                if (uid < Process.FIRST_APPLICATION_UID
9519                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9520                    Slog.e(TAG, "Failed to finalize " + cid);
9521                    PackageHelper.destroySdDir(cid);
9522                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9523                }
9524
9525                boolean mounted = PackageHelper.isContainerMounted(cid);
9526                if (!mounted) {
9527                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9528                }
9529            }
9530            return status;
9531        }
9532
9533        private void cleanUp() {
9534            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9535
9536            // Destroy secure container
9537            PackageHelper.destroySdDir(cid);
9538        }
9539
9540        private List<String> getAllCodePaths() {
9541            final File codeFile = new File(getCodePath());
9542            if (codeFile != null && codeFile.exists()) {
9543                try {
9544                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9545                    return pkg.getAllCodePaths();
9546                } catch (PackageParserException e) {
9547                    // Ignored; we tried our best
9548                }
9549            }
9550            return Collections.EMPTY_LIST;
9551        }
9552
9553        void cleanUpResourcesLI() {
9554            // Enumerate all code paths before deleting
9555            cleanUpResourcesLI(getAllCodePaths());
9556        }
9557
9558        private void cleanUpResourcesLI(List<String> allCodePaths) {
9559            cleanUp();
9560
9561            if (!allCodePaths.isEmpty()) {
9562                if (instructionSets == null) {
9563                    throw new IllegalStateException("instructionSet == null");
9564                }
9565                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9566                for (String codePath : allCodePaths) {
9567                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9568                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9569                        if (retCode < 0) {
9570                            Slog.w(TAG, "Couldn't remove dex file for package: "
9571                                    + " at location " + codePath + ", retcode=" + retCode);
9572                            // we don't consider this to be a failure of the core package deletion
9573                        }
9574                    }
9575                }
9576            }
9577        }
9578
9579        boolean matchContainer(String app) {
9580            if (cid.startsWith(app)) {
9581                return true;
9582            }
9583            return false;
9584        }
9585
9586        String getPackageName() {
9587            return getAsecPackageName(cid);
9588        }
9589
9590        boolean doPostDeleteLI(boolean delete) {
9591            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9592            final List<String> allCodePaths = getAllCodePaths();
9593            boolean mounted = PackageHelper.isContainerMounted(cid);
9594            if (mounted) {
9595                // Unmount first
9596                if (PackageHelper.unMountSdDir(cid)) {
9597                    mounted = false;
9598                }
9599            }
9600            if (!mounted && delete) {
9601                cleanUpResourcesLI(allCodePaths);
9602            }
9603            return !mounted;
9604        }
9605
9606        @Override
9607        int doPreCopy() {
9608            if (isFwdLocked()) {
9609                if (!PackageHelper.fixSdPermissions(cid,
9610                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9611                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9612                }
9613            }
9614
9615            return PackageManager.INSTALL_SUCCEEDED;
9616        }
9617
9618        @Override
9619        int doPostCopy(int uid) {
9620            if (isFwdLocked()) {
9621                if (uid < Process.FIRST_APPLICATION_UID
9622                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9623                                RES_FILE_NAME)) {
9624                    Slog.e(TAG, "Failed to finalize " + cid);
9625                    PackageHelper.destroySdDir(cid);
9626                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9627                }
9628            }
9629
9630            return PackageManager.INSTALL_SUCCEEDED;
9631        }
9632    }
9633
9634    static String getAsecPackageName(String packageCid) {
9635        int idx = packageCid.lastIndexOf("-");
9636        if (idx == -1) {
9637            return packageCid;
9638        }
9639        return packageCid.substring(0, idx);
9640    }
9641
9642    // Utility method used to create code paths based on package name and available index.
9643    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9644        String idxStr = "";
9645        int idx = 1;
9646        // Fall back to default value of idx=1 if prefix is not
9647        // part of oldCodePath
9648        if (oldCodePath != null) {
9649            String subStr = oldCodePath;
9650            // Drop the suffix right away
9651            if (suffix != null && subStr.endsWith(suffix)) {
9652                subStr = subStr.substring(0, subStr.length() - suffix.length());
9653            }
9654            // If oldCodePath already contains prefix find out the
9655            // ending index to either increment or decrement.
9656            int sidx = subStr.lastIndexOf(prefix);
9657            if (sidx != -1) {
9658                subStr = subStr.substring(sidx + prefix.length());
9659                if (subStr != null) {
9660                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9661                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9662                    }
9663                    try {
9664                        idx = Integer.parseInt(subStr);
9665                        if (idx <= 1) {
9666                            idx++;
9667                        } else {
9668                            idx--;
9669                        }
9670                    } catch(NumberFormatException e) {
9671                    }
9672                }
9673            }
9674        }
9675        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9676        return prefix + idxStr;
9677    }
9678
9679    private File getNextCodePath(String packageName) {
9680        int suffix = 1;
9681        File result;
9682        do {
9683            result = new File(mAppInstallDir, packageName + "-" + suffix);
9684            suffix++;
9685        } while (result.exists());
9686        return result;
9687    }
9688
9689    // Utility method used to ignore ADD/REMOVE events
9690    // by directory observer.
9691    private static boolean ignoreCodePath(String fullPathStr) {
9692        String apkName = deriveCodePathName(fullPathStr);
9693        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9694        if (idx != -1 && ((idx+1) < apkName.length())) {
9695            // Make sure the package ends with a numeral
9696            String version = apkName.substring(idx+1);
9697            try {
9698                Integer.parseInt(version);
9699                return true;
9700            } catch (NumberFormatException e) {}
9701        }
9702        return false;
9703    }
9704
9705    // Utility method that returns the relative package path with respect
9706    // to the installation directory. Like say for /data/data/com.test-1.apk
9707    // string com.test-1 is returned.
9708    static String deriveCodePathName(String codePath) {
9709        if (codePath == null) {
9710            return null;
9711        }
9712        final File codeFile = new File(codePath);
9713        final String name = codeFile.getName();
9714        if (codeFile.isDirectory()) {
9715            return name;
9716        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9717            final int lastDot = name.lastIndexOf('.');
9718            return name.substring(0, lastDot);
9719        } else {
9720            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9721            return null;
9722        }
9723    }
9724
9725    class PackageInstalledInfo {
9726        String name;
9727        int uid;
9728        // The set of users that originally had this package installed.
9729        int[] origUsers;
9730        // The set of users that now have this package installed.
9731        int[] newUsers;
9732        PackageParser.Package pkg;
9733        int returnCode;
9734        String returnMsg;
9735        PackageRemovedInfo removedInfo;
9736
9737        public void setError(int code, String msg) {
9738            returnCode = code;
9739            returnMsg = msg;
9740            Slog.w(TAG, msg);
9741        }
9742
9743        public void setError(String msg, PackageParserException e) {
9744            returnCode = e.error;
9745            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9746            Slog.w(TAG, msg, e);
9747        }
9748
9749        public void setError(String msg, PackageManagerException e) {
9750            returnCode = e.error;
9751            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9752            Slog.w(TAG, msg, e);
9753        }
9754
9755        // In some error cases we want to convey more info back to the observer
9756        String origPackage;
9757        String origPermission;
9758    }
9759
9760    /*
9761     * Install a non-existing package.
9762     */
9763    private void installNewPackageLI(PackageParser.Package pkg,
9764            int parseFlags, int scanFlags, UserHandle user,
9765            String installerPackageName, PackageInstalledInfo res) {
9766        // Remember this for later, in case we need to rollback this install
9767        String pkgName = pkg.packageName;
9768
9769        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9770        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9771        synchronized(mPackages) {
9772            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9773                // A package with the same name is already installed, though
9774                // it has been renamed to an older name.  The package we
9775                // are trying to install should be installed as an update to
9776                // the existing one, but that has not been requested, so bail.
9777                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9778                        + " without first uninstalling package running as "
9779                        + mSettings.mRenamedPackages.get(pkgName));
9780                return;
9781            }
9782            if (mPackages.containsKey(pkgName)) {
9783                // Don't allow installation over an existing package with the same name.
9784                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9785                        + " without first uninstalling.");
9786                return;
9787            }
9788        }
9789
9790        try {
9791            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9792                    System.currentTimeMillis(), user);
9793
9794            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9795            // delete the partially installed application. the data directory will have to be
9796            // restored if it was already existing
9797            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9798                // remove package from internal structures.  Note that we want deletePackageX to
9799                // delete the package data and cache directories that it created in
9800                // scanPackageLocked, unless those directories existed before we even tried to
9801                // install.
9802                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9803                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9804                                res.removedInfo, true);
9805            }
9806
9807        } catch (PackageManagerException e) {
9808            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9809        }
9810    }
9811
9812    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9813        // Upgrade keysets are being used.  Determine if new package has a superset of the
9814        // required keys.
9815        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9816        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9817        for (int i = 0; i < upgradeKeySets.length; i++) {
9818            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9819            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9820                return true;
9821            }
9822        }
9823        return false;
9824    }
9825
9826    private void replacePackageLI(PackageParser.Package pkg,
9827            int parseFlags, int scanFlags, UserHandle user,
9828            String installerPackageName, PackageInstalledInfo res) {
9829        PackageParser.Package oldPackage;
9830        String pkgName = pkg.packageName;
9831        int[] allUsers;
9832        boolean[] perUserInstalled;
9833
9834        // First find the old package info and check signatures
9835        synchronized(mPackages) {
9836            oldPackage = mPackages.get(pkgName);
9837            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9838            PackageSetting ps = mSettings.mPackages.get(pkgName);
9839            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9840                // default to original signature matching
9841                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9842                    != PackageManager.SIGNATURE_MATCH) {
9843                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9844                            "New package has a different signature: " + pkgName);
9845                    return;
9846                }
9847            } else {
9848                if(!checkUpgradeKeySetLP(ps, pkg)) {
9849                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9850                            "New package not signed by keys specified by upgrade-keysets: "
9851                            + pkgName);
9852                    return;
9853                }
9854            }
9855
9856            // In case of rollback, remember per-user/profile install state
9857            allUsers = sUserManager.getUserIds();
9858            perUserInstalled = new boolean[allUsers.length];
9859            for (int i = 0; i < allUsers.length; i++) {
9860                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9861            }
9862        }
9863
9864        boolean sysPkg = (isSystemApp(oldPackage));
9865        if (sysPkg) {
9866            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9867                    user, allUsers, perUserInstalled, installerPackageName, res);
9868        } else {
9869            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9870                    user, allUsers, perUserInstalled, installerPackageName, res);
9871        }
9872    }
9873
9874    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9875            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9876            int[] allUsers, boolean[] perUserInstalled,
9877            String installerPackageName, PackageInstalledInfo res) {
9878        String pkgName = deletedPackage.packageName;
9879        boolean deletedPkg = true;
9880        boolean updatedSettings = false;
9881
9882        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9883                + deletedPackage);
9884        long origUpdateTime;
9885        if (pkg.mExtras != null) {
9886            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9887        } else {
9888            origUpdateTime = 0;
9889        }
9890
9891        // First delete the existing package while retaining the data directory
9892        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9893                res.removedInfo, true)) {
9894            // If the existing package wasn't successfully deleted
9895            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9896            deletedPkg = false;
9897        } else {
9898            // Successfully deleted the old package; proceed with replace.
9899
9900            // If deleted package lived in a container, give users a chance to
9901            // relinquish resources before killing.
9902            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9903                if (DEBUG_INSTALL) {
9904                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9905                }
9906                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9907                final ArrayList<String> pkgList = new ArrayList<String>(1);
9908                pkgList.add(deletedPackage.applicationInfo.packageName);
9909                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9910            }
9911
9912            deleteCodeCacheDirsLI(pkgName);
9913            try {
9914                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9915                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9916                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9917                updatedSettings = true;
9918            } catch (PackageManagerException e) {
9919                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9920            }
9921        }
9922
9923        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9924            // remove package from internal structures.  Note that we want deletePackageX to
9925            // delete the package data and cache directories that it created in
9926            // scanPackageLocked, unless those directories existed before we even tried to
9927            // install.
9928            if(updatedSettings) {
9929                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9930                deletePackageLI(
9931                        pkgName, null, true, allUsers, perUserInstalled,
9932                        PackageManager.DELETE_KEEP_DATA,
9933                                res.removedInfo, true);
9934            }
9935            // Since we failed to install the new package we need to restore the old
9936            // package that we deleted.
9937            if (deletedPkg) {
9938                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9939                File restoreFile = new File(deletedPackage.codePath);
9940                // Parse old package
9941                boolean oldOnSd = isExternal(deletedPackage);
9942                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9943                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9944                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9945                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9946                try {
9947                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9948                } catch (PackageManagerException e) {
9949                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9950                            + e.getMessage());
9951                    return;
9952                }
9953                // Restore of old package succeeded. Update permissions.
9954                // writer
9955                synchronized (mPackages) {
9956                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9957                            UPDATE_PERMISSIONS_ALL);
9958                    // can downgrade to reader
9959                    mSettings.writeLPr();
9960                }
9961                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9962            }
9963        }
9964    }
9965
9966    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9967            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9968            int[] allUsers, boolean[] perUserInstalled,
9969            String installerPackageName, PackageInstalledInfo res) {
9970        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9971                + ", old=" + deletedPackage);
9972        boolean updatedSettings = false;
9973        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9974        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9975            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9976        }
9977        String packageName = deletedPackage.packageName;
9978        if (packageName == null) {
9979            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9980                    "Attempt to delete null packageName.");
9981            return;
9982        }
9983        PackageParser.Package oldPkg;
9984        PackageSetting oldPkgSetting;
9985        // reader
9986        synchronized (mPackages) {
9987            oldPkg = mPackages.get(packageName);
9988            oldPkgSetting = mSettings.mPackages.get(packageName);
9989            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9990                    (oldPkgSetting == null)) {
9991                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9992                        "Couldn't find package:" + packageName + " information");
9993                return;
9994            }
9995        }
9996
9997        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9998
9999        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10000        res.removedInfo.removedPackage = packageName;
10001        // Remove existing system package
10002        removePackageLI(oldPkgSetting, true);
10003        // writer
10004        synchronized (mPackages) {
10005            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10006                // We didn't need to disable the .apk as a current system package,
10007                // which means we are replacing another update that is already
10008                // installed.  We need to make sure to delete the older one's .apk.
10009                res.removedInfo.args = createInstallArgsForExisting(0,
10010                        deletedPackage.applicationInfo.getCodePath(),
10011                        deletedPackage.applicationInfo.getResourcePath(),
10012                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10013                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10014            } else {
10015                res.removedInfo.args = null;
10016            }
10017        }
10018
10019        // Successfully disabled the old package. Now proceed with re-installation
10020        deleteCodeCacheDirsLI(packageName);
10021
10022        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10023        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10024
10025        PackageParser.Package newPackage = null;
10026        try {
10027            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10028            if (newPackage.mExtras != null) {
10029                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10030                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10031                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10032
10033                // is the update attempting to change shared user? that isn't going to work...
10034                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10035                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10036                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10037                            + " to " + newPkgSetting.sharedUser);
10038                    updatedSettings = true;
10039                }
10040            }
10041
10042            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10043                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10044                updatedSettings = true;
10045            }
10046
10047        } catch (PackageManagerException e) {
10048            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10049        }
10050
10051        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10052            // Re installation failed. Restore old information
10053            // Remove new pkg information
10054            if (newPackage != null) {
10055                removeInstalledPackageLI(newPackage, true);
10056            }
10057            // Add back the old system package
10058            try {
10059                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10060            } catch (PackageManagerException e) {
10061                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10062            }
10063            // Restore the old system information in Settings
10064            synchronized(mPackages) {
10065                if (updatedSettings) {
10066                    mSettings.enableSystemPackageLPw(packageName);
10067                    mSettings.setInstallerPackageName(packageName,
10068                            oldPkgSetting.installerPackageName);
10069                }
10070                mSettings.writeLPr();
10071            }
10072        }
10073    }
10074
10075    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10076            int[] allUsers, boolean[] perUserInstalled,
10077            PackageInstalledInfo res) {
10078        String pkgName = newPackage.packageName;
10079        synchronized (mPackages) {
10080            //write settings. the installStatus will be incomplete at this stage.
10081            //note that the new package setting would have already been
10082            //added to mPackages. It hasn't been persisted yet.
10083            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10084            mSettings.writeLPr();
10085        }
10086
10087        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10088
10089        synchronized (mPackages) {
10090            updatePermissionsLPw(newPackage.packageName, newPackage,
10091                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10092                            ? UPDATE_PERMISSIONS_ALL : 0));
10093            // For system-bundled packages, we assume that installing an upgraded version
10094            // of the package implies that the user actually wants to run that new code,
10095            // so we enable the package.
10096            if (isSystemApp(newPackage)) {
10097                // NB: implicit assumption that system package upgrades apply to all users
10098                if (DEBUG_INSTALL) {
10099                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10100                }
10101                PackageSetting ps = mSettings.mPackages.get(pkgName);
10102                if (ps != null) {
10103                    if (res.origUsers != null) {
10104                        for (int userHandle : res.origUsers) {
10105                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10106                                    userHandle, installerPackageName);
10107                        }
10108                    }
10109                    // Also convey the prior install/uninstall state
10110                    if (allUsers != null && perUserInstalled != null) {
10111                        for (int i = 0; i < allUsers.length; i++) {
10112                            if (DEBUG_INSTALL) {
10113                                Slog.d(TAG, "    user " + allUsers[i]
10114                                        + " => " + perUserInstalled[i]);
10115                            }
10116                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10117                        }
10118                        // these install state changes will be persisted in the
10119                        // upcoming call to mSettings.writeLPr().
10120                    }
10121                }
10122            }
10123            res.name = pkgName;
10124            res.uid = newPackage.applicationInfo.uid;
10125            res.pkg = newPackage;
10126            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10127            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10128            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10129            //to update install status
10130            mSettings.writeLPr();
10131        }
10132    }
10133
10134    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10135        final int installFlags = args.installFlags;
10136        String installerPackageName = args.installerPackageName;
10137        File tmpPackageFile = new File(args.getCodePath());
10138        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10139        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10140        boolean replace = false;
10141        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10142        // Result object to be returned
10143        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10144
10145        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10146        // Retrieve PackageSettings and parse package
10147        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10148                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10149                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10150        PackageParser pp = new PackageParser();
10151        pp.setSeparateProcesses(mSeparateProcesses);
10152        pp.setDisplayMetrics(mMetrics);
10153
10154        final PackageParser.Package pkg;
10155        try {
10156            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10157        } catch (PackageParserException e) {
10158            res.setError("Failed parse during installPackageLI", e);
10159            return;
10160        }
10161
10162        // Mark that we have an install time CPU ABI override.
10163        pkg.cpuAbiOverride = args.abiOverride;
10164
10165        String pkgName = res.name = pkg.packageName;
10166        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10167            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10168                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10169                return;
10170            }
10171        }
10172
10173        try {
10174            pp.collectCertificates(pkg, parseFlags);
10175            pp.collectManifestDigest(pkg);
10176        } catch (PackageParserException e) {
10177            res.setError("Failed collect during installPackageLI", e);
10178            return;
10179        }
10180
10181        /* If the installer passed in a manifest digest, compare it now. */
10182        if (args.manifestDigest != null) {
10183            if (DEBUG_INSTALL) {
10184                final String parsedManifest = pkg.manifestDigest == null ? "null"
10185                        : pkg.manifestDigest.toString();
10186                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10187                        + parsedManifest);
10188            }
10189
10190            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10191                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10192                return;
10193            }
10194        } else if (DEBUG_INSTALL) {
10195            final String parsedManifest = pkg.manifestDigest == null
10196                    ? "null" : pkg.manifestDigest.toString();
10197            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10198        }
10199
10200        // Get rid of all references to package scan path via parser.
10201        pp = null;
10202        String oldCodePath = null;
10203        boolean systemApp = false;
10204        synchronized (mPackages) {
10205            // Check whether the newly-scanned package wants to define an already-defined perm
10206            int N = pkg.permissions.size();
10207            for (int i = N-1; i >= 0; i--) {
10208                PackageParser.Permission perm = pkg.permissions.get(i);
10209                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10210                if (bp != null) {
10211                    // If the defining package is signed with our cert, it's okay.  This
10212                    // also includes the "updating the same package" case, of course.
10213                    // "updating same package" could also involve key-rotation.
10214                    final boolean sigsOk;
10215                    if (!bp.sourcePackage.equals(pkg.packageName)
10216                            || !(bp.packageSetting instanceof PackageSetting)
10217                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10218                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10219                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10220                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10221                    } else {
10222                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10223                    }
10224                    if (!sigsOk) {
10225                        // If the owning package is the system itself, we log but allow
10226                        // install to proceed; we fail the install on all other permission
10227                        // redefinitions.
10228                        if (!bp.sourcePackage.equals("android")) {
10229                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10230                                    + pkg.packageName + " attempting to redeclare permission "
10231                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10232                            res.origPermission = perm.info.name;
10233                            res.origPackage = bp.sourcePackage;
10234                            return;
10235                        } else {
10236                            Slog.w(TAG, "Package " + pkg.packageName
10237                                    + " attempting to redeclare system permission "
10238                                    + perm.info.name + "; ignoring new declaration");
10239                            pkg.permissions.remove(i);
10240                        }
10241                    }
10242                }
10243            }
10244
10245            // Check if installing already existing package
10246            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10247                String oldName = mSettings.mRenamedPackages.get(pkgName);
10248                if (pkg.mOriginalPackages != null
10249                        && pkg.mOriginalPackages.contains(oldName)
10250                        && mPackages.containsKey(oldName)) {
10251                    // This package is derived from an original package,
10252                    // and this device has been updating from that original
10253                    // name.  We must continue using the original name, so
10254                    // rename the new package here.
10255                    pkg.setPackageName(oldName);
10256                    pkgName = pkg.packageName;
10257                    replace = true;
10258                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10259                            + oldName + " pkgName=" + pkgName);
10260                } else if (mPackages.containsKey(pkgName)) {
10261                    // This package, under its official name, already exists
10262                    // on the device; we should replace it.
10263                    replace = true;
10264                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10265                }
10266            }
10267            PackageSetting ps = mSettings.mPackages.get(pkgName);
10268            if (ps != null) {
10269                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10270                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10271                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10272                    systemApp = (ps.pkg.applicationInfo.flags &
10273                            ApplicationInfo.FLAG_SYSTEM) != 0;
10274                }
10275                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10276            }
10277        }
10278
10279        if (systemApp && onSd) {
10280            // Disable updates to system apps on sdcard
10281            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10282                    "Cannot install updates to system apps on sdcard");
10283            return;
10284        }
10285
10286        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10287            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10288            return;
10289        }
10290
10291        if (replace) {
10292            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10293                    installerPackageName, res);
10294        } else {
10295            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10296                    args.user, installerPackageName, res);
10297        }
10298        synchronized (mPackages) {
10299            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10300            if (ps != null) {
10301                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10302            }
10303        }
10304    }
10305
10306    private static boolean isForwardLocked(PackageParser.Package pkg) {
10307        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10308    }
10309
10310    private static boolean isForwardLocked(ApplicationInfo info) {
10311        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10312    }
10313
10314    private boolean isForwardLocked(PackageSetting ps) {
10315        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10316    }
10317
10318    private static boolean isMultiArch(PackageSetting ps) {
10319        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10320    }
10321
10322    private static boolean isMultiArch(ApplicationInfo info) {
10323        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10324    }
10325
10326    private static boolean isExternal(PackageParser.Package pkg) {
10327        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10328    }
10329
10330    private static boolean isExternal(PackageSetting ps) {
10331        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10332    }
10333
10334    private static boolean isExternal(ApplicationInfo info) {
10335        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10336    }
10337
10338    private static boolean isSystemApp(PackageParser.Package pkg) {
10339        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10340    }
10341
10342    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10343        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10344    }
10345
10346    private static boolean isSystemApp(ApplicationInfo info) {
10347        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10348    }
10349
10350    private static boolean isSystemApp(PackageSetting ps) {
10351        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10352    }
10353
10354    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10355        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10356    }
10357
10358    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10359        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10360    }
10361
10362    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10363        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10364    }
10365
10366    private int packageFlagsToInstallFlags(PackageSetting ps) {
10367        int installFlags = 0;
10368        if (isExternal(ps)) {
10369            installFlags |= PackageManager.INSTALL_EXTERNAL;
10370        }
10371        if (isForwardLocked(ps)) {
10372            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10373        }
10374        return installFlags;
10375    }
10376
10377    private void deleteTempPackageFiles() {
10378        final FilenameFilter filter = new FilenameFilter() {
10379            public boolean accept(File dir, String name) {
10380                return name.startsWith("vmdl") && name.endsWith(".tmp");
10381            }
10382        };
10383        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10384            file.delete();
10385        }
10386    }
10387
10388    @Override
10389    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10390            int flags) {
10391        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10392                flags);
10393    }
10394
10395    @Override
10396    public void deletePackage(final String packageName,
10397            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10398        mContext.enforceCallingOrSelfPermission(
10399                android.Manifest.permission.DELETE_PACKAGES, null);
10400        final int uid = Binder.getCallingUid();
10401        if (UserHandle.getUserId(uid) != userId) {
10402            mContext.enforceCallingPermission(
10403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10404                    "deletePackage for user " + userId);
10405        }
10406        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10407            try {
10408                observer.onPackageDeleted(packageName,
10409                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10410            } catch (RemoteException re) {
10411            }
10412            return;
10413        }
10414
10415        boolean uninstallBlocked = false;
10416        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10417            int[] users = sUserManager.getUserIds();
10418            for (int i = 0; i < users.length; ++i) {
10419                if (getBlockUninstallForUser(packageName, users[i])) {
10420                    uninstallBlocked = true;
10421                    break;
10422                }
10423            }
10424        } else {
10425            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10426        }
10427        if (uninstallBlocked) {
10428            try {
10429                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10430                        null);
10431            } catch (RemoteException re) {
10432            }
10433            return;
10434        }
10435
10436        if (DEBUG_REMOVE) {
10437            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10438        }
10439        // Queue up an async operation since the package deletion may take a little while.
10440        mHandler.post(new Runnable() {
10441            public void run() {
10442                mHandler.removeCallbacks(this);
10443                final int returnCode = deletePackageX(packageName, userId, flags);
10444                if (observer != null) {
10445                    try {
10446                        observer.onPackageDeleted(packageName, returnCode, null);
10447                    } catch (RemoteException e) {
10448                        Log.i(TAG, "Observer no longer exists.");
10449                    } //end catch
10450                } //end if
10451            } //end run
10452        });
10453    }
10454
10455    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10456        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10457                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10458        try {
10459            if (dpm != null) {
10460                if (dpm.isDeviceOwner(packageName)) {
10461                    return true;
10462                }
10463                int[] users;
10464                if (userId == UserHandle.USER_ALL) {
10465                    users = sUserManager.getUserIds();
10466                } else {
10467                    users = new int[]{userId};
10468                }
10469                for (int i = 0; i < users.length; ++i) {
10470                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10471                        return true;
10472                    }
10473                }
10474            }
10475        } catch (RemoteException e) {
10476        }
10477        return false;
10478    }
10479
10480    /**
10481     *  This method is an internal method that could be get invoked either
10482     *  to delete an installed package or to clean up a failed installation.
10483     *  After deleting an installed package, a broadcast is sent to notify any
10484     *  listeners that the package has been installed. For cleaning up a failed
10485     *  installation, the broadcast is not necessary since the package's
10486     *  installation wouldn't have sent the initial broadcast either
10487     *  The key steps in deleting a package are
10488     *  deleting the package information in internal structures like mPackages,
10489     *  deleting the packages base directories through installd
10490     *  updating mSettings to reflect current status
10491     *  persisting settings for later use
10492     *  sending a broadcast if necessary
10493     */
10494    private int deletePackageX(String packageName, int userId, int flags) {
10495        final PackageRemovedInfo info = new PackageRemovedInfo();
10496        final boolean res;
10497
10498        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10499                ? UserHandle.ALL : new UserHandle(userId);
10500
10501        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10502            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10503            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10504        }
10505
10506        boolean removedForAllUsers = false;
10507        boolean systemUpdate = false;
10508
10509        // for the uninstall-updates case and restricted profiles, remember the per-
10510        // userhandle installed state
10511        int[] allUsers;
10512        boolean[] perUserInstalled;
10513        synchronized (mPackages) {
10514            PackageSetting ps = mSettings.mPackages.get(packageName);
10515            allUsers = sUserManager.getUserIds();
10516            perUserInstalled = new boolean[allUsers.length];
10517            for (int i = 0; i < allUsers.length; i++) {
10518                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10519            }
10520        }
10521
10522        synchronized (mInstallLock) {
10523            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10524            res = deletePackageLI(packageName, removeForUser,
10525                    true, allUsers, perUserInstalled,
10526                    flags | REMOVE_CHATTY, info, true);
10527            systemUpdate = info.isRemovedPackageSystemUpdate;
10528            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10529                removedForAllUsers = true;
10530            }
10531            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10532                    + " removedForAllUsers=" + removedForAllUsers);
10533        }
10534
10535        if (res) {
10536            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10537
10538            // If the removed package was a system update, the old system package
10539            // was re-enabled; we need to broadcast this information
10540            if (systemUpdate) {
10541                Bundle extras = new Bundle(1);
10542                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10543                        ? info.removedAppId : info.uid);
10544                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10545
10546                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10547                        extras, null, null, null);
10548                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10549                        extras, null, null, null);
10550                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10551                        null, packageName, null, null);
10552            }
10553        }
10554        // Force a gc here.
10555        Runtime.getRuntime().gc();
10556        // Delete the resources here after sending the broadcast to let
10557        // other processes clean up before deleting resources.
10558        if (info.args != null) {
10559            synchronized (mInstallLock) {
10560                info.args.doPostDeleteLI(true);
10561            }
10562        }
10563
10564        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10565    }
10566
10567    static class PackageRemovedInfo {
10568        String removedPackage;
10569        int uid = -1;
10570        int removedAppId = -1;
10571        int[] removedUsers = null;
10572        boolean isRemovedPackageSystemUpdate = false;
10573        // Clean up resources deleted packages.
10574        InstallArgs args = null;
10575
10576        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10577            Bundle extras = new Bundle(1);
10578            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10579            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10580            if (replacing) {
10581                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10582            }
10583            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10584            if (removedPackage != null) {
10585                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10586                        extras, null, null, removedUsers);
10587                if (fullRemove && !replacing) {
10588                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10589                            extras, null, null, removedUsers);
10590                }
10591            }
10592            if (removedAppId >= 0) {
10593                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10594                        removedUsers);
10595            }
10596        }
10597    }
10598
10599    /*
10600     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10601     * flag is not set, the data directory is removed as well.
10602     * make sure this flag is set for partially installed apps. If not its meaningless to
10603     * delete a partially installed application.
10604     */
10605    private void removePackageDataLI(PackageSetting ps,
10606            int[] allUserHandles, boolean[] perUserInstalled,
10607            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10608        String packageName = ps.name;
10609        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10610        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10611        // Retrieve object to delete permissions for shared user later on
10612        final PackageSetting deletedPs;
10613        // reader
10614        synchronized (mPackages) {
10615            deletedPs = mSettings.mPackages.get(packageName);
10616            if (outInfo != null) {
10617                outInfo.removedPackage = packageName;
10618                outInfo.removedUsers = deletedPs != null
10619                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10620                        : null;
10621            }
10622        }
10623        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10624            removeDataDirsLI(packageName);
10625            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10626        }
10627        // writer
10628        synchronized (mPackages) {
10629            if (deletedPs != null) {
10630                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10631                    if (outInfo != null) {
10632                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10633                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10634                    }
10635                    if (deletedPs != null) {
10636                        updatePermissionsLPw(deletedPs.name, null, 0);
10637                        if (deletedPs.sharedUser != null) {
10638                            // remove permissions associated with package
10639                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10640                        }
10641                    }
10642                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10643                }
10644                // make sure to preserve per-user disabled state if this removal was just
10645                // a downgrade of a system app to the factory package
10646                if (allUserHandles != null && perUserInstalled != null) {
10647                    if (DEBUG_REMOVE) {
10648                        Slog.d(TAG, "Propagating install state across downgrade");
10649                    }
10650                    for (int i = 0; i < allUserHandles.length; i++) {
10651                        if (DEBUG_REMOVE) {
10652                            Slog.d(TAG, "    user " + allUserHandles[i]
10653                                    + " => " + perUserInstalled[i]);
10654                        }
10655                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10656                    }
10657                }
10658            }
10659            // can downgrade to reader
10660            if (writeSettings) {
10661                // Save settings now
10662                mSettings.writeLPr();
10663            }
10664        }
10665        if (outInfo != null) {
10666            // A user ID was deleted here. Go through all users and remove it
10667            // from KeyStore.
10668            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10669        }
10670    }
10671
10672    static boolean locationIsPrivileged(File path) {
10673        try {
10674            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10675                    .getCanonicalPath();
10676            return path.getCanonicalPath().startsWith(privilegedAppDir);
10677        } catch (IOException e) {
10678            Slog.e(TAG, "Unable to access code path " + path);
10679        }
10680        return false;
10681    }
10682
10683    /*
10684     * Tries to delete system package.
10685     */
10686    private boolean deleteSystemPackageLI(PackageSetting newPs,
10687            int[] allUserHandles, boolean[] perUserInstalled,
10688            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10689        final boolean applyUserRestrictions
10690                = (allUserHandles != null) && (perUserInstalled != null);
10691        PackageSetting disabledPs = null;
10692        // Confirm if the system package has been updated
10693        // An updated system app can be deleted. This will also have to restore
10694        // the system pkg from system partition
10695        // reader
10696        synchronized (mPackages) {
10697            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10698        }
10699        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10700                + " disabledPs=" + disabledPs);
10701        if (disabledPs == null) {
10702            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10703            return false;
10704        } else if (DEBUG_REMOVE) {
10705            Slog.d(TAG, "Deleting system pkg from data partition");
10706        }
10707        if (DEBUG_REMOVE) {
10708            if (applyUserRestrictions) {
10709                Slog.d(TAG, "Remembering install states:");
10710                for (int i = 0; i < allUserHandles.length; i++) {
10711                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10712                }
10713            }
10714        }
10715        // Delete the updated package
10716        outInfo.isRemovedPackageSystemUpdate = true;
10717        if (disabledPs.versionCode < newPs.versionCode) {
10718            // Delete data for downgrades
10719            flags &= ~PackageManager.DELETE_KEEP_DATA;
10720        } else {
10721            // Preserve data by setting flag
10722            flags |= PackageManager.DELETE_KEEP_DATA;
10723        }
10724        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10725                allUserHandles, perUserInstalled, outInfo, writeSettings);
10726        if (!ret) {
10727            return false;
10728        }
10729        // writer
10730        synchronized (mPackages) {
10731            // Reinstate the old system package
10732            mSettings.enableSystemPackageLPw(newPs.name);
10733            // Remove any native libraries from the upgraded package.
10734            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10735        }
10736        // Install the system package
10737        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10738        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10739        if (locationIsPrivileged(disabledPs.codePath)) {
10740            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10741        }
10742
10743        final PackageParser.Package newPkg;
10744        try {
10745            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10746        } catch (PackageManagerException e) {
10747            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10748            return false;
10749        }
10750
10751        // writer
10752        synchronized (mPackages) {
10753            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10754            updatePermissionsLPw(newPkg.packageName, newPkg,
10755                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10756            if (applyUserRestrictions) {
10757                if (DEBUG_REMOVE) {
10758                    Slog.d(TAG, "Propagating install state across reinstall");
10759                }
10760                for (int i = 0; i < allUserHandles.length; i++) {
10761                    if (DEBUG_REMOVE) {
10762                        Slog.d(TAG, "    user " + allUserHandles[i]
10763                                + " => " + perUserInstalled[i]);
10764                    }
10765                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10766                }
10767                // Regardless of writeSettings we need to ensure that this restriction
10768                // state propagation is persisted
10769                mSettings.writeAllUsersPackageRestrictionsLPr();
10770            }
10771            // can downgrade to reader here
10772            if (writeSettings) {
10773                mSettings.writeLPr();
10774            }
10775        }
10776        return true;
10777    }
10778
10779    private boolean deleteInstalledPackageLI(PackageSetting ps,
10780            boolean deleteCodeAndResources, int flags,
10781            int[] allUserHandles, boolean[] perUserInstalled,
10782            PackageRemovedInfo outInfo, boolean writeSettings) {
10783        if (outInfo != null) {
10784            outInfo.uid = ps.appId;
10785        }
10786
10787        // Delete package data from internal structures and also remove data if flag is set
10788        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10789
10790        // Delete application code and resources
10791        if (deleteCodeAndResources && (outInfo != null)) {
10792            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10793                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10794                    getAppDexInstructionSets(ps));
10795            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10796        }
10797        return true;
10798    }
10799
10800    @Override
10801    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10802            int userId) {
10803        mContext.enforceCallingOrSelfPermission(
10804                android.Manifest.permission.DELETE_PACKAGES, null);
10805        synchronized (mPackages) {
10806            PackageSetting ps = mSettings.mPackages.get(packageName);
10807            if (ps == null) {
10808                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10809                return false;
10810            }
10811            if (!ps.getInstalled(userId)) {
10812                // Can't block uninstall for an app that is not installed or enabled.
10813                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10814                return false;
10815            }
10816            ps.setBlockUninstall(blockUninstall, userId);
10817            mSettings.writePackageRestrictionsLPr(userId);
10818        }
10819        return true;
10820    }
10821
10822    @Override
10823    public boolean getBlockUninstallForUser(String packageName, int userId) {
10824        synchronized (mPackages) {
10825            PackageSetting ps = mSettings.mPackages.get(packageName);
10826            if (ps == null) {
10827                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10828                return false;
10829            }
10830            return ps.getBlockUninstall(userId);
10831        }
10832    }
10833
10834    /*
10835     * This method handles package deletion in general
10836     */
10837    private boolean deletePackageLI(String packageName, UserHandle user,
10838            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10839            int flags, PackageRemovedInfo outInfo,
10840            boolean writeSettings) {
10841        if (packageName == null) {
10842            Slog.w(TAG, "Attempt to delete null packageName.");
10843            return false;
10844        }
10845        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10846        PackageSetting ps;
10847        boolean dataOnly = false;
10848        int removeUser = -1;
10849        int appId = -1;
10850        synchronized (mPackages) {
10851            ps = mSettings.mPackages.get(packageName);
10852            if (ps == null) {
10853                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10854                return false;
10855            }
10856            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10857                    && user.getIdentifier() != UserHandle.USER_ALL) {
10858                // The caller is asking that the package only be deleted for a single
10859                // user.  To do this, we just mark its uninstalled state and delete
10860                // its data.  If this is a system app, we only allow this to happen if
10861                // they have set the special DELETE_SYSTEM_APP which requests different
10862                // semantics than normal for uninstalling system apps.
10863                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10864                ps.setUserState(user.getIdentifier(),
10865                        COMPONENT_ENABLED_STATE_DEFAULT,
10866                        false, //installed
10867                        true,  //stopped
10868                        true,  //notLaunched
10869                        false, //hidden
10870                        null, null, null,
10871                        false // blockUninstall
10872                        );
10873                if (!isSystemApp(ps)) {
10874                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10875                        // Other user still have this package installed, so all
10876                        // we need to do is clear this user's data and save that
10877                        // it is uninstalled.
10878                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10879                        removeUser = user.getIdentifier();
10880                        appId = ps.appId;
10881                        mSettings.writePackageRestrictionsLPr(removeUser);
10882                    } else {
10883                        // We need to set it back to 'installed' so the uninstall
10884                        // broadcasts will be sent correctly.
10885                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10886                        ps.setInstalled(true, user.getIdentifier());
10887                    }
10888                } else {
10889                    // This is a system app, so we assume that the
10890                    // other users still have this package installed, so all
10891                    // we need to do is clear this user's data and save that
10892                    // it is uninstalled.
10893                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10894                    removeUser = user.getIdentifier();
10895                    appId = ps.appId;
10896                    mSettings.writePackageRestrictionsLPr(removeUser);
10897                }
10898            }
10899        }
10900
10901        if (removeUser >= 0) {
10902            // From above, we determined that we are deleting this only
10903            // for a single user.  Continue the work here.
10904            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10905            if (outInfo != null) {
10906                outInfo.removedPackage = packageName;
10907                outInfo.removedAppId = appId;
10908                outInfo.removedUsers = new int[] {removeUser};
10909            }
10910            mInstaller.clearUserData(packageName, removeUser);
10911            removeKeystoreDataIfNeeded(removeUser, appId);
10912            schedulePackageCleaning(packageName, removeUser, false);
10913            return true;
10914        }
10915
10916        if (dataOnly) {
10917            // Delete application data first
10918            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10919            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10920            return true;
10921        }
10922
10923        boolean ret = false;
10924        if (isSystemApp(ps)) {
10925            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10926            // When an updated system application is deleted we delete the existing resources as well and
10927            // fall back to existing code in system partition
10928            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10929                    flags, outInfo, writeSettings);
10930        } else {
10931            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10932            // Kill application pre-emptively especially for apps on sd.
10933            killApplication(packageName, ps.appId, "uninstall pkg");
10934            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10935                    allUserHandles, perUserInstalled,
10936                    outInfo, writeSettings);
10937        }
10938
10939        return ret;
10940    }
10941
10942    private final class ClearStorageConnection implements ServiceConnection {
10943        IMediaContainerService mContainerService;
10944
10945        @Override
10946        public void onServiceConnected(ComponentName name, IBinder service) {
10947            synchronized (this) {
10948                mContainerService = IMediaContainerService.Stub.asInterface(service);
10949                notifyAll();
10950            }
10951        }
10952
10953        @Override
10954        public void onServiceDisconnected(ComponentName name) {
10955        }
10956    }
10957
10958    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10959        final boolean mounted;
10960        if (Environment.isExternalStorageEmulated()) {
10961            mounted = true;
10962        } else {
10963            final String status = Environment.getExternalStorageState();
10964
10965            mounted = status.equals(Environment.MEDIA_MOUNTED)
10966                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10967        }
10968
10969        if (!mounted) {
10970            return;
10971        }
10972
10973        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10974        int[] users;
10975        if (userId == UserHandle.USER_ALL) {
10976            users = sUserManager.getUserIds();
10977        } else {
10978            users = new int[] { userId };
10979        }
10980        final ClearStorageConnection conn = new ClearStorageConnection();
10981        if (mContext.bindServiceAsUser(
10982                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10983            try {
10984                for (int curUser : users) {
10985                    long timeout = SystemClock.uptimeMillis() + 5000;
10986                    synchronized (conn) {
10987                        long now = SystemClock.uptimeMillis();
10988                        while (conn.mContainerService == null && now < timeout) {
10989                            try {
10990                                conn.wait(timeout - now);
10991                            } catch (InterruptedException e) {
10992                            }
10993                        }
10994                    }
10995                    if (conn.mContainerService == null) {
10996                        return;
10997                    }
10998
10999                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11000                    clearDirectory(conn.mContainerService,
11001                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11002                    if (allData) {
11003                        clearDirectory(conn.mContainerService,
11004                                userEnv.buildExternalStorageAppDataDirs(packageName));
11005                        clearDirectory(conn.mContainerService,
11006                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11007                    }
11008                }
11009            } finally {
11010                mContext.unbindService(conn);
11011            }
11012        }
11013    }
11014
11015    @Override
11016    public void clearApplicationUserData(final String packageName,
11017            final IPackageDataObserver observer, final int userId) {
11018        mContext.enforceCallingOrSelfPermission(
11019                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11020        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11021        // Queue up an async operation since the package deletion may take a little while.
11022        mHandler.post(new Runnable() {
11023            public void run() {
11024                mHandler.removeCallbacks(this);
11025                final boolean succeeded;
11026                synchronized (mInstallLock) {
11027                    succeeded = clearApplicationUserDataLI(packageName, userId);
11028                }
11029                clearExternalStorageDataSync(packageName, userId, true);
11030                if (succeeded) {
11031                    // invoke DeviceStorageMonitor's update method to clear any notifications
11032                    DeviceStorageMonitorInternal
11033                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11034                    if (dsm != null) {
11035                        dsm.checkMemory();
11036                    }
11037                }
11038                if(observer != null) {
11039                    try {
11040                        observer.onRemoveCompleted(packageName, succeeded);
11041                    } catch (RemoteException e) {
11042                        Log.i(TAG, "Observer no longer exists.");
11043                    }
11044                } //end if observer
11045            } //end run
11046        });
11047    }
11048
11049    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11050        if (packageName == null) {
11051            Slog.w(TAG, "Attempt to delete null packageName.");
11052            return false;
11053        }
11054
11055        // Try finding details about the requested package
11056        PackageParser.Package pkg;
11057        synchronized (mPackages) {
11058            pkg = mPackages.get(packageName);
11059            if (pkg == null) {
11060                final PackageSetting ps = mSettings.mPackages.get(packageName);
11061                if (ps != null) {
11062                    pkg = ps.pkg;
11063                }
11064            }
11065        }
11066
11067        if (pkg == null) {
11068            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11069        }
11070
11071        // Always delete data directories for package, even if we found no other
11072        // record of app. This helps users recover from UID mismatches without
11073        // resorting to a full data wipe.
11074        int retCode = mInstaller.clearUserData(packageName, userId);
11075        if (retCode < 0) {
11076            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11077            return false;
11078        }
11079
11080        if (pkg == null) {
11081            return false;
11082        }
11083
11084        if (pkg != null && pkg.applicationInfo != null) {
11085            final int appId = pkg.applicationInfo.uid;
11086            removeKeystoreDataIfNeeded(userId, appId);
11087        }
11088
11089        // Create a native library symlink only if we have native libraries
11090        // and if the native libraries are 32 bit libraries. We do not provide
11091        // this symlink for 64 bit libraries.
11092        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11093                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11094            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11095            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11096                Slog.w(TAG, "Failed linking native library dir");
11097                return false;
11098            }
11099        }
11100
11101        return true;
11102    }
11103
11104    /**
11105     * Remove entries from the keystore daemon. Will only remove it if the
11106     * {@code appId} is valid.
11107     */
11108    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11109        if (appId < 0) {
11110            return;
11111        }
11112
11113        final KeyStore keyStore = KeyStore.getInstance();
11114        if (keyStore != null) {
11115            if (userId == UserHandle.USER_ALL) {
11116                for (final int individual : sUserManager.getUserIds()) {
11117                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11118                }
11119            } else {
11120                keyStore.clearUid(UserHandle.getUid(userId, appId));
11121            }
11122        } else {
11123            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11124        }
11125    }
11126
11127    @Override
11128    public void deleteApplicationCacheFiles(final String packageName,
11129            final IPackageDataObserver observer) {
11130        mContext.enforceCallingOrSelfPermission(
11131                android.Manifest.permission.DELETE_CACHE_FILES, null);
11132        // Queue up an async operation since the package deletion may take a little while.
11133        final int userId = UserHandle.getCallingUserId();
11134        mHandler.post(new Runnable() {
11135            public void run() {
11136                mHandler.removeCallbacks(this);
11137                final boolean succeded;
11138                synchronized (mInstallLock) {
11139                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11140                }
11141                clearExternalStorageDataSync(packageName, userId, false);
11142                if(observer != null) {
11143                    try {
11144                        observer.onRemoveCompleted(packageName, succeded);
11145                    } catch (RemoteException e) {
11146                        Log.i(TAG, "Observer no longer exists.");
11147                    }
11148                } //end if observer
11149            } //end run
11150        });
11151    }
11152
11153    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11154        if (packageName == null) {
11155            Slog.w(TAG, "Attempt to delete null packageName.");
11156            return false;
11157        }
11158        PackageParser.Package p;
11159        synchronized (mPackages) {
11160            p = mPackages.get(packageName);
11161        }
11162        if (p == null) {
11163            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11164            return false;
11165        }
11166        final ApplicationInfo applicationInfo = p.applicationInfo;
11167        if (applicationInfo == null) {
11168            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11169            return false;
11170        }
11171        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11172        if (retCode < 0) {
11173            Slog.w(TAG, "Couldn't remove cache files for package: "
11174                       + packageName + " u" + userId);
11175            return false;
11176        }
11177        return true;
11178    }
11179
11180    @Override
11181    public void getPackageSizeInfo(final String packageName, int userHandle,
11182            final IPackageStatsObserver observer) {
11183        mContext.enforceCallingOrSelfPermission(
11184                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11185        if (packageName == null) {
11186            throw new IllegalArgumentException("Attempt to get size of null packageName");
11187        }
11188
11189        PackageStats stats = new PackageStats(packageName, userHandle);
11190
11191        /*
11192         * Queue up an async operation since the package measurement may take a
11193         * little while.
11194         */
11195        Message msg = mHandler.obtainMessage(INIT_COPY);
11196        msg.obj = new MeasureParams(stats, observer);
11197        mHandler.sendMessage(msg);
11198    }
11199
11200    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11201            PackageStats pStats) {
11202        if (packageName == null) {
11203            Slog.w(TAG, "Attempt to get size of null packageName.");
11204            return false;
11205        }
11206        PackageParser.Package p;
11207        boolean dataOnly = false;
11208        String libDirRoot = null;
11209        String asecPath = null;
11210        PackageSetting ps = null;
11211        synchronized (mPackages) {
11212            p = mPackages.get(packageName);
11213            ps = mSettings.mPackages.get(packageName);
11214            if(p == null) {
11215                dataOnly = true;
11216                if((ps == null) || (ps.pkg == null)) {
11217                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11218                    return false;
11219                }
11220                p = ps.pkg;
11221            }
11222            if (ps != null) {
11223                libDirRoot = ps.legacyNativeLibraryPathString;
11224            }
11225            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11226                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11227                if (secureContainerId != null) {
11228                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11229                }
11230            }
11231        }
11232        String publicSrcDir = null;
11233        if(!dataOnly) {
11234            final ApplicationInfo applicationInfo = p.applicationInfo;
11235            if (applicationInfo == null) {
11236                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11237                return false;
11238            }
11239            if (isForwardLocked(p)) {
11240                publicSrcDir = applicationInfo.getBaseResourcePath();
11241            }
11242        }
11243        // TODO: extend to measure size of split APKs
11244        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11245        // not just the first level.
11246        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11247        // just the primary.
11248        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11249        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11250                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11251        if (res < 0) {
11252            return false;
11253        }
11254
11255        // Fix-up for forward-locked applications in ASEC containers.
11256        if (!isExternal(p)) {
11257            pStats.codeSize += pStats.externalCodeSize;
11258            pStats.externalCodeSize = 0L;
11259        }
11260
11261        return true;
11262    }
11263
11264
11265    @Override
11266    public void addPackageToPreferred(String packageName) {
11267        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11268    }
11269
11270    @Override
11271    public void removePackageFromPreferred(String packageName) {
11272        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11273    }
11274
11275    @Override
11276    public List<PackageInfo> getPreferredPackages(int flags) {
11277        return new ArrayList<PackageInfo>();
11278    }
11279
11280    private int getUidTargetSdkVersionLockedLPr(int uid) {
11281        Object obj = mSettings.getUserIdLPr(uid);
11282        if (obj instanceof SharedUserSetting) {
11283            final SharedUserSetting sus = (SharedUserSetting) obj;
11284            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11285            final Iterator<PackageSetting> it = sus.packages.iterator();
11286            while (it.hasNext()) {
11287                final PackageSetting ps = it.next();
11288                if (ps.pkg != null) {
11289                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11290                    if (v < vers) vers = v;
11291                }
11292            }
11293            return vers;
11294        } else if (obj instanceof PackageSetting) {
11295            final PackageSetting ps = (PackageSetting) obj;
11296            if (ps.pkg != null) {
11297                return ps.pkg.applicationInfo.targetSdkVersion;
11298            }
11299        }
11300        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11301    }
11302
11303    @Override
11304    public void addPreferredActivity(IntentFilter filter, int match,
11305            ComponentName[] set, ComponentName activity, int userId) {
11306        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11307                "Adding preferred");
11308    }
11309
11310    private void addPreferredActivityInternal(IntentFilter filter, int match,
11311            ComponentName[] set, ComponentName activity, boolean always, int userId,
11312            String opname) {
11313        // writer
11314        int callingUid = Binder.getCallingUid();
11315        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11316        if (filter.countActions() == 0) {
11317            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11318            return;
11319        }
11320        synchronized (mPackages) {
11321            if (mContext.checkCallingOrSelfPermission(
11322                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11323                    != PackageManager.PERMISSION_GRANTED) {
11324                if (getUidTargetSdkVersionLockedLPr(callingUid)
11325                        < Build.VERSION_CODES.FROYO) {
11326                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11327                            + callingUid);
11328                    return;
11329                }
11330                mContext.enforceCallingOrSelfPermission(
11331                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11332            }
11333
11334            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11335            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11336                    + userId + ":");
11337            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11338            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11339            mSettings.writePackageRestrictionsLPr(userId);
11340        }
11341    }
11342
11343    @Override
11344    public void replacePreferredActivity(IntentFilter filter, int match,
11345            ComponentName[] set, ComponentName activity, int userId) {
11346        if (filter.countActions() != 1) {
11347            throw new IllegalArgumentException(
11348                    "replacePreferredActivity expects filter to have only 1 action.");
11349        }
11350        if (filter.countDataAuthorities() != 0
11351                || filter.countDataPaths() != 0
11352                || filter.countDataSchemes() > 1
11353                || filter.countDataTypes() != 0) {
11354            throw new IllegalArgumentException(
11355                    "replacePreferredActivity expects filter to have no data authorities, " +
11356                    "paths, or types; and at most one scheme.");
11357        }
11358
11359        final int callingUid = Binder.getCallingUid();
11360        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11361        synchronized (mPackages) {
11362            if (mContext.checkCallingOrSelfPermission(
11363                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11364                    != PackageManager.PERMISSION_GRANTED) {
11365                if (getUidTargetSdkVersionLockedLPr(callingUid)
11366                        < Build.VERSION_CODES.FROYO) {
11367                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11368                            + Binder.getCallingUid());
11369                    return;
11370                }
11371                mContext.enforceCallingOrSelfPermission(
11372                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11373            }
11374
11375            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11376            if (pir != null) {
11377                // Get all of the existing entries that exactly match this filter.
11378                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11379                if (existing != null && existing.size() == 1) {
11380                    PreferredActivity cur = existing.get(0);
11381                    if (DEBUG_PREFERRED) {
11382                        Slog.i(TAG, "Checking replace of preferred:");
11383                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11384                        if (!cur.mPref.mAlways) {
11385                            Slog.i(TAG, "  -- CUR; not mAlways!");
11386                        } else {
11387                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11388                            Slog.i(TAG, "  -- CUR: mSet="
11389                                    + Arrays.toString(cur.mPref.mSetComponents));
11390                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11391                            Slog.i(TAG, "  -- NEW: mMatch="
11392                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11393                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11394                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11395                        }
11396                    }
11397                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11398                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11399                            && cur.mPref.sameSet(set)) {
11400                        // Setting the preferred activity to what it happens to be already
11401                        if (DEBUG_PREFERRED) {
11402                            Slog.i(TAG, "Replacing with same preferred activity "
11403                                    + cur.mPref.mShortComponent + " for user "
11404                                    + userId + ":");
11405                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11406                        }
11407                        return;
11408                    }
11409                }
11410
11411                if (existing != null) {
11412                    if (DEBUG_PREFERRED) {
11413                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11414                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11415                    }
11416                    for (int i = 0; i < existing.size(); i++) {
11417                        PreferredActivity pa = existing.get(i);
11418                        if (DEBUG_PREFERRED) {
11419                            Slog.i(TAG, "Removing existing preferred activity "
11420                                    + pa.mPref.mComponent + ":");
11421                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11422                        }
11423                        pir.removeFilter(pa);
11424                    }
11425                }
11426            }
11427            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11428                    "Replacing preferred");
11429        }
11430    }
11431
11432    @Override
11433    public void clearPackagePreferredActivities(String packageName) {
11434        final int uid = Binder.getCallingUid();
11435        // writer
11436        synchronized (mPackages) {
11437            PackageParser.Package pkg = mPackages.get(packageName);
11438            if (pkg == null || pkg.applicationInfo.uid != uid) {
11439                if (mContext.checkCallingOrSelfPermission(
11440                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11441                        != PackageManager.PERMISSION_GRANTED) {
11442                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11443                            < Build.VERSION_CODES.FROYO) {
11444                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11445                                + Binder.getCallingUid());
11446                        return;
11447                    }
11448                    mContext.enforceCallingOrSelfPermission(
11449                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11450                }
11451            }
11452
11453            int user = UserHandle.getCallingUserId();
11454            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11455                mSettings.writePackageRestrictionsLPr(user);
11456                scheduleWriteSettingsLocked();
11457            }
11458        }
11459    }
11460
11461    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11462    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11463        ArrayList<PreferredActivity> removed = null;
11464        boolean changed = false;
11465        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11466            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11467            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11468            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11469                continue;
11470            }
11471            Iterator<PreferredActivity> it = pir.filterIterator();
11472            while (it.hasNext()) {
11473                PreferredActivity pa = it.next();
11474                // Mark entry for removal only if it matches the package name
11475                // and the entry is of type "always".
11476                if (packageName == null ||
11477                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11478                                && pa.mPref.mAlways)) {
11479                    if (removed == null) {
11480                        removed = new ArrayList<PreferredActivity>();
11481                    }
11482                    removed.add(pa);
11483                }
11484            }
11485            if (removed != null) {
11486                for (int j=0; j<removed.size(); j++) {
11487                    PreferredActivity pa = removed.get(j);
11488                    pir.removeFilter(pa);
11489                }
11490                changed = true;
11491            }
11492        }
11493        return changed;
11494    }
11495
11496    @Override
11497    public void resetPreferredActivities(int userId) {
11498        /* TODO: Actually use userId. Why is it being passed in? */
11499        mContext.enforceCallingOrSelfPermission(
11500                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11501        // writer
11502        synchronized (mPackages) {
11503            int user = UserHandle.getCallingUserId();
11504            clearPackagePreferredActivitiesLPw(null, user);
11505            mSettings.readDefaultPreferredAppsLPw(this, user);
11506            mSettings.writePackageRestrictionsLPr(user);
11507            scheduleWriteSettingsLocked();
11508        }
11509    }
11510
11511    @Override
11512    public int getPreferredActivities(List<IntentFilter> outFilters,
11513            List<ComponentName> outActivities, String packageName) {
11514
11515        int num = 0;
11516        final int userId = UserHandle.getCallingUserId();
11517        // reader
11518        synchronized (mPackages) {
11519            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11520            if (pir != null) {
11521                final Iterator<PreferredActivity> it = pir.filterIterator();
11522                while (it.hasNext()) {
11523                    final PreferredActivity pa = it.next();
11524                    if (packageName == null
11525                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11526                                    && pa.mPref.mAlways)) {
11527                        if (outFilters != null) {
11528                            outFilters.add(new IntentFilter(pa));
11529                        }
11530                        if (outActivities != null) {
11531                            outActivities.add(pa.mPref.mComponent);
11532                        }
11533                    }
11534                }
11535            }
11536        }
11537
11538        return num;
11539    }
11540
11541    @Override
11542    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11543            int userId) {
11544        int callingUid = Binder.getCallingUid();
11545        if (callingUid != Process.SYSTEM_UID) {
11546            throw new SecurityException(
11547                    "addPersistentPreferredActivity can only be run by the system");
11548        }
11549        if (filter.countActions() == 0) {
11550            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11551            return;
11552        }
11553        synchronized (mPackages) {
11554            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11555                    " :");
11556            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11557            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11558                    new PersistentPreferredActivity(filter, activity));
11559            mSettings.writePackageRestrictionsLPr(userId);
11560        }
11561    }
11562
11563    @Override
11564    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11565        int callingUid = Binder.getCallingUid();
11566        if (callingUid != Process.SYSTEM_UID) {
11567            throw new SecurityException(
11568                    "clearPackagePersistentPreferredActivities can only be run by the system");
11569        }
11570        ArrayList<PersistentPreferredActivity> removed = null;
11571        boolean changed = false;
11572        synchronized (mPackages) {
11573            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11574                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11575                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11576                        .valueAt(i);
11577                if (userId != thisUserId) {
11578                    continue;
11579                }
11580                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11581                while (it.hasNext()) {
11582                    PersistentPreferredActivity ppa = it.next();
11583                    // Mark entry for removal only if it matches the package name.
11584                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11585                        if (removed == null) {
11586                            removed = new ArrayList<PersistentPreferredActivity>();
11587                        }
11588                        removed.add(ppa);
11589                    }
11590                }
11591                if (removed != null) {
11592                    for (int j=0; j<removed.size(); j++) {
11593                        PersistentPreferredActivity ppa = removed.get(j);
11594                        ppir.removeFilter(ppa);
11595                    }
11596                    changed = true;
11597                }
11598            }
11599
11600            if (changed) {
11601                mSettings.writePackageRestrictionsLPr(userId);
11602            }
11603        }
11604    }
11605
11606    @Override
11607    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11608            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11609        mContext.enforceCallingOrSelfPermission(
11610                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11611        int callingUid = Binder.getCallingUid();
11612        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11613        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11614        if (intentFilter.countActions() == 0) {
11615            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11616            return;
11617        }
11618        synchronized (mPackages) {
11619            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11620                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11621            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11622            mSettings.writePackageRestrictionsLPr(sourceUserId);
11623        }
11624    }
11625
11626    @Override
11627    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11628            int ownerUserId) {
11629        mContext.enforceCallingOrSelfPermission(
11630                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11631        int callingUid = Binder.getCallingUid();
11632        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11633        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11634        int callingUserId = UserHandle.getUserId(callingUid);
11635        synchronized (mPackages) {
11636            CrossProfileIntentResolver resolver =
11637                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11638            HashSet<CrossProfileIntentFilter> set =
11639                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11640            for (CrossProfileIntentFilter filter : set) {
11641                if (filter.getOwnerPackage().equals(ownerPackage)
11642                        && filter.getOwnerUserId() == callingUserId) {
11643                    resolver.removeFilter(filter);
11644                }
11645            }
11646            mSettings.writePackageRestrictionsLPr(sourceUserId);
11647        }
11648    }
11649
11650    // Enforcing that callingUid is owning pkg on userId
11651    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11652        // The system owns everything.
11653        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11654            return;
11655        }
11656        int callingUserId = UserHandle.getUserId(callingUid);
11657        if (callingUserId != userId) {
11658            throw new SecurityException("calling uid " + callingUid
11659                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11660                    + callingUserId);
11661        }
11662        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11663        if (pi == null) {
11664            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11665                    + callingUserId);
11666        }
11667        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11668            throw new SecurityException("Calling uid " + callingUid
11669                    + " does not own package " + pkg);
11670        }
11671    }
11672
11673    @Override
11674    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11675        Intent intent = new Intent(Intent.ACTION_MAIN);
11676        intent.addCategory(Intent.CATEGORY_HOME);
11677
11678        final int callingUserId = UserHandle.getCallingUserId();
11679        List<ResolveInfo> list = queryIntentActivities(intent, null,
11680                PackageManager.GET_META_DATA, callingUserId);
11681        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11682                true, false, false, callingUserId);
11683
11684        allHomeCandidates.clear();
11685        if (list != null) {
11686            for (ResolveInfo ri : list) {
11687                allHomeCandidates.add(ri);
11688            }
11689        }
11690        return (preferred == null || preferred.activityInfo == null)
11691                ? null
11692                : new ComponentName(preferred.activityInfo.packageName,
11693                        preferred.activityInfo.name);
11694    }
11695
11696    @Override
11697    public void setApplicationEnabledSetting(String appPackageName,
11698            int newState, int flags, int userId, String callingPackage) {
11699        if (!sUserManager.exists(userId)) return;
11700        if (callingPackage == null) {
11701            callingPackage = Integer.toString(Binder.getCallingUid());
11702        }
11703        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11704    }
11705
11706    @Override
11707    public void setComponentEnabledSetting(ComponentName componentName,
11708            int newState, int flags, int userId) {
11709        if (!sUserManager.exists(userId)) return;
11710        setEnabledSetting(componentName.getPackageName(),
11711                componentName.getClassName(), newState, flags, userId, null);
11712    }
11713
11714    private void setEnabledSetting(final String packageName, String className, int newState,
11715            final int flags, int userId, String callingPackage) {
11716        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11717              || newState == COMPONENT_ENABLED_STATE_ENABLED
11718              || newState == COMPONENT_ENABLED_STATE_DISABLED
11719              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11720              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11721            throw new IllegalArgumentException("Invalid new component state: "
11722                    + newState);
11723        }
11724        PackageSetting pkgSetting;
11725        final int uid = Binder.getCallingUid();
11726        final int permission = mContext.checkCallingOrSelfPermission(
11727                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11728        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11729        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11730        boolean sendNow = false;
11731        boolean isApp = (className == null);
11732        String componentName = isApp ? packageName : className;
11733        int packageUid = -1;
11734        ArrayList<String> components;
11735
11736        // writer
11737        synchronized (mPackages) {
11738            pkgSetting = mSettings.mPackages.get(packageName);
11739            if (pkgSetting == null) {
11740                if (className == null) {
11741                    throw new IllegalArgumentException(
11742                            "Unknown package: " + packageName);
11743                }
11744                throw new IllegalArgumentException(
11745                        "Unknown component: " + packageName
11746                        + "/" + className);
11747            }
11748            // Allow root and verify that userId is not being specified by a different user
11749            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11750                throw new SecurityException(
11751                        "Permission Denial: attempt to change component state from pid="
11752                        + Binder.getCallingPid()
11753                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11754            }
11755            if (className == null) {
11756                // We're dealing with an application/package level state change
11757                if (pkgSetting.getEnabled(userId) == newState) {
11758                    // Nothing to do
11759                    return;
11760                }
11761                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11762                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11763                    // Don't care about who enables an app.
11764                    callingPackage = null;
11765                }
11766                pkgSetting.setEnabled(newState, userId, callingPackage);
11767                // pkgSetting.pkg.mSetEnabled = newState;
11768            } else {
11769                // We're dealing with a component level state change
11770                // First, verify that this is a valid class name.
11771                PackageParser.Package pkg = pkgSetting.pkg;
11772                if (pkg == null || !pkg.hasComponentClassName(className)) {
11773                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11774                        throw new IllegalArgumentException("Component class " + className
11775                                + " does not exist in " + packageName);
11776                    } else {
11777                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11778                                + className + " does not exist in " + packageName);
11779                    }
11780                }
11781                switch (newState) {
11782                case COMPONENT_ENABLED_STATE_ENABLED:
11783                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11784                        return;
11785                    }
11786                    break;
11787                case COMPONENT_ENABLED_STATE_DISABLED:
11788                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11789                        return;
11790                    }
11791                    break;
11792                case COMPONENT_ENABLED_STATE_DEFAULT:
11793                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11794                        return;
11795                    }
11796                    break;
11797                default:
11798                    Slog.e(TAG, "Invalid new component state: " + newState);
11799                    return;
11800                }
11801            }
11802            mSettings.writePackageRestrictionsLPr(userId);
11803            components = mPendingBroadcasts.get(userId, packageName);
11804            final boolean newPackage = components == null;
11805            if (newPackage) {
11806                components = new ArrayList<String>();
11807            }
11808            if (!components.contains(componentName)) {
11809                components.add(componentName);
11810            }
11811            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11812                sendNow = true;
11813                // Purge entry from pending broadcast list if another one exists already
11814                // since we are sending one right away.
11815                mPendingBroadcasts.remove(userId, packageName);
11816            } else {
11817                if (newPackage) {
11818                    mPendingBroadcasts.put(userId, packageName, components);
11819                }
11820                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11821                    // Schedule a message
11822                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11823                }
11824            }
11825        }
11826
11827        long callingId = Binder.clearCallingIdentity();
11828        try {
11829            if (sendNow) {
11830                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11831                sendPackageChangedBroadcast(packageName,
11832                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11833            }
11834        } finally {
11835            Binder.restoreCallingIdentity(callingId);
11836        }
11837    }
11838
11839    private void sendPackageChangedBroadcast(String packageName,
11840            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11841        if (DEBUG_INSTALL)
11842            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11843                    + componentNames);
11844        Bundle extras = new Bundle(4);
11845        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11846        String nameList[] = new String[componentNames.size()];
11847        componentNames.toArray(nameList);
11848        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11849        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11850        extras.putInt(Intent.EXTRA_UID, packageUid);
11851        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11852                new int[] {UserHandle.getUserId(packageUid)});
11853    }
11854
11855    @Override
11856    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11857        if (!sUserManager.exists(userId)) return;
11858        final int uid = Binder.getCallingUid();
11859        final int permission = mContext.checkCallingOrSelfPermission(
11860                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11861        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11862        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11863        // writer
11864        synchronized (mPackages) {
11865            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11866                    uid, userId)) {
11867                scheduleWritePackageRestrictionsLocked(userId);
11868            }
11869        }
11870    }
11871
11872    @Override
11873    public String getInstallerPackageName(String packageName) {
11874        // reader
11875        synchronized (mPackages) {
11876            return mSettings.getInstallerPackageNameLPr(packageName);
11877        }
11878    }
11879
11880    @Override
11881    public int getApplicationEnabledSetting(String packageName, int userId) {
11882        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11883        int uid = Binder.getCallingUid();
11884        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11885        // reader
11886        synchronized (mPackages) {
11887            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11888        }
11889    }
11890
11891    @Override
11892    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11893        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11894        int uid = Binder.getCallingUid();
11895        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11896        // reader
11897        synchronized (mPackages) {
11898            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11899        }
11900    }
11901
11902    @Override
11903    public void enterSafeMode() {
11904        enforceSystemOrRoot("Only the system can request entering safe mode");
11905
11906        if (!mSystemReady) {
11907            mSafeMode = true;
11908        }
11909    }
11910
11911    @Override
11912    public void systemReady() {
11913        mSystemReady = true;
11914
11915        // Read the compatibilty setting when the system is ready.
11916        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11917                mContext.getContentResolver(),
11918                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11919        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11920        if (DEBUG_SETTINGS) {
11921            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11922        }
11923
11924        synchronized (mPackages) {
11925            // Verify that all of the preferred activity components actually
11926            // exist.  It is possible for applications to be updated and at
11927            // that point remove a previously declared activity component that
11928            // had been set as a preferred activity.  We try to clean this up
11929            // the next time we encounter that preferred activity, but it is
11930            // possible for the user flow to never be able to return to that
11931            // situation so here we do a sanity check to make sure we haven't
11932            // left any junk around.
11933            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11934            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11935                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11936                removed.clear();
11937                for (PreferredActivity pa : pir.filterSet()) {
11938                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11939                        removed.add(pa);
11940                    }
11941                }
11942                if (removed.size() > 0) {
11943                    for (int r=0; r<removed.size(); r++) {
11944                        PreferredActivity pa = removed.get(r);
11945                        Slog.w(TAG, "Removing dangling preferred activity: "
11946                                + pa.mPref.mComponent);
11947                        pir.removeFilter(pa);
11948                    }
11949                    mSettings.writePackageRestrictionsLPr(
11950                            mSettings.mPreferredActivities.keyAt(i));
11951                }
11952            }
11953        }
11954        sUserManager.systemReady();
11955
11956        // Kick off any messages waiting for system ready
11957        if (mPostSystemReadyMessages != null) {
11958            for (Message msg : mPostSystemReadyMessages) {
11959                msg.sendToTarget();
11960            }
11961            mPostSystemReadyMessages = null;
11962        }
11963    }
11964
11965    @Override
11966    public boolean isSafeMode() {
11967        return mSafeMode;
11968    }
11969
11970    @Override
11971    public boolean hasSystemUidErrors() {
11972        return mHasSystemUidErrors;
11973    }
11974
11975    static String arrayToString(int[] array) {
11976        StringBuffer buf = new StringBuffer(128);
11977        buf.append('[');
11978        if (array != null) {
11979            for (int i=0; i<array.length; i++) {
11980                if (i > 0) buf.append(", ");
11981                buf.append(array[i]);
11982            }
11983        }
11984        buf.append(']');
11985        return buf.toString();
11986    }
11987
11988    static class DumpState {
11989        public static final int DUMP_LIBS = 1 << 0;
11990        public static final int DUMP_FEATURES = 1 << 1;
11991        public static final int DUMP_RESOLVERS = 1 << 2;
11992        public static final int DUMP_PERMISSIONS = 1 << 3;
11993        public static final int DUMP_PACKAGES = 1 << 4;
11994        public static final int DUMP_SHARED_USERS = 1 << 5;
11995        public static final int DUMP_MESSAGES = 1 << 6;
11996        public static final int DUMP_PROVIDERS = 1 << 7;
11997        public static final int DUMP_VERIFIERS = 1 << 8;
11998        public static final int DUMP_PREFERRED = 1 << 9;
11999        public static final int DUMP_PREFERRED_XML = 1 << 10;
12000        public static final int DUMP_KEYSETS = 1 << 11;
12001        public static final int DUMP_VERSION = 1 << 12;
12002        public static final int DUMP_INSTALLS = 1 << 13;
12003
12004        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12005
12006        private int mTypes;
12007
12008        private int mOptions;
12009
12010        private boolean mTitlePrinted;
12011
12012        private SharedUserSetting mSharedUser;
12013
12014        public boolean isDumping(int type) {
12015            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12016                return true;
12017            }
12018
12019            return (mTypes & type) != 0;
12020        }
12021
12022        public void setDump(int type) {
12023            mTypes |= type;
12024        }
12025
12026        public boolean isOptionEnabled(int option) {
12027            return (mOptions & option) != 0;
12028        }
12029
12030        public void setOptionEnabled(int option) {
12031            mOptions |= option;
12032        }
12033
12034        public boolean onTitlePrinted() {
12035            final boolean printed = mTitlePrinted;
12036            mTitlePrinted = true;
12037            return printed;
12038        }
12039
12040        public boolean getTitlePrinted() {
12041            return mTitlePrinted;
12042        }
12043
12044        public void setTitlePrinted(boolean enabled) {
12045            mTitlePrinted = enabled;
12046        }
12047
12048        public SharedUserSetting getSharedUser() {
12049            return mSharedUser;
12050        }
12051
12052        public void setSharedUser(SharedUserSetting user) {
12053            mSharedUser = user;
12054        }
12055    }
12056
12057    @Override
12058    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12059        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12060                != PackageManager.PERMISSION_GRANTED) {
12061            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12062                    + Binder.getCallingPid()
12063                    + ", uid=" + Binder.getCallingUid()
12064                    + " without permission "
12065                    + android.Manifest.permission.DUMP);
12066            return;
12067        }
12068
12069        DumpState dumpState = new DumpState();
12070        boolean fullPreferred = false;
12071        boolean checkin = false;
12072
12073        String packageName = null;
12074
12075        int opti = 0;
12076        while (opti < args.length) {
12077            String opt = args[opti];
12078            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12079                break;
12080            }
12081            opti++;
12082            if ("-a".equals(opt)) {
12083                // Right now we only know how to print all.
12084            } else if ("-h".equals(opt)) {
12085                pw.println("Package manager dump options:");
12086                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12087                pw.println("    --checkin: dump for a checkin");
12088                pw.println("    -f: print details of intent filters");
12089                pw.println("    -h: print this help");
12090                pw.println("  cmd may be one of:");
12091                pw.println("    l[ibraries]: list known shared libraries");
12092                pw.println("    f[ibraries]: list device features");
12093                pw.println("    k[eysets]: print known keysets");
12094                pw.println("    r[esolvers]: dump intent resolvers");
12095                pw.println("    perm[issions]: dump permissions");
12096                pw.println("    pref[erred]: print preferred package settings");
12097                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12098                pw.println("    prov[iders]: dump content providers");
12099                pw.println("    p[ackages]: dump installed packages");
12100                pw.println("    s[hared-users]: dump shared user IDs");
12101                pw.println("    m[essages]: print collected runtime messages");
12102                pw.println("    v[erifiers]: print package verifier info");
12103                pw.println("    version: print database version info");
12104                pw.println("    write: write current settings now");
12105                pw.println("    <package.name>: info about given package");
12106                pw.println("    installs: details about install sessions");
12107                return;
12108            } else if ("--checkin".equals(opt)) {
12109                checkin = true;
12110            } else if ("-f".equals(opt)) {
12111                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12112            } else {
12113                pw.println("Unknown argument: " + opt + "; use -h for help");
12114            }
12115        }
12116
12117        // Is the caller requesting to dump a particular piece of data?
12118        if (opti < args.length) {
12119            String cmd = args[opti];
12120            opti++;
12121            // Is this a package name?
12122            if ("android".equals(cmd) || cmd.contains(".")) {
12123                packageName = cmd;
12124                // When dumping a single package, we always dump all of its
12125                // filter information since the amount of data will be reasonable.
12126                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12127            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12128                dumpState.setDump(DumpState.DUMP_LIBS);
12129            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12130                dumpState.setDump(DumpState.DUMP_FEATURES);
12131            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12132                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12133            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12134                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12135            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12136                dumpState.setDump(DumpState.DUMP_PREFERRED);
12137            } else if ("preferred-xml".equals(cmd)) {
12138                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12139                if (opti < args.length && "--full".equals(args[opti])) {
12140                    fullPreferred = true;
12141                    opti++;
12142                }
12143            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12144                dumpState.setDump(DumpState.DUMP_PACKAGES);
12145            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12146                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12147            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12148                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12149            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12150                dumpState.setDump(DumpState.DUMP_MESSAGES);
12151            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12152                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12153            } else if ("version".equals(cmd)) {
12154                dumpState.setDump(DumpState.DUMP_VERSION);
12155            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12156                dumpState.setDump(DumpState.DUMP_KEYSETS);
12157            } else if ("installs".equals(cmd)) {
12158                dumpState.setDump(DumpState.DUMP_INSTALLS);
12159            } else if ("write".equals(cmd)) {
12160                synchronized (mPackages) {
12161                    mSettings.writeLPr();
12162                    pw.println("Settings written.");
12163                    return;
12164                }
12165            }
12166        }
12167
12168        if (checkin) {
12169            pw.println("vers,1");
12170        }
12171
12172        // reader
12173        synchronized (mPackages) {
12174            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12175                if (!checkin) {
12176                    if (dumpState.onTitlePrinted())
12177                        pw.println();
12178                    pw.println("Database versions:");
12179                    pw.print("  SDK Version:");
12180                    pw.print(" internal=");
12181                    pw.print(mSettings.mInternalSdkPlatform);
12182                    pw.print(" external=");
12183                    pw.println(mSettings.mExternalSdkPlatform);
12184                    pw.print("  DB Version:");
12185                    pw.print(" internal=");
12186                    pw.print(mSettings.mInternalDatabaseVersion);
12187                    pw.print(" external=");
12188                    pw.println(mSettings.mExternalDatabaseVersion);
12189                }
12190            }
12191
12192            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12193                if (!checkin) {
12194                    if (dumpState.onTitlePrinted())
12195                        pw.println();
12196                    pw.println("Verifiers:");
12197                    pw.print("  Required: ");
12198                    pw.print(mRequiredVerifierPackage);
12199                    pw.print(" (uid=");
12200                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12201                    pw.println(")");
12202                } else if (mRequiredVerifierPackage != null) {
12203                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12204                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12205                }
12206            }
12207
12208            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12209                boolean printedHeader = false;
12210                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12211                while (it.hasNext()) {
12212                    String name = it.next();
12213                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12214                    if (!checkin) {
12215                        if (!printedHeader) {
12216                            if (dumpState.onTitlePrinted())
12217                                pw.println();
12218                            pw.println("Libraries:");
12219                            printedHeader = true;
12220                        }
12221                        pw.print("  ");
12222                    } else {
12223                        pw.print("lib,");
12224                    }
12225                    pw.print(name);
12226                    if (!checkin) {
12227                        pw.print(" -> ");
12228                    }
12229                    if (ent.path != null) {
12230                        if (!checkin) {
12231                            pw.print("(jar) ");
12232                            pw.print(ent.path);
12233                        } else {
12234                            pw.print(",jar,");
12235                            pw.print(ent.path);
12236                        }
12237                    } else {
12238                        if (!checkin) {
12239                            pw.print("(apk) ");
12240                            pw.print(ent.apk);
12241                        } else {
12242                            pw.print(",apk,");
12243                            pw.print(ent.apk);
12244                        }
12245                    }
12246                    pw.println();
12247                }
12248            }
12249
12250            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12251                if (dumpState.onTitlePrinted())
12252                    pw.println();
12253                if (!checkin) {
12254                    pw.println("Features:");
12255                }
12256                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12257                while (it.hasNext()) {
12258                    String name = it.next();
12259                    if (!checkin) {
12260                        pw.print("  ");
12261                    } else {
12262                        pw.print("feat,");
12263                    }
12264                    pw.println(name);
12265                }
12266            }
12267
12268            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12269                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12270                        : "Activity Resolver Table:", "  ", packageName,
12271                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12272                    dumpState.setTitlePrinted(true);
12273                }
12274                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12275                        : "Receiver Resolver Table:", "  ", packageName,
12276                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12277                    dumpState.setTitlePrinted(true);
12278                }
12279                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12280                        : "Service Resolver Table:", "  ", packageName,
12281                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12282                    dumpState.setTitlePrinted(true);
12283                }
12284                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12285                        : "Provider Resolver Table:", "  ", packageName,
12286                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12287                    dumpState.setTitlePrinted(true);
12288                }
12289            }
12290
12291            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12292                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12293                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12294                    int user = mSettings.mPreferredActivities.keyAt(i);
12295                    if (pir.dump(pw,
12296                            dumpState.getTitlePrinted()
12297                                ? "\nPreferred Activities User " + user + ":"
12298                                : "Preferred Activities User " + user + ":", "  ",
12299                            packageName, true)) {
12300                        dumpState.setTitlePrinted(true);
12301                    }
12302                }
12303            }
12304
12305            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12306                pw.flush();
12307                FileOutputStream fout = new FileOutputStream(fd);
12308                BufferedOutputStream str = new BufferedOutputStream(fout);
12309                XmlSerializer serializer = new FastXmlSerializer();
12310                try {
12311                    serializer.setOutput(str, "utf-8");
12312                    serializer.startDocument(null, true);
12313                    serializer.setFeature(
12314                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12315                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12316                    serializer.endDocument();
12317                    serializer.flush();
12318                } catch (IllegalArgumentException e) {
12319                    pw.println("Failed writing: " + e);
12320                } catch (IllegalStateException e) {
12321                    pw.println("Failed writing: " + e);
12322                } catch (IOException e) {
12323                    pw.println("Failed writing: " + e);
12324                }
12325            }
12326
12327            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12328                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12329                if (packageName == null) {
12330                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12331                        if (iperm == 0) {
12332                            if (dumpState.onTitlePrinted())
12333                                pw.println();
12334                            pw.println("AppOp Permissions:");
12335                        }
12336                        pw.print("  AppOp Permission ");
12337                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12338                        pw.println(":");
12339                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12340                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12341                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12342                        }
12343                    }
12344                }
12345            }
12346
12347            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12348                boolean printedSomething = false;
12349                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12350                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12351                        continue;
12352                    }
12353                    if (!printedSomething) {
12354                        if (dumpState.onTitlePrinted())
12355                            pw.println();
12356                        pw.println("Registered ContentProviders:");
12357                        printedSomething = true;
12358                    }
12359                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12360                    pw.print("    "); pw.println(p.toString());
12361                }
12362                printedSomething = false;
12363                for (Map.Entry<String, PackageParser.Provider> entry :
12364                        mProvidersByAuthority.entrySet()) {
12365                    PackageParser.Provider p = entry.getValue();
12366                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12367                        continue;
12368                    }
12369                    if (!printedSomething) {
12370                        if (dumpState.onTitlePrinted())
12371                            pw.println();
12372                        pw.println("ContentProvider Authorities:");
12373                        printedSomething = true;
12374                    }
12375                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12376                    pw.print("    "); pw.println(p.toString());
12377                    if (p.info != null && p.info.applicationInfo != null) {
12378                        final String appInfo = p.info.applicationInfo.toString();
12379                        pw.print("      applicationInfo="); pw.println(appInfo);
12380                    }
12381                }
12382            }
12383
12384            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12385                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12386            }
12387
12388            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12389                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12390            }
12391
12392            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12393                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12394            }
12395
12396            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12397                // XXX should handle packageName != null by dumping only install data that
12398                // the given package is involved with.
12399                if (dumpState.onTitlePrinted()) pw.println();
12400                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12401            }
12402
12403            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12404                if (dumpState.onTitlePrinted()) pw.println();
12405                mSettings.dumpReadMessagesLPr(pw, dumpState);
12406
12407                pw.println();
12408                pw.println("Package warning messages:");
12409                final File fname = getSettingsProblemFile();
12410                FileInputStream in = null;
12411                try {
12412                    in = new FileInputStream(fname);
12413                    final int avail = in.available();
12414                    final byte[] data = new byte[avail];
12415                    in.read(data);
12416                    pw.print(new String(data));
12417                } catch (FileNotFoundException e) {
12418                } catch (IOException e) {
12419                } finally {
12420                    if (in != null) {
12421                        try {
12422                            in.close();
12423                        } catch (IOException e) {
12424                        }
12425                    }
12426                }
12427            }
12428        }
12429    }
12430
12431    // ------- apps on sdcard specific code -------
12432    static final boolean DEBUG_SD_INSTALL = false;
12433
12434    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12435
12436    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12437
12438    private boolean mMediaMounted = false;
12439
12440    static String getEncryptKey() {
12441        try {
12442            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12443                    SD_ENCRYPTION_KEYSTORE_NAME);
12444            if (sdEncKey == null) {
12445                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12446                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12447                if (sdEncKey == null) {
12448                    Slog.e(TAG, "Failed to create encryption keys");
12449                    return null;
12450                }
12451            }
12452            return sdEncKey;
12453        } catch (NoSuchAlgorithmException nsae) {
12454            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12455            return null;
12456        } catch (IOException ioe) {
12457            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12458            return null;
12459        }
12460    }
12461
12462    /*
12463     * Update media status on PackageManager.
12464     */
12465    @Override
12466    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12467        int callingUid = Binder.getCallingUid();
12468        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12469            throw new SecurityException("Media status can only be updated by the system");
12470        }
12471        // reader; this apparently protects mMediaMounted, but should probably
12472        // be a different lock in that case.
12473        synchronized (mPackages) {
12474            Log.i(TAG, "Updating external media status from "
12475                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12476                    + (mediaStatus ? "mounted" : "unmounted"));
12477            if (DEBUG_SD_INSTALL)
12478                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12479                        + ", mMediaMounted=" + mMediaMounted);
12480            if (mediaStatus == mMediaMounted) {
12481                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12482                        : 0, -1);
12483                mHandler.sendMessage(msg);
12484                return;
12485            }
12486            mMediaMounted = mediaStatus;
12487        }
12488        // Queue up an async operation since the package installation may take a
12489        // little while.
12490        mHandler.post(new Runnable() {
12491            public void run() {
12492                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12493            }
12494        });
12495    }
12496
12497    /**
12498     * Called by MountService when the initial ASECs to scan are available.
12499     * Should block until all the ASEC containers are finished being scanned.
12500     */
12501    public void scanAvailableAsecs() {
12502        updateExternalMediaStatusInner(true, false, false);
12503        if (mShouldRestoreconData) {
12504            SELinuxMMAC.setRestoreconDone();
12505            mShouldRestoreconData = false;
12506        }
12507    }
12508
12509    /*
12510     * Collect information of applications on external media, map them against
12511     * existing containers and update information based on current mount status.
12512     * Please note that we always have to report status if reportStatus has been
12513     * set to true especially when unloading packages.
12514     */
12515    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12516            boolean externalStorage) {
12517        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12518        int[] uidArr = EmptyArray.INT;
12519
12520        final String[] list = PackageHelper.getSecureContainerList();
12521        if (ArrayUtils.isEmpty(list)) {
12522            Log.i(TAG, "No secure containers found");
12523        } else {
12524            // Process list of secure containers and categorize them
12525            // as active or stale based on their package internal state.
12526
12527            // reader
12528            synchronized (mPackages) {
12529                for (String cid : list) {
12530                    // Leave stages untouched for now; installer service owns them
12531                    if (PackageInstallerService.isStageName(cid)) continue;
12532
12533                    if (DEBUG_SD_INSTALL)
12534                        Log.i(TAG, "Processing container " + cid);
12535                    String pkgName = getAsecPackageName(cid);
12536                    if (pkgName == null) {
12537                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12538                        continue;
12539                    }
12540                    if (DEBUG_SD_INSTALL)
12541                        Log.i(TAG, "Looking for pkg : " + pkgName);
12542
12543                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12544                    if (ps == null) {
12545                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12546                        continue;
12547                    }
12548
12549                    /*
12550                     * Skip packages that are not external if we're unmounting
12551                     * external storage.
12552                     */
12553                    if (externalStorage && !isMounted && !isExternal(ps)) {
12554                        continue;
12555                    }
12556
12557                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12558                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12559                    // The package status is changed only if the code path
12560                    // matches between settings and the container id.
12561                    if (ps.codePathString != null
12562                            && ps.codePathString.startsWith(args.getCodePath())) {
12563                        if (DEBUG_SD_INSTALL) {
12564                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12565                                    + " at code path: " + ps.codePathString);
12566                        }
12567
12568                        // We do have a valid package installed on sdcard
12569                        processCids.put(args, ps.codePathString);
12570                        final int uid = ps.appId;
12571                        if (uid != -1) {
12572                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12573                        }
12574                    } else {
12575                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12576                                + ps.codePathString);
12577                    }
12578                }
12579            }
12580
12581            Arrays.sort(uidArr);
12582        }
12583
12584        // Process packages with valid entries.
12585        if (isMounted) {
12586            if (DEBUG_SD_INSTALL)
12587                Log.i(TAG, "Loading packages");
12588            loadMediaPackages(processCids, uidArr);
12589            startCleaningPackages();
12590            mInstallerService.onSecureContainersAvailable();
12591        } else {
12592            if (DEBUG_SD_INSTALL)
12593                Log.i(TAG, "Unloading packages");
12594            unloadMediaPackages(processCids, uidArr, reportStatus);
12595        }
12596    }
12597
12598    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12599            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12600        int size = pkgList.size();
12601        if (size > 0) {
12602            // Send broadcasts here
12603            Bundle extras = new Bundle();
12604            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12605                    .toArray(new String[size]));
12606            if (uidArr != null) {
12607                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12608            }
12609            if (replacing) {
12610                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12611            }
12612            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12613                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12614            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12615        }
12616    }
12617
12618   /*
12619     * Look at potentially valid container ids from processCids If package
12620     * information doesn't match the one on record or package scanning fails,
12621     * the cid is added to list of removeCids. We currently don't delete stale
12622     * containers.
12623     */
12624    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12625        ArrayList<String> pkgList = new ArrayList<String>();
12626        Set<AsecInstallArgs> keys = processCids.keySet();
12627
12628        for (AsecInstallArgs args : keys) {
12629            String codePath = processCids.get(args);
12630            if (DEBUG_SD_INSTALL)
12631                Log.i(TAG, "Loading container : " + args.cid);
12632            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12633            try {
12634                // Make sure there are no container errors first.
12635                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12636                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12637                            + " when installing from sdcard");
12638                    continue;
12639                }
12640                // Check code path here.
12641                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12642                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12643                            + " does not match one in settings " + codePath);
12644                    continue;
12645                }
12646                // Parse package
12647                int parseFlags = mDefParseFlags;
12648                if (args.isExternal()) {
12649                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12650                }
12651                if (args.isFwdLocked()) {
12652                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12653                }
12654
12655                synchronized (mInstallLock) {
12656                    PackageParser.Package pkg = null;
12657                    try {
12658                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12659                    } catch (PackageManagerException e) {
12660                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12661                    }
12662                    // Scan the package
12663                    if (pkg != null) {
12664                        /*
12665                         * TODO why is the lock being held? doPostInstall is
12666                         * called in other places without the lock. This needs
12667                         * to be straightened out.
12668                         */
12669                        // writer
12670                        synchronized (mPackages) {
12671                            retCode = PackageManager.INSTALL_SUCCEEDED;
12672                            pkgList.add(pkg.packageName);
12673                            // Post process args
12674                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12675                                    pkg.applicationInfo.uid);
12676                        }
12677                    } else {
12678                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12679                    }
12680                }
12681
12682            } finally {
12683                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12684                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12685                }
12686            }
12687        }
12688        // writer
12689        synchronized (mPackages) {
12690            // If the platform SDK has changed since the last time we booted,
12691            // we need to re-grant app permission to catch any new ones that
12692            // appear. This is really a hack, and means that apps can in some
12693            // cases get permissions that the user didn't initially explicitly
12694            // allow... it would be nice to have some better way to handle
12695            // this situation.
12696            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12697            if (regrantPermissions)
12698                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12699                        + mSdkVersion + "; regranting permissions for external storage");
12700            mSettings.mExternalSdkPlatform = mSdkVersion;
12701
12702            // Make sure group IDs have been assigned, and any permission
12703            // changes in other apps are accounted for
12704            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12705                    | (regrantPermissions
12706                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12707                            : 0));
12708
12709            mSettings.updateExternalDatabaseVersion();
12710
12711            // can downgrade to reader
12712            // Persist settings
12713            mSettings.writeLPr();
12714        }
12715        // Send a broadcast to let everyone know we are done processing
12716        if (pkgList.size() > 0) {
12717            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12718        }
12719    }
12720
12721   /*
12722     * Utility method to unload a list of specified containers
12723     */
12724    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12725        // Just unmount all valid containers.
12726        for (AsecInstallArgs arg : cidArgs) {
12727            synchronized (mInstallLock) {
12728                arg.doPostDeleteLI(false);
12729           }
12730       }
12731   }
12732
12733    /*
12734     * Unload packages mounted on external media. This involves deleting package
12735     * data from internal structures, sending broadcasts about diabled packages,
12736     * gc'ing to free up references, unmounting all secure containers
12737     * corresponding to packages on external media, and posting a
12738     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12739     * that we always have to post this message if status has been requested no
12740     * matter what.
12741     */
12742    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12743            final boolean reportStatus) {
12744        if (DEBUG_SD_INSTALL)
12745            Log.i(TAG, "unloading media packages");
12746        ArrayList<String> pkgList = new ArrayList<String>();
12747        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12748        final Set<AsecInstallArgs> keys = processCids.keySet();
12749        for (AsecInstallArgs args : keys) {
12750            String pkgName = args.getPackageName();
12751            if (DEBUG_SD_INSTALL)
12752                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12753            // Delete package internally
12754            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12755            synchronized (mInstallLock) {
12756                boolean res = deletePackageLI(pkgName, null, false, null, null,
12757                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12758                if (res) {
12759                    pkgList.add(pkgName);
12760                } else {
12761                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12762                    failedList.add(args);
12763                }
12764            }
12765        }
12766
12767        // reader
12768        synchronized (mPackages) {
12769            // We didn't update the settings after removing each package;
12770            // write them now for all packages.
12771            mSettings.writeLPr();
12772        }
12773
12774        // We have to absolutely send UPDATED_MEDIA_STATUS only
12775        // after confirming that all the receivers processed the ordered
12776        // broadcast when packages get disabled, force a gc to clean things up.
12777        // and unload all the containers.
12778        if (pkgList.size() > 0) {
12779            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12780                    new IIntentReceiver.Stub() {
12781                public void performReceive(Intent intent, int resultCode, String data,
12782                        Bundle extras, boolean ordered, boolean sticky,
12783                        int sendingUser) throws RemoteException {
12784                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12785                            reportStatus ? 1 : 0, 1, keys);
12786                    mHandler.sendMessage(msg);
12787                }
12788            });
12789        } else {
12790            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12791                    keys);
12792            mHandler.sendMessage(msg);
12793        }
12794    }
12795
12796    /** Binder call */
12797    @Override
12798    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12799            final int flags) {
12800        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12801        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12802        int returnCode = PackageManager.MOVE_SUCCEEDED;
12803        int currInstallFlags = 0;
12804        int newInstallFlags = 0;
12805
12806        File codeFile = null;
12807        String installerPackageName = null;
12808        String packageAbiOverride = null;
12809
12810        // reader
12811        synchronized (mPackages) {
12812            final PackageParser.Package pkg = mPackages.get(packageName);
12813            final PackageSetting ps = mSettings.mPackages.get(packageName);
12814            if (pkg == null || ps == null) {
12815                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12816            } else {
12817                // Disable moving fwd locked apps and system packages
12818                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12819                    Slog.w(TAG, "Cannot move system application");
12820                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12821                } else if (pkg.mOperationPending) {
12822                    Slog.w(TAG, "Attempt to move package which has pending operations");
12823                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12824                } else {
12825                    // Find install location first
12826                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12827                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12828                        Slog.w(TAG, "Ambigous flags specified for move location.");
12829                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12830                    } else {
12831                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12832                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12833                        currInstallFlags = isExternal(pkg)
12834                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12835
12836                        if (newInstallFlags == currInstallFlags) {
12837                            Slog.w(TAG, "No move required. Trying to move to same location");
12838                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12839                        } else {
12840                            if (isForwardLocked(pkg)) {
12841                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12842                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12843                            }
12844                        }
12845                    }
12846                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12847                        pkg.mOperationPending = true;
12848                    }
12849                }
12850
12851                codeFile = new File(pkg.codePath);
12852                installerPackageName = ps.installerPackageName;
12853                packageAbiOverride = ps.cpuAbiOverrideString;
12854            }
12855        }
12856
12857        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12858            try {
12859                observer.packageMoved(packageName, returnCode);
12860            } catch (RemoteException ignored) {
12861            }
12862            return;
12863        }
12864
12865        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12866            @Override
12867            public void onUserActionRequired(Intent intent) throws RemoteException {
12868                throw new IllegalStateException();
12869            }
12870
12871            @Override
12872            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12873                    Bundle extras) throws RemoteException {
12874                Slog.d(TAG, "Install result for move: "
12875                        + PackageManager.installStatusToString(returnCode, msg));
12876
12877                // We usually have a new package now after the install, but if
12878                // we failed we need to clear the pending flag on the original
12879                // package object.
12880                synchronized (mPackages) {
12881                    final PackageParser.Package pkg = mPackages.get(packageName);
12882                    if (pkg != null) {
12883                        pkg.mOperationPending = false;
12884                    }
12885                }
12886
12887                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12888                switch (status) {
12889                    case PackageInstaller.STATUS_SUCCESS:
12890                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12891                        break;
12892                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12893                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12894                        break;
12895                    default:
12896                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12897                        break;
12898                }
12899            }
12900        };
12901
12902        // Treat a move like reinstalling an existing app, which ensures that we
12903        // process everythign uniformly, like unpacking native libraries.
12904        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12905
12906        final Message msg = mHandler.obtainMessage(INIT_COPY);
12907        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12908        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12909                installerPackageName, null, user, packageAbiOverride);
12910        mHandler.sendMessage(msg);
12911    }
12912
12913    @Override
12914    public boolean setInstallLocation(int loc) {
12915        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12916                null);
12917        if (getInstallLocation() == loc) {
12918            return true;
12919        }
12920        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12921                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12922            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12923                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12924            return true;
12925        }
12926        return false;
12927   }
12928
12929    @Override
12930    public int getInstallLocation() {
12931        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12932                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12933                PackageHelper.APP_INSTALL_AUTO);
12934    }
12935
12936    /** Called by UserManagerService */
12937    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12938        mDirtyUsers.remove(userHandle);
12939        mSettings.removeUserLPw(userHandle);
12940        mPendingBroadcasts.remove(userHandle);
12941        if (mInstaller != null) {
12942            // Technically, we shouldn't be doing this with the package lock
12943            // held.  However, this is very rare, and there is already so much
12944            // other disk I/O going on, that we'll let it slide for now.
12945            mInstaller.removeUserDataDirs(userHandle);
12946        }
12947        mUserNeedsBadging.delete(userHandle);
12948        removeUnusedPackagesLILPw(userManager, userHandle);
12949    }
12950
12951    /**
12952     * We're removing userHandle and would like to remove any downloaded packages
12953     * that are no longer in use by any other user.
12954     * @param userHandle the user being removed
12955     */
12956    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12957        final boolean DEBUG_CLEAN_APKS = false;
12958        int [] users = userManager.getUserIdsLPr();
12959        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12960        while (psit.hasNext()) {
12961            PackageSetting ps = psit.next();
12962            if (ps.pkg == null) {
12963                continue;
12964            }
12965            final String packageName = ps.pkg.packageName;
12966            // Skip over if system app
12967            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12968                continue;
12969            }
12970            if (DEBUG_CLEAN_APKS) {
12971                Slog.i(TAG, "Checking package " + packageName);
12972            }
12973            boolean keep = false;
12974            for (int i = 0; i < users.length; i++) {
12975                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12976                    keep = true;
12977                    if (DEBUG_CLEAN_APKS) {
12978                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12979                                + users[i]);
12980                    }
12981                    break;
12982                }
12983            }
12984            if (!keep) {
12985                if (DEBUG_CLEAN_APKS) {
12986                    Slog.i(TAG, "  Removing package " + packageName);
12987                }
12988                mHandler.post(new Runnable() {
12989                    public void run() {
12990                        deletePackageX(packageName, userHandle, 0);
12991                    } //end run
12992                });
12993            }
12994        }
12995    }
12996
12997    /** Called by UserManagerService */
12998    void createNewUserLILPw(int userHandle, File path) {
12999        if (mInstaller != null) {
13000            mInstaller.createUserConfig(userHandle);
13001            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13002        }
13003    }
13004
13005    @Override
13006    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13007        mContext.enforceCallingOrSelfPermission(
13008                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13009                "Only package verification agents can read the verifier device identity");
13010
13011        synchronized (mPackages) {
13012            return mSettings.getVerifierDeviceIdentityLPw();
13013        }
13014    }
13015
13016    @Override
13017    public void setPermissionEnforced(String permission, boolean enforced) {
13018        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13019        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13020            synchronized (mPackages) {
13021                if (mSettings.mReadExternalStorageEnforced == null
13022                        || mSettings.mReadExternalStorageEnforced != enforced) {
13023                    mSettings.mReadExternalStorageEnforced = enforced;
13024                    mSettings.writeLPr();
13025                }
13026            }
13027            // kill any non-foreground processes so we restart them and
13028            // grant/revoke the GID.
13029            final IActivityManager am = ActivityManagerNative.getDefault();
13030            if (am != null) {
13031                final long token = Binder.clearCallingIdentity();
13032                try {
13033                    am.killProcessesBelowForeground("setPermissionEnforcement");
13034                } catch (RemoteException e) {
13035                } finally {
13036                    Binder.restoreCallingIdentity(token);
13037                }
13038            }
13039        } else {
13040            throw new IllegalArgumentException("No selective enforcement for " + permission);
13041        }
13042    }
13043
13044    @Override
13045    @Deprecated
13046    public boolean isPermissionEnforced(String permission) {
13047        return true;
13048    }
13049
13050    @Override
13051    public boolean isStorageLow() {
13052        final long token = Binder.clearCallingIdentity();
13053        try {
13054            final DeviceStorageMonitorInternal
13055                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13056            if (dsm != null) {
13057                return dsm.isMemoryLow();
13058            } else {
13059                return false;
13060            }
13061        } finally {
13062            Binder.restoreCallingIdentity(token);
13063        }
13064    }
13065
13066    @Override
13067    public IPackageInstaller getPackageInstaller() {
13068        return mInstallerService;
13069    }
13070
13071    private boolean userNeedsBadging(int userId) {
13072        int index = mUserNeedsBadging.indexOfKey(userId);
13073        if (index < 0) {
13074            final UserInfo userInfo;
13075            final long token = Binder.clearCallingIdentity();
13076            try {
13077                userInfo = sUserManager.getUserInfo(userId);
13078            } finally {
13079                Binder.restoreCallingIdentity(token);
13080            }
13081            final boolean b;
13082            if (userInfo != null && userInfo.isManagedProfile()) {
13083                b = true;
13084            } else {
13085                b = false;
13086            }
13087            mUserNeedsBadging.put(userId, b);
13088            return b;
13089        }
13090        return mUserNeedsBadging.valueAt(index);
13091    }
13092
13093    @Override
13094    public KeySet getKeySetByAlias(String packageName, String alias) {
13095        if (packageName == null || alias == null) {
13096            return null;
13097        }
13098        synchronized(mPackages) {
13099            final PackageParser.Package pkg = mPackages.get(packageName);
13100            if (pkg == null) {
13101                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13102                throw new IllegalArgumentException("Unknown package: " + packageName);
13103            }
13104            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13105            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13106        }
13107    }
13108
13109    @Override
13110    public KeySet getSigningKeySet(String packageName) {
13111        if (packageName == null) {
13112            return null;
13113        }
13114        synchronized(mPackages) {
13115            final PackageParser.Package pkg = mPackages.get(packageName);
13116            if (pkg == null) {
13117                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13118                throw new IllegalArgumentException("Unknown package: " + packageName);
13119            }
13120            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13121                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13122                throw new SecurityException("May not access signing KeySet of other apps.");
13123            }
13124            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13125            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13126        }
13127    }
13128
13129    @Override
13130    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13131        if (packageName == null || ks == null) {
13132            return false;
13133        }
13134        synchronized(mPackages) {
13135            final PackageParser.Package pkg = mPackages.get(packageName);
13136            if (pkg == null) {
13137                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13138                throw new IllegalArgumentException("Unknown package: " + packageName);
13139            }
13140            IBinder ksh = ks.getToken();
13141            if (ksh instanceof KeySetHandle) {
13142                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13143                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13144            }
13145            return false;
13146        }
13147    }
13148
13149    @Override
13150    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13151        if (packageName == null || ks == null) {
13152            return false;
13153        }
13154        synchronized(mPackages) {
13155            final PackageParser.Package pkg = mPackages.get(packageName);
13156            if (pkg == null) {
13157                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13158                throw new IllegalArgumentException("Unknown package: " + packageName);
13159            }
13160            IBinder ksh = ks.getToken();
13161            if (ksh instanceof KeySetHandle) {
13162                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13163                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13164            }
13165            return false;
13166        }
13167    }
13168}
13169