PackageManagerService.java revision ec9bad2015c6d3bc91bab66f0824043c1e24d013
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.FileUtils;
142import android.os.Handler;
143import android.os.IBinder;
144import android.os.Looper;
145import android.os.Message;
146import android.os.Parcel;
147import android.os.ParcelFileDescriptor;
148import android.os.Process;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.security.KeyStore;
157import android.security.SystemKeyStore;
158import android.system.ErrnoException;
159import android.system.Os;
160import android.system.StructStat;
161import android.text.TextUtils;
162import android.util.ArraySet;
163import android.util.AtomicFile;
164import android.util.DisplayMetrics;
165import android.util.EventLog;
166import android.util.ExceptionUtils;
167import android.util.Log;
168import android.util.LogPrinter;
169import android.util.PrintStreamPrinter;
170import android.util.Slog;
171import android.util.SparseArray;
172import android.util.SparseBooleanArray;
173import android.view.Display;
174
175import java.io.BufferedInputStream;
176import java.io.BufferedOutputStream;
177import java.io.File;
178import java.io.FileDescriptor;
179import java.io.FileInputStream;
180import java.io.FileNotFoundException;
181import java.io.FileOutputStream;
182import java.io.FilenameFilter;
183import java.io.IOException;
184import java.io.InputStream;
185import java.io.PrintWriter;
186import java.nio.charset.StandardCharsets;
187import java.security.NoSuchAlgorithmException;
188import java.security.PublicKey;
189import java.security.cert.CertificateEncodingException;
190import java.security.cert.CertificateException;
191import java.text.SimpleDateFormat;
192import java.util.ArrayList;
193import java.util.Arrays;
194import java.util.Collection;
195import java.util.Collections;
196import java.util.Comparator;
197import java.util.Date;
198import java.util.HashMap;
199import java.util.HashSet;
200import java.util.Iterator;
201import java.util.List;
202import java.util.Map;
203import java.util.Set;
204import java.util.concurrent.atomic.AtomicBoolean;
205import java.util.concurrent.atomic.AtomicLong;
206
207import dalvik.system.DexFile;
208import dalvik.system.StaleDexCacheError;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212import libcore.util.EmptyArray;
213
214/**
215 * Keep track of all those .apks everywhere.
216 *
217 * This is very central to the platform's security; please run the unit
218 * tests whenever making modifications here:
219 *
220mmm frameworks/base/tests/AndroidTests
221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
223 *
224 * {@hide}
225 */
226public class PackageManagerService extends IPackageManager.Stub {
227    static final String TAG = "PackageManager";
228    static final boolean DEBUG_SETTINGS = false;
229    static final boolean DEBUG_PREFERRED = false;
230    static final boolean DEBUG_UPGRADE = false;
231    private static final boolean DEBUG_INSTALL = false;
232    private static final boolean DEBUG_REMOVE = false;
233    private static final boolean DEBUG_BROADCASTS = false;
234    private static final boolean DEBUG_SHOW_INFO = false;
235    private static final boolean DEBUG_PACKAGE_INFO = false;
236    private static final boolean DEBUG_INTENT_MATCHING = false;
237    private static final boolean DEBUG_PACKAGE_SCANNING = false;
238    private static final boolean DEBUG_VERIFY = false;
239    private static final boolean DEBUG_DEXOPT = false;
240    private static final boolean DEBUG_ABI_SELECTION = false;
241
242    private static final int RADIO_UID = Process.PHONE_UID;
243    private static final int LOG_UID = Process.LOG_UID;
244    private static final int NFC_UID = Process.NFC_UID;
245    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
246    private static final int SHELL_UID = Process.SHELL_UID;
247
248    // Cap the size of permission trees that 3rd party apps can define
249    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
250
251    // Suffix used during package installation when copying/moving
252    // package apks to install directory.
253    private static final String INSTALL_PACKAGE_SUFFIX = "-";
254
255    static final int SCAN_NO_DEX = 1<<1;
256    static final int SCAN_FORCE_DEX = 1<<2;
257    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
258    static final int SCAN_NEW_INSTALL = 1<<4;
259    static final int SCAN_NO_PATHS = 1<<5;
260    static final int SCAN_UPDATE_TIME = 1<<6;
261    static final int SCAN_DEFER_DEX = 1<<7;
262    static final int SCAN_BOOTING = 1<<8;
263    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
264    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
265    static final int SCAN_REPLACING = 1<<11;
266
267    static final int REMOVE_CHATTY = 1<<16;
268
269    /**
270     * Timeout (in milliseconds) after which the watchdog should declare that
271     * our handler thread is wedged.  The usual default for such things is one
272     * minute but we sometimes do very lengthy I/O operations on this thread,
273     * such as installing multi-gigabyte applications, so ours needs to be longer.
274     */
275    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
276
277    /**
278     * Whether verification is enabled by default.
279     */
280    private static final boolean DEFAULT_VERIFY_ENABLE = true;
281
282    /**
283     * The default maximum time to wait for the verification agent to return in
284     * milliseconds.
285     */
286    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
287
288    /**
289     * The default response for package verification timeout.
290     *
291     * This can be either PackageManager.VERIFICATION_ALLOW or
292     * PackageManager.VERIFICATION_REJECT.
293     */
294    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
295
296    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
297
298    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
299            DEFAULT_CONTAINER_PACKAGE,
300            "com.android.defcontainer.DefaultContainerService");
301
302    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
303
304    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
305
306    private static String sPreferredInstructionSet;
307
308    final ServiceThread mHandlerThread;
309
310    private static final String IDMAP_PREFIX = "/data/resource-cache/";
311    private static final String IDMAP_SUFFIX = "@idmap";
312
313    final PackageHandler mHandler;
314
315    /**
316     * Messages for {@link #mHandler} that need to wait for system ready before
317     * being dispatched.
318     */
319    private ArrayList<Message> mPostSystemReadyMessages;
320
321    final int mSdkVersion = Build.VERSION.SDK_INT;
322
323    final Context mContext;
324    final boolean mFactoryTest;
325    final boolean mOnlyCore;
326    final DisplayMetrics mMetrics;
327    final int mDefParseFlags;
328    final String[] mSeparateProcesses;
329
330    // This is where all application persistent data goes.
331    final File mAppDataDir;
332
333    // This is where all application persistent data goes for secondary users.
334    final File mUserAppDataDir;
335
336    /** The location for ASEC container files on internal storage. */
337    final String mAsecInternalPath;
338
339    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
340    // LOCK HELD.  Can be called with mInstallLock held.
341    final Installer mInstaller;
342
343    /** Directory where installed third-party apps stored */
344    final File mAppInstallDir;
345
346    /**
347     * Directory to which applications installed internally have their
348     * 32 bit native libraries copied.
349     */
350    private File mAppLib32InstallDir;
351
352    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
353    // apps.
354    final File mDrmAppPrivateInstallDir;
355
356    // ----------------------------------------------------------------
357
358    // Lock for state used when installing and doing other long running
359    // operations.  Methods that must be called with this lock held have
360    // the suffix "LI".
361    final Object mInstallLock = new Object();
362
363    // ----------------------------------------------------------------
364
365    // Keys are String (package name), values are Package.  This also serves
366    // as the lock for the global state.  Methods that must be called with
367    // this lock held have the prefix "LP".
368    final HashMap<String, PackageParser.Package> mPackages =
369            new HashMap<String, PackageParser.Package>();
370
371    // Tracks available target package names -> overlay package paths.
372    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
373        new HashMap<String, HashMap<String, PackageParser.Package>>();
374
375    final Settings mSettings;
376    boolean mRestoredSettings;
377
378    // System configuration read by SystemConfig.
379    final int[] mGlobalGids;
380    final SparseArray<HashSet<String>> mSystemPermissions;
381    final HashMap<String, FeatureInfo> mAvailableFeatures;
382
383    // If mac_permissions.xml was found for seinfo labeling.
384    boolean mFoundPolicyFile;
385
386    // If a recursive restorecon of /data/data/<pkg> is needed.
387    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
388
389    public static final class SharedLibraryEntry {
390        public final String path;
391        public final String apk;
392
393        SharedLibraryEntry(String _path, String _apk) {
394            path = _path;
395            apk = _apk;
396        }
397    }
398
399    // Currently known shared libraries.
400    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
401            new HashMap<String, SharedLibraryEntry>();
402
403    // All available activities, for your resolving pleasure.
404    final ActivityIntentResolver mActivities =
405            new ActivityIntentResolver();
406
407    // All available receivers, for your resolving pleasure.
408    final ActivityIntentResolver mReceivers =
409            new ActivityIntentResolver();
410
411    // All available services, for your resolving pleasure.
412    final ServiceIntentResolver mServices = new ServiceIntentResolver();
413
414    // All available providers, for your resolving pleasure.
415    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
416
417    // Mapping from provider base names (first directory in content URI codePath)
418    // to the provider information.
419    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
420            new HashMap<String, PackageParser.Provider>();
421
422    // Mapping from instrumentation class names to info about them.
423    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
424            new HashMap<ComponentName, PackageParser.Instrumentation>();
425
426    // Mapping from permission names to info about them.
427    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
428            new HashMap<String, PackageParser.PermissionGroup>();
429
430    // Packages whose data we have transfered into another package, thus
431    // should no longer exist.
432    final HashSet<String> mTransferedPackages = new HashSet<String>();
433
434    // Broadcast actions that are only available to the system.
435    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
436
437    /** List of packages waiting for verification. */
438    final SparseArray<PackageVerificationState> mPendingVerification
439            = new SparseArray<PackageVerificationState>();
440
441    /** Set of packages associated with each app op permission. */
442    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
443
444    final PackageInstallerService mInstallerService;
445
446    HashSet<PackageParser.Package> mDeferredDexOpt = null;
447
448    // Cache of users who need badging.
449    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
450
451    /** Token for keys in mPendingVerification. */
452    private int mPendingVerificationToken = 0;
453
454    volatile boolean mSystemReady;
455    volatile boolean mSafeMode;
456    volatile boolean mHasSystemUidErrors;
457
458    ApplicationInfo mAndroidApplication;
459    final ActivityInfo mResolveActivity = new ActivityInfo();
460    final ResolveInfo mResolveInfo = new ResolveInfo();
461    ComponentName mResolveComponentName;
462    PackageParser.Package mPlatformPackage;
463    ComponentName mCustomResolverComponentName;
464
465    boolean mResolverReplaced = false;
466
467    // Set of pending broadcasts for aggregating enable/disable of components.
468    static class PendingPackageBroadcasts {
469        // for each user id, a map of <package name -> components within that package>
470        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
471
472        public PendingPackageBroadcasts() {
473            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
474        }
475
476        public ArrayList<String> get(int userId, String packageName) {
477            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
478            return packages.get(packageName);
479        }
480
481        public void put(int userId, String packageName, ArrayList<String> components) {
482            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
483            packages.put(packageName, components);
484        }
485
486        public void remove(int userId, String packageName) {
487            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
488            if (packages != null) {
489                packages.remove(packageName);
490            }
491        }
492
493        public void remove(int userId) {
494            mUidMap.remove(userId);
495        }
496
497        public int userIdCount() {
498            return mUidMap.size();
499        }
500
501        public int userIdAt(int n) {
502            return mUidMap.keyAt(n);
503        }
504
505        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
506            return mUidMap.get(userId);
507        }
508
509        public int size() {
510            // total number of pending broadcast entries across all userIds
511            int num = 0;
512            for (int i = 0; i< mUidMap.size(); i++) {
513                num += mUidMap.valueAt(i).size();
514            }
515            return num;
516        }
517
518        public void clear() {
519            mUidMap.clear();
520        }
521
522        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
523            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
524            if (map == null) {
525                map = new HashMap<String, ArrayList<String>>();
526                mUidMap.put(userId, map);
527            }
528            return map;
529        }
530    }
531    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
532
533    // Service Connection to remote media container service to copy
534    // package uri's from external media onto secure containers
535    // or internal storage.
536    private IMediaContainerService mContainerService = null;
537
538    static final int SEND_PENDING_BROADCAST = 1;
539    static final int MCS_BOUND = 3;
540    static final int END_COPY = 4;
541    static final int INIT_COPY = 5;
542    static final int MCS_UNBIND = 6;
543    static final int START_CLEANING_PACKAGE = 7;
544    static final int FIND_INSTALL_LOC = 8;
545    static final int POST_INSTALL = 9;
546    static final int MCS_RECONNECT = 10;
547    static final int MCS_GIVE_UP = 11;
548    static final int UPDATED_MEDIA_STATUS = 12;
549    static final int WRITE_SETTINGS = 13;
550    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
551    static final int PACKAGE_VERIFIED = 15;
552    static final int CHECK_PENDING_VERIFICATION = 16;
553
554    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
555
556    // Delay time in millisecs
557    static final int BROADCAST_DELAY = 10 * 1000;
558
559    static UserManagerService sUserManager;
560
561    // Stores a list of users whose package restrictions file needs to be updated
562    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
563
564    final private DefaultContainerConnection mDefContainerConn =
565            new DefaultContainerConnection();
566    class DefaultContainerConnection implements ServiceConnection {
567        public void onServiceConnected(ComponentName name, IBinder service) {
568            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
569            IMediaContainerService imcs =
570                IMediaContainerService.Stub.asInterface(service);
571            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
572        }
573
574        public void onServiceDisconnected(ComponentName name) {
575            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
576        }
577    };
578
579    // Recordkeeping of restore-after-install operations that are currently in flight
580    // between the Package Manager and the Backup Manager
581    class PostInstallData {
582        public InstallArgs args;
583        public PackageInstalledInfo res;
584
585        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
586            args = _a;
587            res = _r;
588        }
589    };
590    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
591    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
592
593    private final String mRequiredVerifierPackage;
594
595    private final PackageUsage mPackageUsage = new PackageUsage();
596
597    private class PackageUsage {
598        private static final int WRITE_INTERVAL
599            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
600
601        private final Object mFileLock = new Object();
602        private final AtomicLong mLastWritten = new AtomicLong(0);
603        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
604
605        private boolean mIsHistoricalPackageUsageAvailable = true;
606
607        boolean isHistoricalPackageUsageAvailable() {
608            return mIsHistoricalPackageUsageAvailable;
609        }
610
611        void write(boolean force) {
612            if (force) {
613                writeInternal();
614                return;
615            }
616            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
617                && !DEBUG_DEXOPT) {
618                return;
619            }
620            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
621                new Thread("PackageUsage_DiskWriter") {
622                    @Override
623                    public void run() {
624                        try {
625                            writeInternal();
626                        } finally {
627                            mBackgroundWriteRunning.set(false);
628                        }
629                    }
630                }.start();
631            }
632        }
633
634        private void writeInternal() {
635            synchronized (mPackages) {
636                synchronized (mFileLock) {
637                    AtomicFile file = getFile();
638                    FileOutputStream f = null;
639                    try {
640                        f = file.startWrite();
641                        BufferedOutputStream out = new BufferedOutputStream(f);
642                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
643                        StringBuilder sb = new StringBuilder();
644                        for (PackageParser.Package pkg : mPackages.values()) {
645                            if (pkg.mLastPackageUsageTimeInMills == 0) {
646                                continue;
647                            }
648                            sb.setLength(0);
649                            sb.append(pkg.packageName);
650                            sb.append(' ');
651                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
652                            sb.append('\n');
653                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
654                        }
655                        out.flush();
656                        file.finishWrite(f);
657                    } catch (IOException e) {
658                        if (f != null) {
659                            file.failWrite(f);
660                        }
661                        Log.e(TAG, "Failed to write package usage times", e);
662                    }
663                }
664            }
665            mLastWritten.set(SystemClock.elapsedRealtime());
666        }
667
668        void readLP() {
669            synchronized (mFileLock) {
670                AtomicFile file = getFile();
671                BufferedInputStream in = null;
672                try {
673                    in = new BufferedInputStream(file.openRead());
674                    StringBuffer sb = new StringBuffer();
675                    while (true) {
676                        String packageName = readToken(in, sb, ' ');
677                        if (packageName == null) {
678                            break;
679                        }
680                        String timeInMillisString = readToken(in, sb, '\n');
681                        if (timeInMillisString == null) {
682                            throw new IOException("Failed to find last usage time for package "
683                                                  + packageName);
684                        }
685                        PackageParser.Package pkg = mPackages.get(packageName);
686                        if (pkg == null) {
687                            continue;
688                        }
689                        long timeInMillis;
690                        try {
691                            timeInMillis = Long.parseLong(timeInMillisString.toString());
692                        } catch (NumberFormatException e) {
693                            throw new IOException("Failed to parse " + timeInMillisString
694                                                  + " as a long.", e);
695                        }
696                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
697                    }
698                } catch (FileNotFoundException expected) {
699                    mIsHistoricalPackageUsageAvailable = false;
700                } catch (IOException e) {
701                    Log.w(TAG, "Failed to read package usage times", e);
702                } finally {
703                    IoUtils.closeQuietly(in);
704                }
705            }
706            mLastWritten.set(SystemClock.elapsedRealtime());
707        }
708
709        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
710                throws IOException {
711            sb.setLength(0);
712            while (true) {
713                int ch = in.read();
714                if (ch == -1) {
715                    if (sb.length() == 0) {
716                        return null;
717                    }
718                    throw new IOException("Unexpected EOF");
719                }
720                if (ch == endOfToken) {
721                    return sb.toString();
722                }
723                sb.append((char)ch);
724            }
725        }
726
727        private AtomicFile getFile() {
728            File dataDir = Environment.getDataDirectory();
729            File systemDir = new File(dataDir, "system");
730            File fname = new File(systemDir, "package-usage.list");
731            return new AtomicFile(fname);
732        }
733    }
734
735    class PackageHandler extends Handler {
736        private boolean mBound = false;
737        final ArrayList<HandlerParams> mPendingInstalls =
738            new ArrayList<HandlerParams>();
739
740        private boolean connectToService() {
741            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
742                    " DefaultContainerService");
743            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
744            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
745            if (mContext.bindServiceAsUser(service, mDefContainerConn,
746                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
747                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
748                mBound = true;
749                return true;
750            }
751            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
752            return false;
753        }
754
755        private void disconnectService() {
756            mContainerService = null;
757            mBound = false;
758            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
759            mContext.unbindService(mDefContainerConn);
760            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
761        }
762
763        PackageHandler(Looper looper) {
764            super(looper);
765        }
766
767        public void handleMessage(Message msg) {
768            try {
769                doHandleMessage(msg);
770            } finally {
771                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
772            }
773        }
774
775        void doHandleMessage(Message msg) {
776            switch (msg.what) {
777                case INIT_COPY: {
778                    HandlerParams params = (HandlerParams) msg.obj;
779                    int idx = mPendingInstalls.size();
780                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
781                    // If a bind was already initiated we dont really
782                    // need to do anything. The pending install
783                    // will be processed later on.
784                    if (!mBound) {
785                        // If this is the only one pending we might
786                        // have to bind to the service again.
787                        if (!connectToService()) {
788                            Slog.e(TAG, "Failed to bind to media container service");
789                            params.serviceError();
790                            return;
791                        } else {
792                            // Once we bind to the service, the first
793                            // pending request will be processed.
794                            mPendingInstalls.add(idx, params);
795                        }
796                    } else {
797                        mPendingInstalls.add(idx, params);
798                        // Already bound to the service. Just make
799                        // sure we trigger off processing the first request.
800                        if (idx == 0) {
801                            mHandler.sendEmptyMessage(MCS_BOUND);
802                        }
803                    }
804                    break;
805                }
806                case MCS_BOUND: {
807                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
808                    if (msg.obj != null) {
809                        mContainerService = (IMediaContainerService) msg.obj;
810                    }
811                    if (mContainerService == null) {
812                        // Something seriously wrong. Bail out
813                        Slog.e(TAG, "Cannot bind to media container service");
814                        for (HandlerParams params : mPendingInstalls) {
815                            // Indicate service bind error
816                            params.serviceError();
817                        }
818                        mPendingInstalls.clear();
819                    } else if (mPendingInstalls.size() > 0) {
820                        HandlerParams params = mPendingInstalls.get(0);
821                        if (params != null) {
822                            if (params.startCopy()) {
823                                // We are done...  look for more work or to
824                                // go idle.
825                                if (DEBUG_SD_INSTALL) Log.i(TAG,
826                                        "Checking for more work or unbind...");
827                                // Delete pending install
828                                if (mPendingInstalls.size() > 0) {
829                                    mPendingInstalls.remove(0);
830                                }
831                                if (mPendingInstalls.size() == 0) {
832                                    if (mBound) {
833                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
834                                                "Posting delayed MCS_UNBIND");
835                                        removeMessages(MCS_UNBIND);
836                                        Message ubmsg = obtainMessage(MCS_UNBIND);
837                                        // Unbind after a little delay, to avoid
838                                        // continual thrashing.
839                                        sendMessageDelayed(ubmsg, 10000);
840                                    }
841                                } else {
842                                    // There are more pending requests in queue.
843                                    // Just post MCS_BOUND message to trigger processing
844                                    // of next pending install.
845                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
846                                            "Posting MCS_BOUND for next work");
847                                    mHandler.sendEmptyMessage(MCS_BOUND);
848                                }
849                            }
850                        }
851                    } else {
852                        // Should never happen ideally.
853                        Slog.w(TAG, "Empty queue");
854                    }
855                    break;
856                }
857                case MCS_RECONNECT: {
858                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
859                    if (mPendingInstalls.size() > 0) {
860                        if (mBound) {
861                            disconnectService();
862                        }
863                        if (!connectToService()) {
864                            Slog.e(TAG, "Failed to bind to media container service");
865                            for (HandlerParams params : mPendingInstalls) {
866                                // Indicate service bind error
867                                params.serviceError();
868                            }
869                            mPendingInstalls.clear();
870                        }
871                    }
872                    break;
873                }
874                case MCS_UNBIND: {
875                    // If there is no actual work left, then time to unbind.
876                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
877
878                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
879                        if (mBound) {
880                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
881
882                            disconnectService();
883                        }
884                    } else if (mPendingInstalls.size() > 0) {
885                        // There are more pending requests in queue.
886                        // Just post MCS_BOUND message to trigger processing
887                        // of next pending install.
888                        mHandler.sendEmptyMessage(MCS_BOUND);
889                    }
890
891                    break;
892                }
893                case MCS_GIVE_UP: {
894                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
895                    mPendingInstalls.remove(0);
896                    break;
897                }
898                case SEND_PENDING_BROADCAST: {
899                    String packages[];
900                    ArrayList<String> components[];
901                    int size = 0;
902                    int uids[];
903                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
904                    synchronized (mPackages) {
905                        if (mPendingBroadcasts == null) {
906                            return;
907                        }
908                        size = mPendingBroadcasts.size();
909                        if (size <= 0) {
910                            // Nothing to be done. Just return
911                            return;
912                        }
913                        packages = new String[size];
914                        components = new ArrayList[size];
915                        uids = new int[size];
916                        int i = 0;  // filling out the above arrays
917
918                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
919                            int packageUserId = mPendingBroadcasts.userIdAt(n);
920                            Iterator<Map.Entry<String, ArrayList<String>>> it
921                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
922                                            .entrySet().iterator();
923                            while (it.hasNext() && i < size) {
924                                Map.Entry<String, ArrayList<String>> ent = it.next();
925                                packages[i] = ent.getKey();
926                                components[i] = ent.getValue();
927                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
928                                uids[i] = (ps != null)
929                                        ? UserHandle.getUid(packageUserId, ps.appId)
930                                        : -1;
931                                i++;
932                            }
933                        }
934                        size = i;
935                        mPendingBroadcasts.clear();
936                    }
937                    // Send broadcasts
938                    for (int i = 0; i < size; i++) {
939                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
940                    }
941                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
942                    break;
943                }
944                case START_CLEANING_PACKAGE: {
945                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
946                    final String packageName = (String)msg.obj;
947                    final int userId = msg.arg1;
948                    final boolean andCode = msg.arg2 != 0;
949                    synchronized (mPackages) {
950                        if (userId == UserHandle.USER_ALL) {
951                            int[] users = sUserManager.getUserIds();
952                            for (int user : users) {
953                                mSettings.addPackageToCleanLPw(
954                                        new PackageCleanItem(user, packageName, andCode));
955                            }
956                        } else {
957                            mSettings.addPackageToCleanLPw(
958                                    new PackageCleanItem(userId, packageName, andCode));
959                        }
960                    }
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
962                    startCleaningPackages();
963                } break;
964                case POST_INSTALL: {
965                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
966                    PostInstallData data = mRunningInstalls.get(msg.arg1);
967                    mRunningInstalls.delete(msg.arg1);
968                    boolean deleteOld = false;
969
970                    if (data != null) {
971                        InstallArgs args = data.args;
972                        PackageInstalledInfo res = data.res;
973
974                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
975                            res.removedInfo.sendBroadcast(false, true, false);
976                            Bundle extras = new Bundle(1);
977                            extras.putInt(Intent.EXTRA_UID, res.uid);
978                            // Determine the set of users who are adding this
979                            // package for the first time vs. those who are seeing
980                            // an update.
981                            int[] firstUsers;
982                            int[] updateUsers = new int[0];
983                            if (res.origUsers == null || res.origUsers.length == 0) {
984                                firstUsers = res.newUsers;
985                            } else {
986                                firstUsers = new int[0];
987                                for (int i=0; i<res.newUsers.length; i++) {
988                                    int user = res.newUsers[i];
989                                    boolean isNew = true;
990                                    for (int j=0; j<res.origUsers.length; j++) {
991                                        if (res.origUsers[j] == user) {
992                                            isNew = false;
993                                            break;
994                                        }
995                                    }
996                                    if (isNew) {
997                                        int[] newFirst = new int[firstUsers.length+1];
998                                        System.arraycopy(firstUsers, 0, newFirst, 0,
999                                                firstUsers.length);
1000                                        newFirst[firstUsers.length] = user;
1001                                        firstUsers = newFirst;
1002                                    } else {
1003                                        int[] newUpdate = new int[updateUsers.length+1];
1004                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1005                                                updateUsers.length);
1006                                        newUpdate[updateUsers.length] = user;
1007                                        updateUsers = newUpdate;
1008                                    }
1009                                }
1010                            }
1011                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1012                                    res.pkg.applicationInfo.packageName,
1013                                    extras, null, null, firstUsers);
1014                            final boolean update = res.removedInfo.removedPackage != null;
1015                            if (update) {
1016                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1017                            }
1018                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1019                                    res.pkg.applicationInfo.packageName,
1020                                    extras, null, null, updateUsers);
1021                            if (update) {
1022                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1023                                        res.pkg.applicationInfo.packageName,
1024                                        extras, null, null, updateUsers);
1025                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1026                                        null, null,
1027                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1028
1029                                // treat asec-hosted packages like removable media on upgrade
1030                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1031                                    if (DEBUG_INSTALL) {
1032                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1033                                                + " is ASEC-hosted -> AVAILABLE");
1034                                    }
1035                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1036                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1037                                    pkgList.add(res.pkg.applicationInfo.packageName);
1038                                    sendResourcesChangedBroadcast(true, true,
1039                                            pkgList,uidArray, null);
1040                                }
1041                            }
1042                            if (res.removedInfo.args != null) {
1043                                // Remove the replaced package's older resources safely now
1044                                deleteOld = true;
1045                            }
1046
1047                            // Log current value of "unknown sources" setting
1048                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1049                                getUnknownSourcesSettings());
1050                        }
1051                        // Force a gc to clear up things
1052                        Runtime.getRuntime().gc();
1053                        // We delete after a gc for applications  on sdcard.
1054                        if (deleteOld) {
1055                            synchronized (mInstallLock) {
1056                                res.removedInfo.args.doPostDeleteLI(true);
1057                            }
1058                        }
1059                        if (args.observer != null) {
1060                            try {
1061                                Bundle extras = extrasForInstallResult(res);
1062                                args.observer.onPackageInstalled(res.name, res.returnCode,
1063                                        res.returnMsg, extras);
1064                            } catch (RemoteException e) {
1065                                Slog.i(TAG, "Observer no longer exists.");
1066                            }
1067                        }
1068                    } else {
1069                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1070                    }
1071                } break;
1072                case UPDATED_MEDIA_STATUS: {
1073                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1074                    boolean reportStatus = msg.arg1 == 1;
1075                    boolean doGc = msg.arg2 == 1;
1076                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1077                    if (doGc) {
1078                        // Force a gc to clear up stale containers.
1079                        Runtime.getRuntime().gc();
1080                    }
1081                    if (msg.obj != null) {
1082                        @SuppressWarnings("unchecked")
1083                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1084                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1085                        // Unload containers
1086                        unloadAllContainers(args);
1087                    }
1088                    if (reportStatus) {
1089                        try {
1090                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1091                            PackageHelper.getMountService().finishMediaUpdate();
1092                        } catch (RemoteException e) {
1093                            Log.e(TAG, "MountService not running?");
1094                        }
1095                    }
1096                } break;
1097                case WRITE_SETTINGS: {
1098                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1099                    synchronized (mPackages) {
1100                        removeMessages(WRITE_SETTINGS);
1101                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1102                        mSettings.writeLPr();
1103                        mDirtyUsers.clear();
1104                    }
1105                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1106                } break;
1107                case WRITE_PACKAGE_RESTRICTIONS: {
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109                    synchronized (mPackages) {
1110                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1111                        for (int userId : mDirtyUsers) {
1112                            mSettings.writePackageRestrictionsLPr(userId);
1113                        }
1114                        mDirtyUsers.clear();
1115                    }
1116                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117                } break;
1118                case CHECK_PENDING_VERIFICATION: {
1119                    final int verificationId = msg.arg1;
1120                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1121
1122                    if ((state != null) && !state.timeoutExtended()) {
1123                        final InstallArgs args = state.getInstallArgs();
1124                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1125
1126                        Slog.i(TAG, "Verification timed out for " + originUri);
1127                        mPendingVerification.remove(verificationId);
1128
1129                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1130
1131                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1132                            Slog.i(TAG, "Continuing with installation of " + originUri);
1133                            state.setVerifierResponse(Binder.getCallingUid(),
1134                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1135                            broadcastPackageVerified(verificationId, originUri,
1136                                    PackageManager.VERIFICATION_ALLOW,
1137                                    state.getInstallArgs().getUser());
1138                            try {
1139                                ret = args.copyApk(mContainerService, true);
1140                            } catch (RemoteException e) {
1141                                Slog.e(TAG, "Could not contact the ContainerService");
1142                            }
1143                        } else {
1144                            broadcastPackageVerified(verificationId, originUri,
1145                                    PackageManager.VERIFICATION_REJECT,
1146                                    state.getInstallArgs().getUser());
1147                        }
1148
1149                        processPendingInstall(args, ret);
1150                        mHandler.sendEmptyMessage(MCS_UNBIND);
1151                    }
1152                    break;
1153                }
1154                case PACKAGE_VERIFIED: {
1155                    final int verificationId = msg.arg1;
1156
1157                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1158                    if (state == null) {
1159                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1160                        break;
1161                    }
1162
1163                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1164
1165                    state.setVerifierResponse(response.callerUid, response.code);
1166
1167                    if (state.isVerificationComplete()) {
1168                        mPendingVerification.remove(verificationId);
1169
1170                        final InstallArgs args = state.getInstallArgs();
1171                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1172
1173                        int ret;
1174                        if (state.isInstallAllowed()) {
1175                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1176                            broadcastPackageVerified(verificationId, originUri,
1177                                    response.code, state.getInstallArgs().getUser());
1178                            try {
1179                                ret = args.copyApk(mContainerService, true);
1180                            } catch (RemoteException e) {
1181                                Slog.e(TAG, "Could not contact the ContainerService");
1182                            }
1183                        } else {
1184                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1185                        }
1186
1187                        processPendingInstall(args, ret);
1188
1189                        mHandler.sendEmptyMessage(MCS_UNBIND);
1190                    }
1191
1192                    break;
1193                }
1194            }
1195        }
1196    }
1197
1198    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1199        Bundle extras = null;
1200        switch (res.returnCode) {
1201            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1202                extras = new Bundle();
1203                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1204                        res.origPermission);
1205                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1206                        res.origPackage);
1207                break;
1208            }
1209        }
1210        return extras;
1211    }
1212
1213    void scheduleWriteSettingsLocked() {
1214        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1215            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1216        }
1217    }
1218
1219    void scheduleWritePackageRestrictionsLocked(int userId) {
1220        if (!sUserManager.exists(userId)) return;
1221        mDirtyUsers.add(userId);
1222        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1223            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1224        }
1225    }
1226
1227    public static final PackageManagerService main(Context context, Installer installer,
1228            boolean factoryTest, boolean onlyCore) {
1229        PackageManagerService m = new PackageManagerService(context, installer,
1230                factoryTest, onlyCore);
1231        ServiceManager.addService("package", m);
1232        return m;
1233    }
1234
1235    static String[] splitString(String str, char sep) {
1236        int count = 1;
1237        int i = 0;
1238        while ((i=str.indexOf(sep, i)) >= 0) {
1239            count++;
1240            i++;
1241        }
1242
1243        String[] res = new String[count];
1244        i=0;
1245        count = 0;
1246        int lastI=0;
1247        while ((i=str.indexOf(sep, i)) >= 0) {
1248            res[count] = str.substring(lastI, i);
1249            count++;
1250            i++;
1251            lastI = i;
1252        }
1253        res[count] = str.substring(lastI, str.length());
1254        return res;
1255    }
1256
1257    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1258        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1259                Context.DISPLAY_SERVICE);
1260        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1261    }
1262
1263    public PackageManagerService(Context context, Installer installer,
1264            boolean factoryTest, boolean onlyCore) {
1265        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1266                SystemClock.uptimeMillis());
1267
1268        if (mSdkVersion <= 0) {
1269            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1270        }
1271
1272        mContext = context;
1273        mFactoryTest = factoryTest;
1274        mOnlyCore = onlyCore;
1275        mMetrics = new DisplayMetrics();
1276        mSettings = new Settings(context);
1277        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1278                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1279        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1280                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1281        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1282                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1283        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289
1290        String separateProcesses = SystemProperties.get("debug.separate_processes");
1291        if (separateProcesses != null && separateProcesses.length() > 0) {
1292            if ("*".equals(separateProcesses)) {
1293                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1294                mSeparateProcesses = null;
1295                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1296            } else {
1297                mDefParseFlags = 0;
1298                mSeparateProcesses = separateProcesses.split(",");
1299                Slog.w(TAG, "Running with debug.separate_processes: "
1300                        + separateProcesses);
1301            }
1302        } else {
1303            mDefParseFlags = 0;
1304            mSeparateProcesses = null;
1305        }
1306
1307        mInstaller = installer;
1308
1309        getDefaultDisplayMetrics(context, mMetrics);
1310
1311        SystemConfig systemConfig = SystemConfig.getInstance();
1312        mGlobalGids = systemConfig.getGlobalGids();
1313        mSystemPermissions = systemConfig.getSystemPermissions();
1314        mAvailableFeatures = systemConfig.getAvailableFeatures();
1315
1316        synchronized (mInstallLock) {
1317        // writer
1318        synchronized (mPackages) {
1319            mHandlerThread = new ServiceThread(TAG,
1320                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1321            mHandlerThread.start();
1322            mHandler = new PackageHandler(mHandlerThread.getLooper());
1323            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1324
1325            File dataDir = Environment.getDataDirectory();
1326            mAppDataDir = new File(dataDir, "data");
1327            mAppInstallDir = new File(dataDir, "app");
1328            mAppLib32InstallDir = new File(dataDir, "app-lib");
1329            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1330            mUserAppDataDir = new File(dataDir, "user");
1331            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1332
1333            sUserManager = new UserManagerService(context, this,
1334                    mInstallLock, mPackages);
1335
1336            // Propagate permission configuration in to package manager.
1337            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1338                    = systemConfig.getPermissions();
1339            for (int i=0; i<permConfig.size(); i++) {
1340                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1341                BasePermission bp = mSettings.mPermissions.get(perm.name);
1342                if (bp == null) {
1343                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1344                    mSettings.mPermissions.put(perm.name, bp);
1345                }
1346                if (perm.gids != null) {
1347                    bp.gids = appendInts(bp.gids, perm.gids);
1348                }
1349            }
1350
1351            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1352            for (int i=0; i<libConfig.size(); i++) {
1353                mSharedLibraries.put(libConfig.keyAt(i),
1354                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1355            }
1356
1357            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1358
1359            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1360                    mSdkVersion, mOnlyCore);
1361
1362            String customResolverActivity = Resources.getSystem().getString(
1363                    R.string.config_customResolverActivity);
1364            if (TextUtils.isEmpty(customResolverActivity)) {
1365                customResolverActivity = null;
1366            } else {
1367                mCustomResolverComponentName = ComponentName.unflattenFromString(
1368                        customResolverActivity);
1369            }
1370
1371            long startTime = SystemClock.uptimeMillis();
1372
1373            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1374                    startTime);
1375
1376            // Set flag to monitor and not change apk file paths when
1377            // scanning install directories.
1378            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1379
1380            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1381
1382            /**
1383             * Add everything in the in the boot class path to the
1384             * list of process files because dexopt will have been run
1385             * if necessary during zygote startup.
1386             */
1387            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1388            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1389
1390            if (bootClassPath != null) {
1391                String[] bootClassPathElements = splitString(bootClassPath, ':');
1392                for (String element : bootClassPathElements) {
1393                    alreadyDexOpted.add(element);
1394                }
1395            } else {
1396                Slog.w(TAG, "No BOOTCLASSPATH found!");
1397            }
1398
1399            if (systemServerClassPath != null) {
1400                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1401                for (String element : systemServerClassPathElements) {
1402                    alreadyDexOpted.add(element);
1403                }
1404            } else {
1405                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1406            }
1407
1408            boolean didDexOptLibraryOrTool = false;
1409
1410            final List<String> allInstructionSets = getAllInstructionSets();
1411            final String[] dexCodeInstructionSets =
1412                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1413
1414            /**
1415             * Ensure all external libraries have had dexopt run on them.
1416             */
1417            if (mSharedLibraries.size() > 0) {
1418                // NOTE: For now, we're compiling these system "shared libraries"
1419                // (and framework jars) into all available architectures. It's possible
1420                // to compile them only when we come across an app that uses them (there's
1421                // already logic for that in scanPackageLI) but that adds some complexity.
1422                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1423                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1424                        final String lib = libEntry.path;
1425                        if (lib == null) {
1426                            continue;
1427                        }
1428
1429                        try {
1430                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1431                                                                                 dexCodeInstructionSet,
1432                                                                                 false);
1433                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1434                                alreadyDexOpted.add(lib);
1435
1436                                // The list of "shared libraries" we have at this point is
1437                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1438                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1439                                } else {
1440                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1441                                }
1442                                didDexOptLibraryOrTool = true;
1443                            }
1444                        } catch (FileNotFoundException e) {
1445                            Slog.w(TAG, "Library not found: " + lib);
1446                        } catch (IOException e) {
1447                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1448                                    + e.getMessage());
1449                        }
1450                    }
1451                }
1452            }
1453
1454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1455
1456            // Gross hack for now: we know this file doesn't contain any
1457            // code, so don't dexopt it to avoid the resulting log spew.
1458            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1459
1460            // Gross hack for now: we know this file is only part of
1461            // the boot class path for art, so don't dexopt it to
1462            // avoid the resulting log spew.
1463            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1464
1465            /**
1466             * And there are a number of commands implemented in Java, which
1467             * we currently need to do the dexopt on so that they can be
1468             * run from a non-root shell.
1469             */
1470            String[] frameworkFiles = frameworkDir.list();
1471            if (frameworkFiles != null) {
1472                // TODO: We could compile these only for the most preferred ABI. We should
1473                // first double check that the dex files for these commands are not referenced
1474                // by other system apps.
1475                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1476                    for (int i=0; i<frameworkFiles.length; i++) {
1477                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1478                        String path = libPath.getPath();
1479                        // Skip the file if we already did it.
1480                        if (alreadyDexOpted.contains(path)) {
1481                            continue;
1482                        }
1483                        // Skip the file if it is not a type we want to dexopt.
1484                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1485                            continue;
1486                        }
1487                        try {
1488                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1489                                                                                 dexCodeInstructionSet,
1490                                                                                 false);
1491                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1492                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1493                                didDexOptLibraryOrTool = true;
1494                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1495                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1496                                didDexOptLibraryOrTool = true;
1497                            }
1498                        } catch (FileNotFoundException e) {
1499                            Slog.w(TAG, "Jar not found: " + path);
1500                        } catch (IOException e) {
1501                            Slog.w(TAG, "Exception reading jar: " + path, e);
1502                        }
1503                    }
1504                }
1505            }
1506
1507            // Collect vendor overlay packages.
1508            // (Do this before scanning any apps.)
1509            // For security and version matching reason, only consider
1510            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1511            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1512            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1513                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1514
1515            // Find base frameworks (resource packages without code).
1516            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1517                    | PackageParser.PARSE_IS_SYSTEM_DIR
1518                    | PackageParser.PARSE_IS_PRIVILEGED,
1519                    scanFlags | SCAN_NO_DEX, 0);
1520
1521            // Collected privileged system packages.
1522            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1523            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1524                    | PackageParser.PARSE_IS_SYSTEM_DIR
1525                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1526
1527            // Collect ordinary system packages.
1528            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1529            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1530                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1531
1532            // Collect all vendor packages.
1533            File vendorAppDir = new File("/vendor/app");
1534            try {
1535                vendorAppDir = vendorAppDir.getCanonicalFile();
1536            } catch (IOException e) {
1537                // failed to look up canonical path, continue with original one
1538            }
1539            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1540                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1541
1542            // Collect all OEM packages.
1543            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1544            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1546
1547            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1548            mInstaller.moveFiles();
1549
1550            // Prune any system packages that no longer exist.
1551            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1552            if (!mOnlyCore) {
1553                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1554                while (psit.hasNext()) {
1555                    PackageSetting ps = psit.next();
1556
1557                    /*
1558                     * If this is not a system app, it can't be a
1559                     * disable system app.
1560                     */
1561                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1562                        continue;
1563                    }
1564
1565                    /*
1566                     * If the package is scanned, it's not erased.
1567                     */
1568                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1569                    if (scannedPkg != null) {
1570                        /*
1571                         * If the system app is both scanned and in the
1572                         * disabled packages list, then it must have been
1573                         * added via OTA. Remove it from the currently
1574                         * scanned package so the previously user-installed
1575                         * application can be scanned.
1576                         */
1577                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1578                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1579                                    + "; removing system app");
1580                            removePackageLI(ps, true);
1581                        }
1582
1583                        continue;
1584                    }
1585
1586                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1587                        psit.remove();
1588                        String msg = "System package " + ps.name
1589                                + " no longer exists; wiping its data";
1590                        reportSettingsProblem(Log.WARN, msg);
1591                        removeDataDirsLI(ps.name);
1592                    } else {
1593                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1594                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1595                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1596                        }
1597                    }
1598                }
1599            }
1600
1601            //look for any incomplete package installations
1602            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1603            //clean up list
1604            for(int i = 0; i < deletePkgsList.size(); i++) {
1605                //clean up here
1606                cleanupInstallFailedPackage(deletePkgsList.get(i));
1607            }
1608            //delete tmp files
1609            deleteTempPackageFiles();
1610
1611            // Remove any shared userIDs that have no associated packages
1612            mSettings.pruneSharedUsersLPw();
1613
1614            if (!mOnlyCore) {
1615                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1616                        SystemClock.uptimeMillis());
1617                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1618
1619                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1620                        scanFlags, 0);
1621
1622                /**
1623                 * Remove disable package settings for any updated system
1624                 * apps that were removed via an OTA. If they're not a
1625                 * previously-updated app, remove them completely.
1626                 * Otherwise, just revoke their system-level permissions.
1627                 */
1628                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1629                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1630                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1631
1632                    String msg;
1633                    if (deletedPkg == null) {
1634                        msg = "Updated system package " + deletedAppName
1635                                + " no longer exists; wiping its data";
1636                        removeDataDirsLI(deletedAppName);
1637                    } else {
1638                        msg = "Updated system app + " + deletedAppName
1639                                + " no longer present; removing system privileges for "
1640                                + deletedAppName;
1641
1642                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1643
1644                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1645                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1646                    }
1647                    reportSettingsProblem(Log.WARN, msg);
1648                }
1649            }
1650
1651            // Now that we know all of the shared libraries, update all clients to have
1652            // the correct library paths.
1653            updateAllSharedLibrariesLPw();
1654
1655            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1656                // NOTE: We ignore potential failures here during a system scan (like
1657                // the rest of the commands above) because there's precious little we
1658                // can do about it. A settings error is reported, though.
1659                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1660                        false /* force dexopt */, false /* defer dexopt */);
1661            }
1662
1663            // Now that we know all the packages we are keeping,
1664            // read and update their last usage times.
1665            mPackageUsage.readLP();
1666
1667            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1668                    SystemClock.uptimeMillis());
1669            Slog.i(TAG, "Time to scan packages: "
1670                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1671                    + " seconds");
1672
1673            // If the platform SDK has changed since the last time we booted,
1674            // we need to re-grant app permission to catch any new ones that
1675            // appear.  This is really a hack, and means that apps can in some
1676            // cases get permissions that the user didn't initially explicitly
1677            // allow...  it would be nice to have some better way to handle
1678            // this situation.
1679            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1680                    != mSdkVersion;
1681            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1682                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1683                    + "; regranting permissions for internal storage");
1684            mSettings.mInternalSdkPlatform = mSdkVersion;
1685
1686            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1687                    | (regrantPermissions
1688                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1689                            : 0));
1690
1691            // If this is the first boot, and it is a normal boot, then
1692            // we need to initialize the default preferred apps.
1693            if (!mRestoredSettings && !onlyCore) {
1694                mSettings.readDefaultPreferredAppsLPw(this, 0);
1695            }
1696
1697            // If this is first boot after an OTA, and a normal boot, then
1698            // we need to clear code cache directories.
1699            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1700                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1701                for (String pkgName : mSettings.mPackages.keySet()) {
1702                    deleteCodeCacheDirsLI(pkgName);
1703                }
1704                mSettings.mFingerprint = Build.FINGERPRINT;
1705            }
1706
1707            // All the changes are done during package scanning.
1708            mSettings.updateInternalDatabaseVersion();
1709
1710            // can downgrade to reader
1711            mSettings.writeLPr();
1712
1713            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1714                    SystemClock.uptimeMillis());
1715
1716
1717            mRequiredVerifierPackage = getRequiredVerifierLPr();
1718        } // synchronized (mPackages)
1719        } // synchronized (mInstallLock)
1720
1721        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1722
1723        // Now after opening every single application zip, make sure they
1724        // are all flushed.  Not really needed, but keeps things nice and
1725        // tidy.
1726        Runtime.getRuntime().gc();
1727    }
1728
1729    @Override
1730    public boolean isFirstBoot() {
1731        return !mRestoredSettings;
1732    }
1733
1734    @Override
1735    public boolean isOnlyCoreApps() {
1736        return mOnlyCore;
1737    }
1738
1739    private String getRequiredVerifierLPr() {
1740        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1741        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1742                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1743
1744        String requiredVerifier = null;
1745
1746        final int N = receivers.size();
1747        for (int i = 0; i < N; i++) {
1748            final ResolveInfo info = receivers.get(i);
1749
1750            if (info.activityInfo == null) {
1751                continue;
1752            }
1753
1754            final String packageName = info.activityInfo.packageName;
1755
1756            final PackageSetting ps = mSettings.mPackages.get(packageName);
1757            if (ps == null) {
1758                continue;
1759            }
1760
1761            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1762            if (!gp.grantedPermissions
1763                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1764                continue;
1765            }
1766
1767            if (requiredVerifier != null) {
1768                throw new RuntimeException("There can be only one required verifier");
1769            }
1770
1771            requiredVerifier = packageName;
1772        }
1773
1774        return requiredVerifier;
1775    }
1776
1777    @Override
1778    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1779            throws RemoteException {
1780        try {
1781            return super.onTransact(code, data, reply, flags);
1782        } catch (RuntimeException e) {
1783            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1784                Slog.wtf(TAG, "Package Manager Crash", e);
1785            }
1786            throw e;
1787        }
1788    }
1789
1790    void cleanupInstallFailedPackage(PackageSetting ps) {
1791        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1792        removeDataDirsLI(ps.name);
1793
1794        // TODO: try cleaning up codePath directory contents first, since it
1795        // might be a cluster
1796
1797        if (ps.codePath != null) {
1798            if (!ps.codePath.delete()) {
1799                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1800            }
1801        }
1802        if (ps.resourcePath != null) {
1803            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1804                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1805            }
1806        }
1807        mSettings.removePackageLPw(ps.name);
1808    }
1809
1810    static int[] appendInts(int[] cur, int[] add) {
1811        if (add == null) return cur;
1812        if (cur == null) return add;
1813        final int N = add.length;
1814        for (int i=0; i<N; i++) {
1815            cur = appendInt(cur, add[i]);
1816        }
1817        return cur;
1818    }
1819
1820    static int[] removeInts(int[] cur, int[] rem) {
1821        if (rem == null) return cur;
1822        if (cur == null) return cur;
1823        final int N = rem.length;
1824        for (int i=0; i<N; i++) {
1825            cur = removeInt(cur, rem[i]);
1826        }
1827        return cur;
1828    }
1829
1830    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1831        if (!sUserManager.exists(userId)) return null;
1832        final PackageSetting ps = (PackageSetting) p.mExtras;
1833        if (ps == null) {
1834            return null;
1835        }
1836        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1837        final PackageUserState state = ps.readUserState(userId);
1838        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1839                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1840                state, userId);
1841    }
1842
1843    @Override
1844    public boolean isPackageAvailable(String packageName, int userId) {
1845        if (!sUserManager.exists(userId)) return false;
1846        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1847        synchronized (mPackages) {
1848            PackageParser.Package p = mPackages.get(packageName);
1849            if (p != null) {
1850                final PackageSetting ps = (PackageSetting) p.mExtras;
1851                if (ps != null) {
1852                    final PackageUserState state = ps.readUserState(userId);
1853                    if (state != null) {
1854                        return PackageParser.isAvailable(state);
1855                    }
1856                }
1857            }
1858        }
1859        return false;
1860    }
1861
1862    @Override
1863    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1864        if (!sUserManager.exists(userId)) return null;
1865        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1866        // reader
1867        synchronized (mPackages) {
1868            PackageParser.Package p = mPackages.get(packageName);
1869            if (DEBUG_PACKAGE_INFO)
1870                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1871            if (p != null) {
1872                return generatePackageInfo(p, flags, userId);
1873            }
1874            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1875                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1876            }
1877        }
1878        return null;
1879    }
1880
1881    @Override
1882    public String[] currentToCanonicalPackageNames(String[] names) {
1883        String[] out = new String[names.length];
1884        // reader
1885        synchronized (mPackages) {
1886            for (int i=names.length-1; i>=0; i--) {
1887                PackageSetting ps = mSettings.mPackages.get(names[i]);
1888                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1889            }
1890        }
1891        return out;
1892    }
1893
1894    @Override
1895    public String[] canonicalToCurrentPackageNames(String[] names) {
1896        String[] out = new String[names.length];
1897        // reader
1898        synchronized (mPackages) {
1899            for (int i=names.length-1; i>=0; i--) {
1900                String cur = mSettings.mRenamedPackages.get(names[i]);
1901                out[i] = cur != null ? cur : names[i];
1902            }
1903        }
1904        return out;
1905    }
1906
1907    @Override
1908    public int getPackageUid(String packageName, int userId) {
1909        if (!sUserManager.exists(userId)) return -1;
1910        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1911        // reader
1912        synchronized (mPackages) {
1913            PackageParser.Package p = mPackages.get(packageName);
1914            if(p != null) {
1915                return UserHandle.getUid(userId, p.applicationInfo.uid);
1916            }
1917            PackageSetting ps = mSettings.mPackages.get(packageName);
1918            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1919                return -1;
1920            }
1921            p = ps.pkg;
1922            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1923        }
1924    }
1925
1926    @Override
1927    public int[] getPackageGids(String packageName) {
1928        // reader
1929        synchronized (mPackages) {
1930            PackageParser.Package p = mPackages.get(packageName);
1931            if (DEBUG_PACKAGE_INFO)
1932                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1933            if (p != null) {
1934                final PackageSetting ps = (PackageSetting)p.mExtras;
1935                return ps.getGids();
1936            }
1937        }
1938        // stupid thing to indicate an error.
1939        return new int[0];
1940    }
1941
1942    static final PermissionInfo generatePermissionInfo(
1943            BasePermission bp, int flags) {
1944        if (bp.perm != null) {
1945            return PackageParser.generatePermissionInfo(bp.perm, flags);
1946        }
1947        PermissionInfo pi = new PermissionInfo();
1948        pi.name = bp.name;
1949        pi.packageName = bp.sourcePackage;
1950        pi.nonLocalizedLabel = bp.name;
1951        pi.protectionLevel = bp.protectionLevel;
1952        return pi;
1953    }
1954
1955    @Override
1956    public PermissionInfo getPermissionInfo(String name, int flags) {
1957        // reader
1958        synchronized (mPackages) {
1959            final BasePermission p = mSettings.mPermissions.get(name);
1960            if (p != null) {
1961                return generatePermissionInfo(p, flags);
1962            }
1963            return null;
1964        }
1965    }
1966
1967    @Override
1968    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1969        // reader
1970        synchronized (mPackages) {
1971            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1972            for (BasePermission p : mSettings.mPermissions.values()) {
1973                if (group == null) {
1974                    if (p.perm == null || p.perm.info.group == null) {
1975                        out.add(generatePermissionInfo(p, flags));
1976                    }
1977                } else {
1978                    if (p.perm != null && group.equals(p.perm.info.group)) {
1979                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1980                    }
1981                }
1982            }
1983
1984            if (out.size() > 0) {
1985                return out;
1986            }
1987            return mPermissionGroups.containsKey(group) ? out : null;
1988        }
1989    }
1990
1991    @Override
1992    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1993        // reader
1994        synchronized (mPackages) {
1995            return PackageParser.generatePermissionGroupInfo(
1996                    mPermissionGroups.get(name), flags);
1997        }
1998    }
1999
2000    @Override
2001    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2002        // reader
2003        synchronized (mPackages) {
2004            final int N = mPermissionGroups.size();
2005            ArrayList<PermissionGroupInfo> out
2006                    = new ArrayList<PermissionGroupInfo>(N);
2007            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2008                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2009            }
2010            return out;
2011        }
2012    }
2013
2014    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2015            int userId) {
2016        if (!sUserManager.exists(userId)) return null;
2017        PackageSetting ps = mSettings.mPackages.get(packageName);
2018        if (ps != null) {
2019            if (ps.pkg == null) {
2020                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2021                        flags, userId);
2022                if (pInfo != null) {
2023                    return pInfo.applicationInfo;
2024                }
2025                return null;
2026            }
2027            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2028                    ps.readUserState(userId), userId);
2029        }
2030        return null;
2031    }
2032
2033    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2034            int userId) {
2035        if (!sUserManager.exists(userId)) return null;
2036        PackageSetting ps = mSettings.mPackages.get(packageName);
2037        if (ps != null) {
2038            PackageParser.Package pkg = ps.pkg;
2039            if (pkg == null) {
2040                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2041                    return null;
2042                }
2043                // Only data remains, so we aren't worried about code paths
2044                pkg = new PackageParser.Package(packageName);
2045                pkg.applicationInfo.packageName = packageName;
2046                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2047                pkg.applicationInfo.dataDir =
2048                        getDataPathForPackage(packageName, 0).getPath();
2049                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2050                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2051            }
2052            return generatePackageInfo(pkg, flags, userId);
2053        }
2054        return null;
2055    }
2056
2057    @Override
2058    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2059        if (!sUserManager.exists(userId)) return null;
2060        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2061        // writer
2062        synchronized (mPackages) {
2063            PackageParser.Package p = mPackages.get(packageName);
2064            if (DEBUG_PACKAGE_INFO) Log.v(
2065                    TAG, "getApplicationInfo " + packageName
2066                    + ": " + p);
2067            if (p != null) {
2068                PackageSetting ps = mSettings.mPackages.get(packageName);
2069                if (ps == null) return null;
2070                // Note: isEnabledLP() does not apply here - always return info
2071                return PackageParser.generateApplicationInfo(
2072                        p, flags, ps.readUserState(userId), userId);
2073            }
2074            if ("android".equals(packageName)||"system".equals(packageName)) {
2075                return mAndroidApplication;
2076            }
2077            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2078                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2079            }
2080        }
2081        return null;
2082    }
2083
2084
2085    @Override
2086    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2087        mContext.enforceCallingOrSelfPermission(
2088                android.Manifest.permission.CLEAR_APP_CACHE, null);
2089        // Queue up an async operation since clearing cache may take a little while.
2090        mHandler.post(new Runnable() {
2091            public void run() {
2092                mHandler.removeCallbacks(this);
2093                int retCode = -1;
2094                synchronized (mInstallLock) {
2095                    retCode = mInstaller.freeCache(freeStorageSize);
2096                    if (retCode < 0) {
2097                        Slog.w(TAG, "Couldn't clear application caches");
2098                    }
2099                }
2100                if (observer != null) {
2101                    try {
2102                        observer.onRemoveCompleted(null, (retCode >= 0));
2103                    } catch (RemoteException e) {
2104                        Slog.w(TAG, "RemoveException when invoking call back");
2105                    }
2106                }
2107            }
2108        });
2109    }
2110
2111    @Override
2112    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2113        mContext.enforceCallingOrSelfPermission(
2114                android.Manifest.permission.CLEAR_APP_CACHE, null);
2115        // Queue up an async operation since clearing cache may take a little while.
2116        mHandler.post(new Runnable() {
2117            public void run() {
2118                mHandler.removeCallbacks(this);
2119                int retCode = -1;
2120                synchronized (mInstallLock) {
2121                    retCode = mInstaller.freeCache(freeStorageSize);
2122                    if (retCode < 0) {
2123                        Slog.w(TAG, "Couldn't clear application caches");
2124                    }
2125                }
2126                if(pi != null) {
2127                    try {
2128                        // Callback via pending intent
2129                        int code = (retCode >= 0) ? 1 : 0;
2130                        pi.sendIntent(null, code, null,
2131                                null, null);
2132                    } catch (SendIntentException e1) {
2133                        Slog.i(TAG, "Failed to send pending intent");
2134                    }
2135                }
2136            }
2137        });
2138    }
2139
2140    void freeStorage(long freeStorageSize) throws IOException {
2141        synchronized (mInstallLock) {
2142            if (mInstaller.freeCache(freeStorageSize) < 0) {
2143                throw new IOException("Failed to free enough space");
2144            }
2145        }
2146    }
2147
2148    @Override
2149    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2150        if (!sUserManager.exists(userId)) return null;
2151        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2152        synchronized (mPackages) {
2153            PackageParser.Activity a = mActivities.mActivities.get(component);
2154
2155            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2156            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2157                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2158                if (ps == null) return null;
2159                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2160                        userId);
2161            }
2162            if (mResolveComponentName.equals(component)) {
2163                return mResolveActivity;
2164            }
2165        }
2166        return null;
2167    }
2168
2169    @Override
2170    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2171            String resolvedType) {
2172        synchronized (mPackages) {
2173            PackageParser.Activity a = mActivities.mActivities.get(component);
2174            if (a == null) {
2175                return false;
2176            }
2177            for (int i=0; i<a.intents.size(); i++) {
2178                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2179                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2180                    return true;
2181                }
2182            }
2183            return false;
2184        }
2185    }
2186
2187    @Override
2188    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2189        if (!sUserManager.exists(userId)) return null;
2190        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2191        synchronized (mPackages) {
2192            PackageParser.Activity a = mReceivers.mActivities.get(component);
2193            if (DEBUG_PACKAGE_INFO) Log.v(
2194                TAG, "getReceiverInfo " + component + ": " + a);
2195            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2196                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2197                if (ps == null) return null;
2198                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2199                        userId);
2200            }
2201        }
2202        return null;
2203    }
2204
2205    @Override
2206    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2207        if (!sUserManager.exists(userId)) return null;
2208        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2209        synchronized (mPackages) {
2210            PackageParser.Service s = mServices.mServices.get(component);
2211            if (DEBUG_PACKAGE_INFO) Log.v(
2212                TAG, "getServiceInfo " + component + ": " + s);
2213            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2214                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2215                if (ps == null) return null;
2216                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2217                        userId);
2218            }
2219        }
2220        return null;
2221    }
2222
2223    @Override
2224    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2225        if (!sUserManager.exists(userId)) return null;
2226        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2227        synchronized (mPackages) {
2228            PackageParser.Provider p = mProviders.mProviders.get(component);
2229            if (DEBUG_PACKAGE_INFO) Log.v(
2230                TAG, "getProviderInfo " + component + ": " + p);
2231            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2232                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2233                if (ps == null) return null;
2234                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2235                        userId);
2236            }
2237        }
2238        return null;
2239    }
2240
2241    @Override
2242    public String[] getSystemSharedLibraryNames() {
2243        Set<String> libSet;
2244        synchronized (mPackages) {
2245            libSet = mSharedLibraries.keySet();
2246            int size = libSet.size();
2247            if (size > 0) {
2248                String[] libs = new String[size];
2249                libSet.toArray(libs);
2250                return libs;
2251            }
2252        }
2253        return null;
2254    }
2255
2256    @Override
2257    public FeatureInfo[] getSystemAvailableFeatures() {
2258        Collection<FeatureInfo> featSet;
2259        synchronized (mPackages) {
2260            featSet = mAvailableFeatures.values();
2261            int size = featSet.size();
2262            if (size > 0) {
2263                FeatureInfo[] features = new FeatureInfo[size+1];
2264                featSet.toArray(features);
2265                FeatureInfo fi = new FeatureInfo();
2266                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2267                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2268                features[size] = fi;
2269                return features;
2270            }
2271        }
2272        return null;
2273    }
2274
2275    @Override
2276    public boolean hasSystemFeature(String name) {
2277        synchronized (mPackages) {
2278            return mAvailableFeatures.containsKey(name);
2279        }
2280    }
2281
2282    private void checkValidCaller(int uid, int userId) {
2283        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2284            return;
2285
2286        throw new SecurityException("Caller uid=" + uid
2287                + " is not privileged to communicate with user=" + userId);
2288    }
2289
2290    @Override
2291    public int checkPermission(String permName, String pkgName) {
2292        synchronized (mPackages) {
2293            PackageParser.Package p = mPackages.get(pkgName);
2294            if (p != null && p.mExtras != null) {
2295                PackageSetting ps = (PackageSetting)p.mExtras;
2296                if (ps.sharedUser != null) {
2297                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2298                        return PackageManager.PERMISSION_GRANTED;
2299                    }
2300                } else if (ps.grantedPermissions.contains(permName)) {
2301                    return PackageManager.PERMISSION_GRANTED;
2302                }
2303            }
2304        }
2305        return PackageManager.PERMISSION_DENIED;
2306    }
2307
2308    @Override
2309    public int checkUidPermission(String permName, int uid) {
2310        synchronized (mPackages) {
2311            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2312            if (obj != null) {
2313                GrantedPermissions gp = (GrantedPermissions)obj;
2314                if (gp.grantedPermissions.contains(permName)) {
2315                    return PackageManager.PERMISSION_GRANTED;
2316                }
2317            } else {
2318                HashSet<String> perms = mSystemPermissions.get(uid);
2319                if (perms != null && perms.contains(permName)) {
2320                    return PackageManager.PERMISSION_GRANTED;
2321                }
2322            }
2323        }
2324        return PackageManager.PERMISSION_DENIED;
2325    }
2326
2327    /**
2328     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2329     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2330     * @param message the message to log on security exception
2331     */
2332    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2333            String message) {
2334        if (userId < 0) {
2335            throw new IllegalArgumentException("Invalid userId " + userId);
2336        }
2337        if (userId == UserHandle.getUserId(callingUid)) return;
2338        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2339            if (requireFullPermission) {
2340                mContext.enforceCallingOrSelfPermission(
2341                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2342            } else {
2343                try {
2344                    mContext.enforceCallingOrSelfPermission(
2345                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2346                } catch (SecurityException se) {
2347                    mContext.enforceCallingOrSelfPermission(
2348                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2349                }
2350            }
2351        }
2352    }
2353
2354    private BasePermission findPermissionTreeLP(String permName) {
2355        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2356            if (permName.startsWith(bp.name) &&
2357                    permName.length() > bp.name.length() &&
2358                    permName.charAt(bp.name.length()) == '.') {
2359                return bp;
2360            }
2361        }
2362        return null;
2363    }
2364
2365    private BasePermission checkPermissionTreeLP(String permName) {
2366        if (permName != null) {
2367            BasePermission bp = findPermissionTreeLP(permName);
2368            if (bp != null) {
2369                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2370                    return bp;
2371                }
2372                throw new SecurityException("Calling uid "
2373                        + Binder.getCallingUid()
2374                        + " is not allowed to add to permission tree "
2375                        + bp.name + " owned by uid " + bp.uid);
2376            }
2377        }
2378        throw new SecurityException("No permission tree found for " + permName);
2379    }
2380
2381    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2382        if (s1 == null) {
2383            return s2 == null;
2384        }
2385        if (s2 == null) {
2386            return false;
2387        }
2388        if (s1.getClass() != s2.getClass()) {
2389            return false;
2390        }
2391        return s1.equals(s2);
2392    }
2393
2394    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2395        if (pi1.icon != pi2.icon) return false;
2396        if (pi1.logo != pi2.logo) return false;
2397        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2398        if (!compareStrings(pi1.name, pi2.name)) return false;
2399        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2400        // We'll take care of setting this one.
2401        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2402        // These are not currently stored in settings.
2403        //if (!compareStrings(pi1.group, pi2.group)) return false;
2404        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2405        //if (pi1.labelRes != pi2.labelRes) return false;
2406        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2407        return true;
2408    }
2409
2410    int permissionInfoFootprint(PermissionInfo info) {
2411        int size = info.name.length();
2412        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2413        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2414        return size;
2415    }
2416
2417    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2418        int size = 0;
2419        for (BasePermission perm : mSettings.mPermissions.values()) {
2420            if (perm.uid == tree.uid) {
2421                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2422            }
2423        }
2424        return size;
2425    }
2426
2427    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2428        // We calculate the max size of permissions defined by this uid and throw
2429        // if that plus the size of 'info' would exceed our stated maximum.
2430        if (tree.uid != Process.SYSTEM_UID) {
2431            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2432            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2433                throw new SecurityException("Permission tree size cap exceeded");
2434            }
2435        }
2436    }
2437
2438    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2439        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2440            throw new SecurityException("Label must be specified in permission");
2441        }
2442        BasePermission tree = checkPermissionTreeLP(info.name);
2443        BasePermission bp = mSettings.mPermissions.get(info.name);
2444        boolean added = bp == null;
2445        boolean changed = true;
2446        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2447        if (added) {
2448            enforcePermissionCapLocked(info, tree);
2449            bp = new BasePermission(info.name, tree.sourcePackage,
2450                    BasePermission.TYPE_DYNAMIC);
2451        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2452            throw new SecurityException(
2453                    "Not allowed to modify non-dynamic permission "
2454                    + info.name);
2455        } else {
2456            if (bp.protectionLevel == fixedLevel
2457                    && bp.perm.owner.equals(tree.perm.owner)
2458                    && bp.uid == tree.uid
2459                    && comparePermissionInfos(bp.perm.info, info)) {
2460                changed = false;
2461            }
2462        }
2463        bp.protectionLevel = fixedLevel;
2464        info = new PermissionInfo(info);
2465        info.protectionLevel = fixedLevel;
2466        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2467        bp.perm.info.packageName = tree.perm.info.packageName;
2468        bp.uid = tree.uid;
2469        if (added) {
2470            mSettings.mPermissions.put(info.name, bp);
2471        }
2472        if (changed) {
2473            if (!async) {
2474                mSettings.writeLPr();
2475            } else {
2476                scheduleWriteSettingsLocked();
2477            }
2478        }
2479        return added;
2480    }
2481
2482    @Override
2483    public boolean addPermission(PermissionInfo info) {
2484        synchronized (mPackages) {
2485            return addPermissionLocked(info, false);
2486        }
2487    }
2488
2489    @Override
2490    public boolean addPermissionAsync(PermissionInfo info) {
2491        synchronized (mPackages) {
2492            return addPermissionLocked(info, true);
2493        }
2494    }
2495
2496    @Override
2497    public void removePermission(String name) {
2498        synchronized (mPackages) {
2499            checkPermissionTreeLP(name);
2500            BasePermission bp = mSettings.mPermissions.get(name);
2501            if (bp != null) {
2502                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2503                    throw new SecurityException(
2504                            "Not allowed to modify non-dynamic permission "
2505                            + name);
2506                }
2507                mSettings.mPermissions.remove(name);
2508                mSettings.writeLPr();
2509            }
2510        }
2511    }
2512
2513    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2514        int index = pkg.requestedPermissions.indexOf(bp.name);
2515        if (index == -1) {
2516            throw new SecurityException("Package " + pkg.packageName
2517                    + " has not requested permission " + bp.name);
2518        }
2519        boolean isNormal =
2520                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2521                        == PermissionInfo.PROTECTION_NORMAL);
2522        boolean isDangerous =
2523                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2524                        == PermissionInfo.PROTECTION_DANGEROUS);
2525        boolean isDevelopment =
2526                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2527
2528        if (!isNormal && !isDangerous && !isDevelopment) {
2529            throw new SecurityException("Permission " + bp.name
2530                    + " is not a changeable permission type");
2531        }
2532
2533        if (isNormal || isDangerous) {
2534            if (pkg.requestedPermissionsRequired.get(index)) {
2535                throw new SecurityException("Can't change " + bp.name
2536                        + ". It is required by the application");
2537            }
2538        }
2539    }
2540
2541    @Override
2542    public void grantPermission(String packageName, String permissionName) {
2543        mContext.enforceCallingOrSelfPermission(
2544                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2545        synchronized (mPackages) {
2546            final PackageParser.Package pkg = mPackages.get(packageName);
2547            if (pkg == null) {
2548                throw new IllegalArgumentException("Unknown package: " + packageName);
2549            }
2550            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2551            if (bp == null) {
2552                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2553            }
2554
2555            checkGrantRevokePermissions(pkg, bp);
2556
2557            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2558            if (ps == null) {
2559                return;
2560            }
2561            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2562            if (gp.grantedPermissions.add(permissionName)) {
2563                if (ps.haveGids) {
2564                    gp.gids = appendInts(gp.gids, bp.gids);
2565                }
2566                mSettings.writeLPr();
2567            }
2568        }
2569    }
2570
2571    @Override
2572    public void revokePermission(String packageName, String permissionName) {
2573        int changedAppId = -1;
2574
2575        synchronized (mPackages) {
2576            final PackageParser.Package pkg = mPackages.get(packageName);
2577            if (pkg == null) {
2578                throw new IllegalArgumentException("Unknown package: " + packageName);
2579            }
2580            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2581                mContext.enforceCallingOrSelfPermission(
2582                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2583            }
2584            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2585            if (bp == null) {
2586                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2587            }
2588
2589            checkGrantRevokePermissions(pkg, bp);
2590
2591            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2592            if (ps == null) {
2593                return;
2594            }
2595            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2596            if (gp.grantedPermissions.remove(permissionName)) {
2597                gp.grantedPermissions.remove(permissionName);
2598                if (ps.haveGids) {
2599                    gp.gids = removeInts(gp.gids, bp.gids);
2600                }
2601                mSettings.writeLPr();
2602                changedAppId = ps.appId;
2603            }
2604        }
2605
2606        if (changedAppId >= 0) {
2607            // We changed the perm on someone, kill its processes.
2608            IActivityManager am = ActivityManagerNative.getDefault();
2609            if (am != null) {
2610                final int callingUserId = UserHandle.getCallingUserId();
2611                final long ident = Binder.clearCallingIdentity();
2612                try {
2613                    //XXX we should only revoke for the calling user's app permissions,
2614                    // but for now we impact all users.
2615                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2616                    //        "revoke " + permissionName);
2617                    int[] users = sUserManager.getUserIds();
2618                    for (int user : users) {
2619                        am.killUid(UserHandle.getUid(user, changedAppId),
2620                                "revoke " + permissionName);
2621                    }
2622                } catch (RemoteException e) {
2623                } finally {
2624                    Binder.restoreCallingIdentity(ident);
2625                }
2626            }
2627        }
2628    }
2629
2630    @Override
2631    public boolean isProtectedBroadcast(String actionName) {
2632        synchronized (mPackages) {
2633            return mProtectedBroadcasts.contains(actionName);
2634        }
2635    }
2636
2637    @Override
2638    public int checkSignatures(String pkg1, String pkg2) {
2639        synchronized (mPackages) {
2640            final PackageParser.Package p1 = mPackages.get(pkg1);
2641            final PackageParser.Package p2 = mPackages.get(pkg2);
2642            if (p1 == null || p1.mExtras == null
2643                    || p2 == null || p2.mExtras == null) {
2644                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2645            }
2646            return compareSignatures(p1.mSignatures, p2.mSignatures);
2647        }
2648    }
2649
2650    @Override
2651    public int checkUidSignatures(int uid1, int uid2) {
2652        // Map to base uids.
2653        uid1 = UserHandle.getAppId(uid1);
2654        uid2 = UserHandle.getAppId(uid2);
2655        // reader
2656        synchronized (mPackages) {
2657            Signature[] s1;
2658            Signature[] s2;
2659            Object obj = mSettings.getUserIdLPr(uid1);
2660            if (obj != null) {
2661                if (obj instanceof SharedUserSetting) {
2662                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2663                } else if (obj instanceof PackageSetting) {
2664                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2665                } else {
2666                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2667                }
2668            } else {
2669                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2670            }
2671            obj = mSettings.getUserIdLPr(uid2);
2672            if (obj != null) {
2673                if (obj instanceof SharedUserSetting) {
2674                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2675                } else if (obj instanceof PackageSetting) {
2676                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2677                } else {
2678                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2679                }
2680            } else {
2681                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2682            }
2683            return compareSignatures(s1, s2);
2684        }
2685    }
2686
2687    /**
2688     * Compares two sets of signatures. Returns:
2689     * <br />
2690     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2691     * <br />
2692     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2693     * <br />
2694     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2695     * <br />
2696     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2697     * <br />
2698     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2699     */
2700    static int compareSignatures(Signature[] s1, Signature[] s2) {
2701        if (s1 == null) {
2702            return s2 == null
2703                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2704                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2705        }
2706
2707        if (s2 == null) {
2708            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2709        }
2710
2711        if (s1.length != s2.length) {
2712            return PackageManager.SIGNATURE_NO_MATCH;
2713        }
2714
2715        // Since both signature sets are of size 1, we can compare without HashSets.
2716        if (s1.length == 1) {
2717            return s1[0].equals(s2[0]) ?
2718                    PackageManager.SIGNATURE_MATCH :
2719                    PackageManager.SIGNATURE_NO_MATCH;
2720        }
2721
2722        HashSet<Signature> set1 = new HashSet<Signature>();
2723        for (Signature sig : s1) {
2724            set1.add(sig);
2725        }
2726        HashSet<Signature> set2 = new HashSet<Signature>();
2727        for (Signature sig : s2) {
2728            set2.add(sig);
2729        }
2730        // Make sure s2 contains all signatures in s1.
2731        if (set1.equals(set2)) {
2732            return PackageManager.SIGNATURE_MATCH;
2733        }
2734        return PackageManager.SIGNATURE_NO_MATCH;
2735    }
2736
2737    /**
2738     * If the database version for this type of package (internal storage or
2739     * external storage) is less than the version where package signatures
2740     * were updated, return true.
2741     */
2742    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2743        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2744                DatabaseVersion.SIGNATURE_END_ENTITY))
2745                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2746                        DatabaseVersion.SIGNATURE_END_ENTITY));
2747    }
2748
2749    /**
2750     * Used for backward compatibility to make sure any packages with
2751     * certificate chains get upgraded to the new style. {@code existingSigs}
2752     * will be in the old format (since they were stored on disk from before the
2753     * system upgrade) and {@code scannedSigs} will be in the newer format.
2754     */
2755    private int compareSignaturesCompat(PackageSignatures existingSigs,
2756            PackageParser.Package scannedPkg) {
2757        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2758            return PackageManager.SIGNATURE_NO_MATCH;
2759        }
2760
2761        HashSet<Signature> existingSet = new HashSet<Signature>();
2762        for (Signature sig : existingSigs.mSignatures) {
2763            existingSet.add(sig);
2764        }
2765        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2766        for (Signature sig : scannedPkg.mSignatures) {
2767            try {
2768                Signature[] chainSignatures = sig.getChainSignatures();
2769                for (Signature chainSig : chainSignatures) {
2770                    scannedCompatSet.add(chainSig);
2771                }
2772            } catch (CertificateEncodingException e) {
2773                scannedCompatSet.add(sig);
2774            }
2775        }
2776        /*
2777         * Make sure the expanded scanned set contains all signatures in the
2778         * existing one.
2779         */
2780        if (scannedCompatSet.equals(existingSet)) {
2781            // Migrate the old signatures to the new scheme.
2782            existingSigs.assignSignatures(scannedPkg.mSignatures);
2783            // The new KeySets will be re-added later in the scanning process.
2784            synchronized (mPackages) {
2785                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2786            }
2787            return PackageManager.SIGNATURE_MATCH;
2788        }
2789        return PackageManager.SIGNATURE_NO_MATCH;
2790    }
2791
2792    @Override
2793    public String[] getPackagesForUid(int uid) {
2794        uid = UserHandle.getAppId(uid);
2795        // reader
2796        synchronized (mPackages) {
2797            Object obj = mSettings.getUserIdLPr(uid);
2798            if (obj instanceof SharedUserSetting) {
2799                final SharedUserSetting sus = (SharedUserSetting) obj;
2800                final int N = sus.packages.size();
2801                final String[] res = new String[N];
2802                final Iterator<PackageSetting> it = sus.packages.iterator();
2803                int i = 0;
2804                while (it.hasNext()) {
2805                    res[i++] = it.next().name;
2806                }
2807                return res;
2808            } else if (obj instanceof PackageSetting) {
2809                final PackageSetting ps = (PackageSetting) obj;
2810                return new String[] { ps.name };
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public String getNameForUid(int uid) {
2818        // reader
2819        synchronized (mPackages) {
2820            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2821            if (obj instanceof SharedUserSetting) {
2822                final SharedUserSetting sus = (SharedUserSetting) obj;
2823                return sus.name + ":" + sus.userId;
2824            } else if (obj instanceof PackageSetting) {
2825                final PackageSetting ps = (PackageSetting) obj;
2826                return ps.name;
2827            }
2828        }
2829        return null;
2830    }
2831
2832    @Override
2833    public int getUidForSharedUser(String sharedUserName) {
2834        if(sharedUserName == null) {
2835            return -1;
2836        }
2837        // reader
2838        synchronized (mPackages) {
2839            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2840            if (suid == null) {
2841                return -1;
2842            }
2843            return suid.userId;
2844        }
2845    }
2846
2847    @Override
2848    public int getFlagsForUid(int uid) {
2849        synchronized (mPackages) {
2850            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2851            if (obj instanceof SharedUserSetting) {
2852                final SharedUserSetting sus = (SharedUserSetting) obj;
2853                return sus.pkgFlags;
2854            } else if (obj instanceof PackageSetting) {
2855                final PackageSetting ps = (PackageSetting) obj;
2856                return ps.pkgFlags;
2857            }
2858        }
2859        return 0;
2860    }
2861
2862    @Override
2863    public String[] getAppOpPermissionPackages(String permissionName) {
2864        synchronized (mPackages) {
2865            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2866            if (pkgs == null) {
2867                return null;
2868            }
2869            return pkgs.toArray(new String[pkgs.size()]);
2870        }
2871    }
2872
2873    @Override
2874    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2875            int flags, int userId) {
2876        if (!sUserManager.exists(userId)) return null;
2877        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2878        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2879        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2880    }
2881
2882    @Override
2883    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2884            IntentFilter filter, int match, ComponentName activity) {
2885        final int userId = UserHandle.getCallingUserId();
2886        if (DEBUG_PREFERRED) {
2887            Log.v(TAG, "setLastChosenActivity intent=" + intent
2888                + " resolvedType=" + resolvedType
2889                + " flags=" + flags
2890                + " filter=" + filter
2891                + " match=" + match
2892                + " activity=" + activity);
2893            filter.dump(new PrintStreamPrinter(System.out), "    ");
2894        }
2895        intent.setComponent(null);
2896        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2897        // Find any earlier preferred or last chosen entries and nuke them
2898        findPreferredActivity(intent, resolvedType,
2899                flags, query, 0, false, true, false, userId);
2900        // Add the new activity as the last chosen for this filter
2901        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2902                "Setting last chosen");
2903    }
2904
2905    @Override
2906    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2907        final int userId = UserHandle.getCallingUserId();
2908        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2909        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2910        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2911                false, false, false, userId);
2912    }
2913
2914    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2915            int flags, List<ResolveInfo> query, int userId) {
2916        if (query != null) {
2917            final int N = query.size();
2918            if (N == 1) {
2919                return query.get(0);
2920            } else if (N > 1) {
2921                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2922                // If there is more than one activity with the same priority,
2923                // then let the user decide between them.
2924                ResolveInfo r0 = query.get(0);
2925                ResolveInfo r1 = query.get(1);
2926                if (DEBUG_INTENT_MATCHING || debug) {
2927                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2928                            + r1.activityInfo.name + "=" + r1.priority);
2929                }
2930                // If the first activity has a higher priority, or a different
2931                // default, then it is always desireable to pick it.
2932                if (r0.priority != r1.priority
2933                        || r0.preferredOrder != r1.preferredOrder
2934                        || r0.isDefault != r1.isDefault) {
2935                    return query.get(0);
2936                }
2937                // If we have saved a preference for a preferred activity for
2938                // this Intent, use that.
2939                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2940                        flags, query, r0.priority, true, false, debug, userId);
2941                if (ri != null) {
2942                    return ri;
2943                }
2944                if (userId != 0) {
2945                    ri = new ResolveInfo(mResolveInfo);
2946                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2947                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2948                            ri.activityInfo.applicationInfo);
2949                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2950                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2951                    return ri;
2952                }
2953                return mResolveInfo;
2954            }
2955        }
2956        return null;
2957    }
2958
2959    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2960            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2961        final int N = query.size();
2962        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2963                .get(userId);
2964        // Get the list of persistent preferred activities that handle the intent
2965        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2966        List<PersistentPreferredActivity> pprefs = ppir != null
2967                ? ppir.queryIntent(intent, resolvedType,
2968                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2969                : null;
2970        if (pprefs != null && pprefs.size() > 0) {
2971            final int M = pprefs.size();
2972            for (int i=0; i<M; i++) {
2973                final PersistentPreferredActivity ppa = pprefs.get(i);
2974                if (DEBUG_PREFERRED || debug) {
2975                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2976                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2977                            + "\n  component=" + ppa.mComponent);
2978                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2979                }
2980                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2981                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2982                if (DEBUG_PREFERRED || debug) {
2983                    Slog.v(TAG, "Found persistent preferred activity:");
2984                    if (ai != null) {
2985                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2986                    } else {
2987                        Slog.v(TAG, "  null");
2988                    }
2989                }
2990                if (ai == null) {
2991                    // This previously registered persistent preferred activity
2992                    // component is no longer known. Ignore it and do NOT remove it.
2993                    continue;
2994                }
2995                for (int j=0; j<N; j++) {
2996                    final ResolveInfo ri = query.get(j);
2997                    if (!ri.activityInfo.applicationInfo.packageName
2998                            .equals(ai.applicationInfo.packageName)) {
2999                        continue;
3000                    }
3001                    if (!ri.activityInfo.name.equals(ai.name)) {
3002                        continue;
3003                    }
3004                    //  Found a persistent preference that can handle the intent.
3005                    if (DEBUG_PREFERRED || debug) {
3006                        Slog.v(TAG, "Returning persistent preferred activity: " +
3007                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3008                    }
3009                    return ri;
3010                }
3011            }
3012        }
3013        return null;
3014    }
3015
3016    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3017            List<ResolveInfo> query, int priority, boolean always,
3018            boolean removeMatches, boolean debug, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        // writer
3021        synchronized (mPackages) {
3022            if (intent.getSelector() != null) {
3023                intent = intent.getSelector();
3024            }
3025            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3026
3027            // Try to find a matching persistent preferred activity.
3028            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3029                    debug, userId);
3030
3031            // If a persistent preferred activity matched, use it.
3032            if (pri != null) {
3033                return pri;
3034            }
3035
3036            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3037            // Get the list of preferred activities that handle the intent
3038            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3039            List<PreferredActivity> prefs = pir != null
3040                    ? pir.queryIntent(intent, resolvedType,
3041                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3042                    : null;
3043            if (prefs != null && prefs.size() > 0) {
3044                boolean changed = false;
3045                try {
3046                    // First figure out how good the original match set is.
3047                    // We will only allow preferred activities that came
3048                    // from the same match quality.
3049                    int match = 0;
3050
3051                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3052
3053                    final int N = query.size();
3054                    for (int j=0; j<N; j++) {
3055                        final ResolveInfo ri = query.get(j);
3056                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3057                                + ": 0x" + Integer.toHexString(match));
3058                        if (ri.match > match) {
3059                            match = ri.match;
3060                        }
3061                    }
3062
3063                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3064                            + Integer.toHexString(match));
3065
3066                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3067                    final int M = prefs.size();
3068                    for (int i=0; i<M; i++) {
3069                        final PreferredActivity pa = prefs.get(i);
3070                        if (DEBUG_PREFERRED || debug) {
3071                            Slog.v(TAG, "Checking PreferredActivity ds="
3072                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3073                                    + "\n  component=" + pa.mPref.mComponent);
3074                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3075                        }
3076                        if (pa.mPref.mMatch != match) {
3077                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3078                                    + Integer.toHexString(pa.mPref.mMatch));
3079                            continue;
3080                        }
3081                        // If it's not an "always" type preferred activity and that's what we're
3082                        // looking for, skip it.
3083                        if (always && !pa.mPref.mAlways) {
3084                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3085                            continue;
3086                        }
3087                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3088                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3089                        if (DEBUG_PREFERRED || debug) {
3090                            Slog.v(TAG, "Found preferred activity:");
3091                            if (ai != null) {
3092                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3093                            } else {
3094                                Slog.v(TAG, "  null");
3095                            }
3096                        }
3097                        if (ai == null) {
3098                            // This previously registered preferred activity
3099                            // component is no longer known.  Most likely an update
3100                            // to the app was installed and in the new version this
3101                            // component no longer exists.  Clean it up by removing
3102                            // it from the preferred activities list, and skip it.
3103                            Slog.w(TAG, "Removing dangling preferred activity: "
3104                                    + pa.mPref.mComponent);
3105                            pir.removeFilter(pa);
3106                            changed = true;
3107                            continue;
3108                        }
3109                        for (int j=0; j<N; j++) {
3110                            final ResolveInfo ri = query.get(j);
3111                            if (!ri.activityInfo.applicationInfo.packageName
3112                                    .equals(ai.applicationInfo.packageName)) {
3113                                continue;
3114                            }
3115                            if (!ri.activityInfo.name.equals(ai.name)) {
3116                                continue;
3117                            }
3118
3119                            if (removeMatches) {
3120                                pir.removeFilter(pa);
3121                                changed = true;
3122                                if (DEBUG_PREFERRED) {
3123                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3124                                }
3125                                break;
3126                            }
3127
3128                            // Okay we found a previously set preferred or last chosen app.
3129                            // If the result set is different from when this
3130                            // was created, we need to clear it and re-ask the
3131                            // user their preference, if we're looking for an "always" type entry.
3132                            if (always && !pa.mPref.sameSet(query, priority)) {
3133                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3134                                        + intent + " type " + resolvedType);
3135                                if (DEBUG_PREFERRED) {
3136                                    Slog.v(TAG, "Removing preferred activity since set changed "
3137                                            + pa.mPref.mComponent);
3138                                }
3139                                pir.removeFilter(pa);
3140                                // Re-add the filter as a "last chosen" entry (!always)
3141                                PreferredActivity lastChosen = new PreferredActivity(
3142                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3143                                pir.addFilter(lastChosen);
3144                                changed = true;
3145                                return null;
3146                            }
3147
3148                            // Yay! Either the set matched or we're looking for the last chosen
3149                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3150                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3151                            return ri;
3152                        }
3153                    }
3154                } finally {
3155                    if (changed) {
3156                        if (DEBUG_PREFERRED) {
3157                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3158                        }
3159                        mSettings.writePackageRestrictionsLPr(userId);
3160                    }
3161                }
3162            }
3163        }
3164        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3165        return null;
3166    }
3167
3168    /*
3169     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3170     */
3171    @Override
3172    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3173            int targetUserId) {
3174        mContext.enforceCallingOrSelfPermission(
3175                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3176        List<CrossProfileIntentFilter> matches =
3177                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3178        if (matches != null) {
3179            int size = matches.size();
3180            for (int i = 0; i < size; i++) {
3181                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3182            }
3183        }
3184        ArrayList<String> packageNames = null;
3185        SparseArray<ArrayList<String>> fromSource =
3186                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3187        if (fromSource != null) {
3188            packageNames = fromSource.get(targetUserId);
3189            if (packageNames != null) {
3190                // We need the package name, so we try to resolve with the loosest flags possible
3191                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3192                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3193                int count = resolveInfos.size();
3194                for (int i = 0; i < count; i++) {
3195                    ResolveInfo resolveInfo = resolveInfos.get(i);
3196                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3197                        return true;
3198                    }
3199                }
3200            }
3201        }
3202        return false;
3203    }
3204
3205    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3206            String resolvedType, int userId) {
3207        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3208        if (resolver != null) {
3209            return resolver.queryIntent(intent, resolvedType, false, userId);
3210        }
3211        return null;
3212    }
3213
3214    @Override
3215    public List<ResolveInfo> queryIntentActivities(Intent intent,
3216            String resolvedType, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return Collections.emptyList();
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3219        ComponentName comp = intent.getComponent();
3220        if (comp == null) {
3221            if (intent.getSelector() != null) {
3222                intent = intent.getSelector();
3223                comp = intent.getComponent();
3224            }
3225        }
3226
3227        if (comp != null) {
3228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3230            if (ai != null) {
3231                final ResolveInfo ri = new ResolveInfo();
3232                ri.activityInfo = ai;
3233                list.add(ri);
3234            }
3235            return list;
3236        }
3237
3238        // reader
3239        synchronized (mPackages) {
3240            final String pkgName = intent.getPackage();
3241            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3242            if (pkgName == null) {
3243                ResolveInfo resolveInfo = null;
3244                if (queryCrossProfile) {
3245                    // Check if the intent needs to be forwarded to another user for this package
3246                    ArrayList<ResolveInfo> crossProfileResult =
3247                            queryIntentActivitiesCrossProfilePackage(
3248                                    intent, resolvedType, flags, userId);
3249                    if (!crossProfileResult.isEmpty()) {
3250                        // Skip the current profile
3251                        return crossProfileResult;
3252                    }
3253                    List<CrossProfileIntentFilter> matchingFilters =
3254                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3255                    // Check for results that need to skip the current profile.
3256                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3257                            resolvedType, flags, userId);
3258                    if (resolveInfo != null) {
3259                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3260                        result.add(resolveInfo);
3261                        return result;
3262                    }
3263                    // Check for cross profile results.
3264                    resolveInfo = queryCrossProfileIntents(
3265                            matchingFilters, intent, resolvedType, flags, userId);
3266                }
3267                // Check for results in the current profile.
3268                List<ResolveInfo> result = mActivities.queryIntent(
3269                        intent, resolvedType, flags, userId);
3270                if (resolveInfo != null) {
3271                    result.add(resolveInfo);
3272                    Collections.sort(result, mResolvePrioritySorter);
3273                }
3274                return result;
3275            }
3276            final PackageParser.Package pkg = mPackages.get(pkgName);
3277            if (pkg != null) {
3278                if (queryCrossProfile) {
3279                    ArrayList<ResolveInfo> crossProfileResult =
3280                            queryIntentActivitiesCrossProfilePackage(
3281                                    intent, resolvedType, flags, userId, pkg, pkgName);
3282                    if (!crossProfileResult.isEmpty()) {
3283                        // Skip the current profile
3284                        return crossProfileResult;
3285                    }
3286                }
3287                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3288                        pkg.activities, userId);
3289            }
3290            return new ArrayList<ResolveInfo>();
3291        }
3292    }
3293
3294    private ResolveInfo querySkipCurrentProfileIntents(
3295            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3296            int flags, int sourceUserId) {
3297        if (matchingFilters != null) {
3298            int size = matchingFilters.size();
3299            for (int i = 0; i < size; i ++) {
3300                CrossProfileIntentFilter filter = matchingFilters.get(i);
3301                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3302                    // Checking if there are activities in the target user that can handle the
3303                    // intent.
3304                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3305                            flags, sourceUserId);
3306                    if (resolveInfo != null) {
3307                        return resolveInfo;
3308                    }
3309                }
3310            }
3311        }
3312        return null;
3313    }
3314
3315    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3316            Intent intent, String resolvedType, int flags, int userId) {
3317        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3318        SparseArray<ArrayList<String>> sourceForwardingInfo =
3319                mSettings.mCrossProfilePackageInfo.get(userId);
3320        if (sourceForwardingInfo != null) {
3321            int NI = sourceForwardingInfo.size();
3322            for (int i = 0; i < NI; i++) {
3323                int targetUserId = sourceForwardingInfo.keyAt(i);
3324                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3325                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3326                        intent, resolvedType, flags, targetUserId);
3327                int NJ = resolveInfos.size();
3328                for (int j = 0; j < NJ; j++) {
3329                    ResolveInfo resolveInfo = resolveInfos.get(j);
3330                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3331                        matchingResolveInfos.add(createForwardingResolveInfo(
3332                                resolveInfo.filter, userId, targetUserId));
3333                    }
3334                }
3335            }
3336        }
3337        return matchingResolveInfos;
3338    }
3339
3340    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3341            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3342            String packageName) {
3343        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3344        SparseArray<ArrayList<String>> sourceForwardingInfo =
3345                mSettings.mCrossProfilePackageInfo.get(userId);
3346        if (sourceForwardingInfo != null) {
3347            int NI = sourceForwardingInfo.size();
3348            for (int i = 0; i < NI; i++) {
3349                int targetUserId = sourceForwardingInfo.keyAt(i);
3350                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3351                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3352                            intent, resolvedType, flags, pkg.activities, targetUserId);
3353                    int NJ = resolveInfos.size();
3354                    for (int j = 0; j < NJ; j++) {
3355                        ResolveInfo resolveInfo = resolveInfos.get(j);
3356                        matchingResolveInfos.add(createForwardingResolveInfo(
3357                                resolveInfo.filter, userId, targetUserId));
3358                    }
3359                }
3360            }
3361        }
3362        return matchingResolveInfos;
3363    }
3364
3365    // Return matching ResolveInfo if any for skip current profile intent filters.
3366    private ResolveInfo queryCrossProfileIntents(
3367            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3368            int flags, int sourceUserId) {
3369        if (matchingFilters != null) {
3370            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3371            // match the same intent. For performance reasons, it is better not to
3372            // run queryIntent twice for the same userId
3373            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3374            int size = matchingFilters.size();
3375            for (int i = 0; i < size; i++) {
3376                CrossProfileIntentFilter filter = matchingFilters.get(i);
3377                int targetUserId = filter.getTargetUserId();
3378                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3379                        && !alreadyTriedUserIds.get(targetUserId)) {
3380                    // Checking if there are activities in the target user that can handle the
3381                    // intent.
3382                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3383                            flags, sourceUserId);
3384                    if (resolveInfo != null) return resolveInfo;
3385                    alreadyTriedUserIds.put(targetUserId, true);
3386                }
3387            }
3388        }
3389        return null;
3390    }
3391
3392    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3393            String resolvedType, int flags, int sourceUserId) {
3394        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3395                resolvedType, flags, filter.getTargetUserId());
3396        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3397            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3398        }
3399        return null;
3400    }
3401
3402    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3403            int sourceUserId, int targetUserId) {
3404        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3405        String className;
3406        if (targetUserId == UserHandle.USER_OWNER) {
3407            className = FORWARD_INTENT_TO_USER_OWNER;
3408        } else {
3409            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3410        }
3411        ComponentName forwardingActivityComponentName = new ComponentName(
3412                mAndroidApplication.packageName, className);
3413        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3414                sourceUserId);
3415        if (targetUserId == UserHandle.USER_OWNER) {
3416            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3417            forwardingResolveInfo.noResourceId = true;
3418        }
3419        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3420        forwardingResolveInfo.priority = 0;
3421        forwardingResolveInfo.preferredOrder = 0;
3422        forwardingResolveInfo.match = 0;
3423        forwardingResolveInfo.isDefault = true;
3424        forwardingResolveInfo.filter = filter;
3425        forwardingResolveInfo.targetUserId = targetUserId;
3426        return forwardingResolveInfo;
3427    }
3428
3429    @Override
3430    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3431            Intent[] specifics, String[] specificTypes, Intent intent,
3432            String resolvedType, int flags, int userId) {
3433        if (!sUserManager.exists(userId)) return Collections.emptyList();
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3435                "query intent activity options");
3436        final String resultsAction = intent.getAction();
3437
3438        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3439                | PackageManager.GET_RESOLVED_FILTER, userId);
3440
3441        if (DEBUG_INTENT_MATCHING) {
3442            Log.v(TAG, "Query " + intent + ": " + results);
3443        }
3444
3445        int specificsPos = 0;
3446        int N;
3447
3448        // todo: note that the algorithm used here is O(N^2).  This
3449        // isn't a problem in our current environment, but if we start running
3450        // into situations where we have more than 5 or 10 matches then this
3451        // should probably be changed to something smarter...
3452
3453        // First we go through and resolve each of the specific items
3454        // that were supplied, taking care of removing any corresponding
3455        // duplicate items in the generic resolve list.
3456        if (specifics != null) {
3457            for (int i=0; i<specifics.length; i++) {
3458                final Intent sintent = specifics[i];
3459                if (sintent == null) {
3460                    continue;
3461                }
3462
3463                if (DEBUG_INTENT_MATCHING) {
3464                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3465                }
3466
3467                String action = sintent.getAction();
3468                if (resultsAction != null && resultsAction.equals(action)) {
3469                    // If this action was explicitly requested, then don't
3470                    // remove things that have it.
3471                    action = null;
3472                }
3473
3474                ResolveInfo ri = null;
3475                ActivityInfo ai = null;
3476
3477                ComponentName comp = sintent.getComponent();
3478                if (comp == null) {
3479                    ri = resolveIntent(
3480                        sintent,
3481                        specificTypes != null ? specificTypes[i] : null,
3482                            flags, userId);
3483                    if (ri == null) {
3484                        continue;
3485                    }
3486                    if (ri == mResolveInfo) {
3487                        // ACK!  Must do something better with this.
3488                    }
3489                    ai = ri.activityInfo;
3490                    comp = new ComponentName(ai.applicationInfo.packageName,
3491                            ai.name);
3492                } else {
3493                    ai = getActivityInfo(comp, flags, userId);
3494                    if (ai == null) {
3495                        continue;
3496                    }
3497                }
3498
3499                // Look for any generic query activities that are duplicates
3500                // of this specific one, and remove them from the results.
3501                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3502                N = results.size();
3503                int j;
3504                for (j=specificsPos; j<N; j++) {
3505                    ResolveInfo sri = results.get(j);
3506                    if ((sri.activityInfo.name.equals(comp.getClassName())
3507                            && sri.activityInfo.applicationInfo.packageName.equals(
3508                                    comp.getPackageName()))
3509                        || (action != null && sri.filter.matchAction(action))) {
3510                        results.remove(j);
3511                        if (DEBUG_INTENT_MATCHING) Log.v(
3512                            TAG, "Removing duplicate item from " + j
3513                            + " due to specific " + specificsPos);
3514                        if (ri == null) {
3515                            ri = sri;
3516                        }
3517                        j--;
3518                        N--;
3519                    }
3520                }
3521
3522                // Add this specific item to its proper place.
3523                if (ri == null) {
3524                    ri = new ResolveInfo();
3525                    ri.activityInfo = ai;
3526                }
3527                results.add(specificsPos, ri);
3528                ri.specificIndex = i;
3529                specificsPos++;
3530            }
3531        }
3532
3533        // Now we go through the remaining generic results and remove any
3534        // duplicate actions that are found here.
3535        N = results.size();
3536        for (int i=specificsPos; i<N-1; i++) {
3537            final ResolveInfo rii = results.get(i);
3538            if (rii.filter == null) {
3539                continue;
3540            }
3541
3542            // Iterate over all of the actions of this result's intent
3543            // filter...  typically this should be just one.
3544            final Iterator<String> it = rii.filter.actionsIterator();
3545            if (it == null) {
3546                continue;
3547            }
3548            while (it.hasNext()) {
3549                final String action = it.next();
3550                if (resultsAction != null && resultsAction.equals(action)) {
3551                    // If this action was explicitly requested, then don't
3552                    // remove things that have it.
3553                    continue;
3554                }
3555                for (int j=i+1; j<N; j++) {
3556                    final ResolveInfo rij = results.get(j);
3557                    if (rij.filter != null && rij.filter.hasAction(action)) {
3558                        results.remove(j);
3559                        if (DEBUG_INTENT_MATCHING) Log.v(
3560                            TAG, "Removing duplicate item from " + j
3561                            + " due to action " + action + " at " + i);
3562                        j--;
3563                        N--;
3564                    }
3565                }
3566            }
3567
3568            // If the caller didn't request filter information, drop it now
3569            // so we don't have to marshall/unmarshall it.
3570            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3571                rii.filter = null;
3572            }
3573        }
3574
3575        // Filter out the caller activity if so requested.
3576        if (caller != null) {
3577            N = results.size();
3578            for (int i=0; i<N; i++) {
3579                ActivityInfo ainfo = results.get(i).activityInfo;
3580                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3581                        && caller.getClassName().equals(ainfo.name)) {
3582                    results.remove(i);
3583                    break;
3584                }
3585            }
3586        }
3587
3588        // If the caller didn't request filter information,
3589        // drop them now so we don't have to
3590        // marshall/unmarshall it.
3591        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3592            N = results.size();
3593            for (int i=0; i<N; i++) {
3594                results.get(i).filter = null;
3595            }
3596        }
3597
3598        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3599        return results;
3600    }
3601
3602    @Override
3603    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3604            int userId) {
3605        if (!sUserManager.exists(userId)) return Collections.emptyList();
3606        ComponentName comp = intent.getComponent();
3607        if (comp == null) {
3608            if (intent.getSelector() != null) {
3609                intent = intent.getSelector();
3610                comp = intent.getComponent();
3611            }
3612        }
3613        if (comp != null) {
3614            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3615            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3616            if (ai != null) {
3617                ResolveInfo ri = new ResolveInfo();
3618                ri.activityInfo = ai;
3619                list.add(ri);
3620            }
3621            return list;
3622        }
3623
3624        // reader
3625        synchronized (mPackages) {
3626            String pkgName = intent.getPackage();
3627            if (pkgName == null) {
3628                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3629            }
3630            final PackageParser.Package pkg = mPackages.get(pkgName);
3631            if (pkg != null) {
3632                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3633                        userId);
3634            }
3635            return null;
3636        }
3637    }
3638
3639    @Override
3640    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3641        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3642        if (!sUserManager.exists(userId)) return null;
3643        if (query != null) {
3644            if (query.size() >= 1) {
3645                // If there is more than one service with the same priority,
3646                // just arbitrarily pick the first one.
3647                return query.get(0);
3648            }
3649        }
3650        return null;
3651    }
3652
3653    @Override
3654    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3655            int userId) {
3656        if (!sUserManager.exists(userId)) return Collections.emptyList();
3657        ComponentName comp = intent.getComponent();
3658        if (comp == null) {
3659            if (intent.getSelector() != null) {
3660                intent = intent.getSelector();
3661                comp = intent.getComponent();
3662            }
3663        }
3664        if (comp != null) {
3665            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3666            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3667            if (si != null) {
3668                final ResolveInfo ri = new ResolveInfo();
3669                ri.serviceInfo = si;
3670                list.add(ri);
3671            }
3672            return list;
3673        }
3674
3675        // reader
3676        synchronized (mPackages) {
3677            String pkgName = intent.getPackage();
3678            if (pkgName == null) {
3679                return mServices.queryIntent(intent, resolvedType, flags, userId);
3680            }
3681            final PackageParser.Package pkg = mPackages.get(pkgName);
3682            if (pkg != null) {
3683                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3684                        userId);
3685            }
3686            return null;
3687        }
3688    }
3689
3690    @Override
3691    public List<ResolveInfo> queryIntentContentProviders(
3692            Intent intent, String resolvedType, int flags, int userId) {
3693        if (!sUserManager.exists(userId)) return Collections.emptyList();
3694        ComponentName comp = intent.getComponent();
3695        if (comp == null) {
3696            if (intent.getSelector() != null) {
3697                intent = intent.getSelector();
3698                comp = intent.getComponent();
3699            }
3700        }
3701        if (comp != null) {
3702            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3703            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3704            if (pi != null) {
3705                final ResolveInfo ri = new ResolveInfo();
3706                ri.providerInfo = pi;
3707                list.add(ri);
3708            }
3709            return list;
3710        }
3711
3712        // reader
3713        synchronized (mPackages) {
3714            String pkgName = intent.getPackage();
3715            if (pkgName == null) {
3716                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3717            }
3718            final PackageParser.Package pkg = mPackages.get(pkgName);
3719            if (pkg != null) {
3720                return mProviders.queryIntentForPackage(
3721                        intent, resolvedType, flags, pkg.providers, userId);
3722            }
3723            return null;
3724        }
3725    }
3726
3727    @Override
3728    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3729        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3730
3731        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3732
3733        // writer
3734        synchronized (mPackages) {
3735            ArrayList<PackageInfo> list;
3736            if (listUninstalled) {
3737                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3738                for (PackageSetting ps : mSettings.mPackages.values()) {
3739                    PackageInfo pi;
3740                    if (ps.pkg != null) {
3741                        pi = generatePackageInfo(ps.pkg, flags, userId);
3742                    } else {
3743                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3744                    }
3745                    if (pi != null) {
3746                        list.add(pi);
3747                    }
3748                }
3749            } else {
3750                list = new ArrayList<PackageInfo>(mPackages.size());
3751                for (PackageParser.Package p : mPackages.values()) {
3752                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3753                    if (pi != null) {
3754                        list.add(pi);
3755                    }
3756                }
3757            }
3758
3759            return new ParceledListSlice<PackageInfo>(list);
3760        }
3761    }
3762
3763    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3764            String[] permissions, boolean[] tmp, int flags, int userId) {
3765        int numMatch = 0;
3766        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3767        for (int i=0; i<permissions.length; i++) {
3768            if (gp.grantedPermissions.contains(permissions[i])) {
3769                tmp[i] = true;
3770                numMatch++;
3771            } else {
3772                tmp[i] = false;
3773            }
3774        }
3775        if (numMatch == 0) {
3776            return;
3777        }
3778        PackageInfo pi;
3779        if (ps.pkg != null) {
3780            pi = generatePackageInfo(ps.pkg, flags, userId);
3781        } else {
3782            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3783        }
3784        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3785            if (numMatch == permissions.length) {
3786                pi.requestedPermissions = permissions;
3787            } else {
3788                pi.requestedPermissions = new String[numMatch];
3789                numMatch = 0;
3790                for (int i=0; i<permissions.length; i++) {
3791                    if (tmp[i]) {
3792                        pi.requestedPermissions[numMatch] = permissions[i];
3793                        numMatch++;
3794                    }
3795                }
3796            }
3797        }
3798        list.add(pi);
3799    }
3800
3801    @Override
3802    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3803            String[] permissions, int flags, int userId) {
3804        if (!sUserManager.exists(userId)) return null;
3805        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3806
3807        // writer
3808        synchronized (mPackages) {
3809            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3810            boolean[] tmpBools = new boolean[permissions.length];
3811            if (listUninstalled) {
3812                for (PackageSetting ps : mSettings.mPackages.values()) {
3813                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3814                }
3815            } else {
3816                for (PackageParser.Package pkg : mPackages.values()) {
3817                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3818                    if (ps != null) {
3819                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3820                                userId);
3821                    }
3822                }
3823            }
3824
3825            return new ParceledListSlice<PackageInfo>(list);
3826        }
3827    }
3828
3829    @Override
3830    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3831        if (!sUserManager.exists(userId)) return null;
3832        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3833
3834        // writer
3835        synchronized (mPackages) {
3836            ArrayList<ApplicationInfo> list;
3837            if (listUninstalled) {
3838                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3839                for (PackageSetting ps : mSettings.mPackages.values()) {
3840                    ApplicationInfo ai;
3841                    if (ps.pkg != null) {
3842                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3843                                ps.readUserState(userId), userId);
3844                    } else {
3845                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3846                    }
3847                    if (ai != null) {
3848                        list.add(ai);
3849                    }
3850                }
3851            } else {
3852                list = new ArrayList<ApplicationInfo>(mPackages.size());
3853                for (PackageParser.Package p : mPackages.values()) {
3854                    if (p.mExtras != null) {
3855                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3856                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3857                        if (ai != null) {
3858                            list.add(ai);
3859                        }
3860                    }
3861                }
3862            }
3863
3864            return new ParceledListSlice<ApplicationInfo>(list);
3865        }
3866    }
3867
3868    public List<ApplicationInfo> getPersistentApplications(int flags) {
3869        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3870
3871        // reader
3872        synchronized (mPackages) {
3873            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3874            final int userId = UserHandle.getCallingUserId();
3875            while (i.hasNext()) {
3876                final PackageParser.Package p = i.next();
3877                if (p.applicationInfo != null
3878                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3879                        && (!mSafeMode || isSystemApp(p))) {
3880                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3881                    if (ps != null) {
3882                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3883                                ps.readUserState(userId), userId);
3884                        if (ai != null) {
3885                            finalList.add(ai);
3886                        }
3887                    }
3888                }
3889            }
3890        }
3891
3892        return finalList;
3893    }
3894
3895    @Override
3896    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3897        if (!sUserManager.exists(userId)) return null;
3898        // reader
3899        synchronized (mPackages) {
3900            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3901            PackageSetting ps = provider != null
3902                    ? mSettings.mPackages.get(provider.owner.packageName)
3903                    : null;
3904            return ps != null
3905                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3906                    && (!mSafeMode || (provider.info.applicationInfo.flags
3907                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3908                    ? PackageParser.generateProviderInfo(provider, flags,
3909                            ps.readUserState(userId), userId)
3910                    : null;
3911        }
3912    }
3913
3914    /**
3915     * @deprecated
3916     */
3917    @Deprecated
3918    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3919        // reader
3920        synchronized (mPackages) {
3921            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3922                    .entrySet().iterator();
3923            final int userId = UserHandle.getCallingUserId();
3924            while (i.hasNext()) {
3925                Map.Entry<String, PackageParser.Provider> entry = i.next();
3926                PackageParser.Provider p = entry.getValue();
3927                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3928
3929                if (ps != null && p.syncable
3930                        && (!mSafeMode || (p.info.applicationInfo.flags
3931                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3932                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3933                            ps.readUserState(userId), userId);
3934                    if (info != null) {
3935                        outNames.add(entry.getKey());
3936                        outInfo.add(info);
3937                    }
3938                }
3939            }
3940        }
3941    }
3942
3943    @Override
3944    public List<ProviderInfo> queryContentProviders(String processName,
3945            int uid, int flags) {
3946        ArrayList<ProviderInfo> finalList = null;
3947        // reader
3948        synchronized (mPackages) {
3949            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3950            final int userId = processName != null ?
3951                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3952            while (i.hasNext()) {
3953                final PackageParser.Provider p = i.next();
3954                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3955                if (ps != null && p.info.authority != null
3956                        && (processName == null
3957                                || (p.info.processName.equals(processName)
3958                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3959                        && mSettings.isEnabledLPr(p.info, flags, userId)
3960                        && (!mSafeMode
3961                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3962                    if (finalList == null) {
3963                        finalList = new ArrayList<ProviderInfo>(3);
3964                    }
3965                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3966                            ps.readUserState(userId), userId);
3967                    if (info != null) {
3968                        finalList.add(info);
3969                    }
3970                }
3971            }
3972        }
3973
3974        if (finalList != null) {
3975            Collections.sort(finalList, mProviderInitOrderSorter);
3976        }
3977
3978        return finalList;
3979    }
3980
3981    @Override
3982    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3983            int flags) {
3984        // reader
3985        synchronized (mPackages) {
3986            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3987            return PackageParser.generateInstrumentationInfo(i, flags);
3988        }
3989    }
3990
3991    @Override
3992    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3993            int flags) {
3994        ArrayList<InstrumentationInfo> finalList =
3995            new ArrayList<InstrumentationInfo>();
3996
3997        // reader
3998        synchronized (mPackages) {
3999            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4000            while (i.hasNext()) {
4001                final PackageParser.Instrumentation p = i.next();
4002                if (targetPackage == null
4003                        || targetPackage.equals(p.info.targetPackage)) {
4004                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4005                            flags);
4006                    if (ii != null) {
4007                        finalList.add(ii);
4008                    }
4009                }
4010            }
4011        }
4012
4013        return finalList;
4014    }
4015
4016    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4017        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4018        if (overlays == null) {
4019            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4020            return;
4021        }
4022        for (PackageParser.Package opkg : overlays.values()) {
4023            // Not much to do if idmap fails: we already logged the error
4024            // and we certainly don't want to abort installation of pkg simply
4025            // because an overlay didn't fit properly. For these reasons,
4026            // ignore the return value of createIdmapForPackagePairLI.
4027            createIdmapForPackagePairLI(pkg, opkg);
4028        }
4029    }
4030
4031    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4032            PackageParser.Package opkg) {
4033        if (!opkg.mTrustedOverlay) {
4034            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4035                    opkg.baseCodePath + ": overlay not trusted");
4036            return false;
4037        }
4038        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4039        if (overlaySet == null) {
4040            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4041                    opkg.baseCodePath + " but target package has no known overlays");
4042            return false;
4043        }
4044        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4045        // TODO: generate idmap for split APKs
4046        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4047            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4048                    + opkg.baseCodePath);
4049            return false;
4050        }
4051        PackageParser.Package[] overlayArray =
4052            overlaySet.values().toArray(new PackageParser.Package[0]);
4053        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4054            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4055                return p1.mOverlayPriority - p2.mOverlayPriority;
4056            }
4057        };
4058        Arrays.sort(overlayArray, cmp);
4059
4060        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4061        int i = 0;
4062        for (PackageParser.Package p : overlayArray) {
4063            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4064        }
4065        return true;
4066    }
4067
4068    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4069        final File[] files = dir.listFiles();
4070        if (ArrayUtils.isEmpty(files)) {
4071            Log.d(TAG, "No files in app dir " + dir);
4072            return;
4073        }
4074
4075        if (DEBUG_PACKAGE_SCANNING) {
4076            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4077                    + " flags=0x" + Integer.toHexString(parseFlags));
4078        }
4079
4080        for (File file : files) {
4081            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4082                    && !PackageInstallerService.isStageName(file.getName());
4083            if (!isPackage) {
4084                // Ignore entries which are not packages
4085                continue;
4086            }
4087            try {
4088                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4089                        scanFlags, currentTime, null);
4090            } catch (PackageManagerException e) {
4091                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4092
4093                // Delete invalid userdata apps
4094                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4095                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4096                    Slog.w(TAG, "Deleting invalid package at " + file);
4097                    if (file.isDirectory()) {
4098                        FileUtils.deleteContents(file);
4099                    }
4100                    file.delete();
4101                }
4102            }
4103        }
4104    }
4105
4106    private static File getSettingsProblemFile() {
4107        File dataDir = Environment.getDataDirectory();
4108        File systemDir = new File(dataDir, "system");
4109        File fname = new File(systemDir, "uiderrors.txt");
4110        return fname;
4111    }
4112
4113    static void reportSettingsProblem(int priority, String msg) {
4114        try {
4115            File fname = getSettingsProblemFile();
4116            FileOutputStream out = new FileOutputStream(fname, true);
4117            PrintWriter pw = new FastPrintWriter(out);
4118            SimpleDateFormat formatter = new SimpleDateFormat();
4119            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4120            pw.println(dateString + ": " + msg);
4121            pw.close();
4122            FileUtils.setPermissions(
4123                    fname.toString(),
4124                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4125                    -1, -1);
4126        } catch (java.io.IOException e) {
4127        }
4128        Slog.println(priority, TAG, msg);
4129    }
4130
4131    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4132            PackageParser.Package pkg, File srcFile, int parseFlags)
4133            throws PackageManagerException {
4134        if (ps != null
4135                && ps.codePath.equals(srcFile)
4136                && ps.timeStamp == srcFile.lastModified()
4137                && !isCompatSignatureUpdateNeeded(pkg)) {
4138            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4139            if (ps.signatures.mSignatures != null
4140                    && ps.signatures.mSignatures.length != 0
4141                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4142                // Optimization: reuse the existing cached certificates
4143                // if the package appears to be unchanged.
4144                pkg.mSignatures = ps.signatures.mSignatures;
4145                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4146                synchronized (mPackages) {
4147                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4148                }
4149                return;
4150            }
4151
4152            Slog.w(TAG, "PackageSetting for " + ps.name
4153                    + " is missing signatures.  Collecting certs again to recover them.");
4154        } else {
4155            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4156        }
4157
4158        try {
4159            pp.collectCertificates(pkg, parseFlags);
4160            pp.collectManifestDigest(pkg);
4161        } catch (PackageParserException e) {
4162            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4163                    + pkg.packageName + ": " + e.getMessage());
4164        }
4165    }
4166
4167    /*
4168     *  Scan a package and return the newly parsed package.
4169     *  Returns null in case of errors and the error code is stored in mLastScanError
4170     */
4171    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4172            long currentTime, UserHandle user) throws PackageManagerException {
4173        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4174        parseFlags |= mDefParseFlags;
4175        PackageParser pp = new PackageParser();
4176        pp.setSeparateProcesses(mSeparateProcesses);
4177        pp.setOnlyCoreApps(mOnlyCore);
4178        pp.setDisplayMetrics(mMetrics);
4179
4180        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4181            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4182        }
4183
4184        final PackageParser.Package pkg;
4185        try {
4186            pkg = pp.parsePackage(scanFile, parseFlags);
4187        } catch (PackageParserException e) {
4188            throw new PackageManagerException(e.error,
4189                    "Failed to scan " + scanFile + ": " + e.getMessage());
4190        }
4191
4192        PackageSetting ps = null;
4193        PackageSetting updatedPkg;
4194        // reader
4195        synchronized (mPackages) {
4196            // Look to see if we already know about this package.
4197            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4198            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4199                // This package has been renamed to its original name.  Let's
4200                // use that.
4201                ps = mSettings.peekPackageLPr(oldName);
4202            }
4203            // If there was no original package, see one for the real package name.
4204            if (ps == null) {
4205                ps = mSettings.peekPackageLPr(pkg.packageName);
4206            }
4207            // Check to see if this package could be hiding/updating a system
4208            // package.  Must look for it either under the original or real
4209            // package name depending on our state.
4210            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4211            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4212        }
4213        boolean updatedPkgBetter = false;
4214        // First check if this is a system package that may involve an update
4215        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4216            if (ps != null && !ps.codePath.equals(scanFile)) {
4217                // The path has changed from what was last scanned...  check the
4218                // version of the new path against what we have stored to determine
4219                // what to do.
4220                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4221                if (pkg.mVersionCode < ps.versionCode) {
4222                    // The system package has been updated and the code path does not match
4223                    // Ignore entry. Skip it.
4224                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4225                            + " ignored: updated version " + ps.versionCode
4226                            + " better than this " + pkg.mVersionCode);
4227                    if (!updatedPkg.codePath.equals(scanFile)) {
4228                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4229                                + ps.name + " changing from " + updatedPkg.codePathString
4230                                + " to " + scanFile);
4231                        updatedPkg.codePath = scanFile;
4232                        updatedPkg.codePathString = scanFile.toString();
4233                        // This is the point at which we know that the system-disk APK
4234                        // for this package has moved during a reboot (e.g. due to an OTA),
4235                        // so we need to reevaluate it for privilege policy.
4236                        if (locationIsPrivileged(scanFile)) {
4237                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4238                        }
4239                    }
4240                    updatedPkg.pkg = pkg;
4241                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4242                } else {
4243                    // The current app on the system partition is better than
4244                    // what we have updated to on the data partition; switch
4245                    // back to the system partition version.
4246                    // At this point, its safely assumed that package installation for
4247                    // apps in system partition will go through. If not there won't be a working
4248                    // version of the app
4249                    // writer
4250                    synchronized (mPackages) {
4251                        // Just remove the loaded entries from package lists.
4252                        mPackages.remove(ps.name);
4253                    }
4254                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4255                            + "reverting from " + ps.codePathString
4256                            + ": new version " + pkg.mVersionCode
4257                            + " better than installed " + ps.versionCode);
4258
4259                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4260                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4261                            getAppDexInstructionSets(ps));
4262                    synchronized (mInstallLock) {
4263                        args.cleanUpResourcesLI();
4264                    }
4265                    synchronized (mPackages) {
4266                        mSettings.enableSystemPackageLPw(ps.name);
4267                    }
4268                    updatedPkgBetter = true;
4269                }
4270            }
4271        }
4272
4273        if (updatedPkg != null) {
4274            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4275            // initially
4276            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4277
4278            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4279            // flag set initially
4280            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4281                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4282            }
4283        }
4284
4285        // Verify certificates against what was last scanned
4286        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4287
4288        /*
4289         * A new system app appeared, but we already had a non-system one of the
4290         * same name installed earlier.
4291         */
4292        boolean shouldHideSystemApp = false;
4293        if (updatedPkg == null && ps != null
4294                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4295            /*
4296             * Check to make sure the signatures match first. If they don't,
4297             * wipe the installed application and its data.
4298             */
4299            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4300                    != PackageManager.SIGNATURE_MATCH) {
4301                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4302                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4303                ps = null;
4304            } else {
4305                /*
4306                 * If the newly-added system app is an older version than the
4307                 * already installed version, hide it. It will be scanned later
4308                 * and re-added like an update.
4309                 */
4310                if (pkg.mVersionCode < ps.versionCode) {
4311                    shouldHideSystemApp = true;
4312                } else {
4313                    /*
4314                     * The newly found system app is a newer version that the
4315                     * one previously installed. Simply remove the
4316                     * already-installed application and replace it with our own
4317                     * while keeping the application data.
4318                     */
4319                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4320                            + ps.codePathString + ": new version " + pkg.mVersionCode
4321                            + " better than installed " + ps.versionCode);
4322                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4323                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4324                            getAppDexInstructionSets(ps));
4325                    synchronized (mInstallLock) {
4326                        args.cleanUpResourcesLI();
4327                    }
4328                }
4329            }
4330        }
4331
4332        // The apk is forward locked (not public) if its code and resources
4333        // are kept in different files. (except for app in either system or
4334        // vendor path).
4335        // TODO grab this value from PackageSettings
4336        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4337            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4338                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4339            }
4340        }
4341
4342        // TODO: extend to support forward-locked splits
4343        String resourcePath = null;
4344        String baseResourcePath = null;
4345        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4346            if (ps != null && ps.resourcePathString != null) {
4347                resourcePath = ps.resourcePathString;
4348                baseResourcePath = ps.resourcePathString;
4349            } else {
4350                // Should not happen at all. Just log an error.
4351                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4352            }
4353        } else {
4354            resourcePath = pkg.codePath;
4355            baseResourcePath = pkg.baseCodePath;
4356        }
4357
4358        // Set application objects path explicitly.
4359        pkg.applicationInfo.setCodePath(pkg.codePath);
4360        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4361        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4362        pkg.applicationInfo.setResourcePath(resourcePath);
4363        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4364        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4365
4366        // Note that we invoke the following method only if we are about to unpack an application
4367        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4368                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4369
4370        /*
4371         * If the system app should be overridden by a previously installed
4372         * data, hide the system app now and let the /data/app scan pick it up
4373         * again.
4374         */
4375        if (shouldHideSystemApp) {
4376            synchronized (mPackages) {
4377                /*
4378                 * We have to grant systems permissions before we hide, because
4379                 * grantPermissions will assume the package update is trying to
4380                 * expand its permissions.
4381                 */
4382                grantPermissionsLPw(pkg, true);
4383                mSettings.disableSystemPackageLPw(pkg.packageName);
4384            }
4385        }
4386
4387        return scannedPkg;
4388    }
4389
4390    private static String fixProcessName(String defProcessName,
4391            String processName, int uid) {
4392        if (processName == null) {
4393            return defProcessName;
4394        }
4395        return processName;
4396    }
4397
4398    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4399            throws PackageManagerException {
4400        if (pkgSetting.signatures.mSignatures != null) {
4401            // Already existing package. Make sure signatures match
4402            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4403                    == PackageManager.SIGNATURE_MATCH;
4404            if (!match) {
4405                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4406                        == PackageManager.SIGNATURE_MATCH;
4407            }
4408            if (!match) {
4409                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4410                        + pkg.packageName + " signatures do not match the "
4411                        + "previously installed version; ignoring!");
4412            }
4413        }
4414
4415        // Check for shared user signatures
4416        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4417            // Already existing package. Make sure signatures match
4418            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4419                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4420            if (!match) {
4421                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4422                        == PackageManager.SIGNATURE_MATCH;
4423            }
4424            if (!match) {
4425                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4426                        "Package " + pkg.packageName
4427                        + " has no signatures that match those in shared user "
4428                        + pkgSetting.sharedUser.name + "; ignoring!");
4429            }
4430        }
4431    }
4432
4433    /**
4434     * Enforces that only the system UID or root's UID can call a method exposed
4435     * via Binder.
4436     *
4437     * @param message used as message if SecurityException is thrown
4438     * @throws SecurityException if the caller is not system or root
4439     */
4440    private static final void enforceSystemOrRoot(String message) {
4441        final int uid = Binder.getCallingUid();
4442        if (uid != Process.SYSTEM_UID && uid != 0) {
4443            throw new SecurityException(message);
4444        }
4445    }
4446
4447    @Override
4448    public void performBootDexOpt() {
4449        enforceSystemOrRoot("Only the system can request dexopt be performed");
4450
4451        final HashSet<PackageParser.Package> pkgs;
4452        synchronized (mPackages) {
4453            pkgs = mDeferredDexOpt;
4454            mDeferredDexOpt = null;
4455        }
4456
4457        if (pkgs != null) {
4458            // Filter out packages that aren't recently used.
4459            //
4460            // The exception is first boot of a non-eng device, which
4461            // should do a full dexopt.
4462            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4463            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4464                // TODO: add a property to control this?
4465                long dexOptLRUThresholdInMinutes;
4466                if (eng) {
4467                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4468                } else {
4469                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4470                }
4471                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4472
4473                int total = pkgs.size();
4474                int skipped = 0;
4475                long now = System.currentTimeMillis();
4476                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4477                    PackageParser.Package pkg = i.next();
4478                    long then = pkg.mLastPackageUsageTimeInMills;
4479                    if (then + dexOptLRUThresholdInMills < now) {
4480                        if (DEBUG_DEXOPT) {
4481                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4482                                  ((then == 0) ? "never" : new Date(then)));
4483                        }
4484                        i.remove();
4485                        skipped++;
4486                    }
4487                }
4488                if (DEBUG_DEXOPT) {
4489                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4490                }
4491            }
4492
4493            int i = 0;
4494            for (PackageParser.Package pkg : pkgs) {
4495                i++;
4496                if (DEBUG_DEXOPT) {
4497                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4498                          + ": " + pkg.packageName);
4499                }
4500                if (!isFirstBoot()) {
4501                    try {
4502                        ActivityManagerNative.getDefault().showBootMessage(
4503                                mContext.getResources().getString(
4504                                        R.string.android_upgrading_apk,
4505                                        i, pkgs.size()), true);
4506                    } catch (RemoteException e) {
4507                    }
4508                }
4509                PackageParser.Package p = pkg;
4510                synchronized (mInstallLock) {
4511                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4512                            true /* include dependencies */);
4513                }
4514            }
4515        }
4516    }
4517
4518    @Override
4519    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4520        return performDexOpt(packageName, instructionSet, true);
4521    }
4522
4523    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4524        if (info.primaryCpuAbi == null) {
4525            return getPreferredInstructionSet();
4526        }
4527
4528        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4529    }
4530
4531    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4532        PackageParser.Package p;
4533        final String targetInstructionSet;
4534        synchronized (mPackages) {
4535            p = mPackages.get(packageName);
4536            if (p == null) {
4537                return false;
4538            }
4539            if (updateUsage) {
4540                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4541            }
4542            mPackageUsage.write(false);
4543
4544            targetInstructionSet = instructionSet != null ? instructionSet :
4545                    getPrimaryInstructionSet(p.applicationInfo);
4546            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4547                return false;
4548            }
4549        }
4550
4551        synchronized (mInstallLock) {
4552            final String[] instructionSets = new String[] { targetInstructionSet };
4553            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4554                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4555        }
4556    }
4557
4558    public HashSet<String> getPackagesThatNeedDexOpt() {
4559        HashSet<String> pkgs = null;
4560        synchronized (mPackages) {
4561            for (PackageParser.Package p : mPackages.values()) {
4562                if (DEBUG_DEXOPT) {
4563                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4564                }
4565                if (!p.mDexOptPerformed.isEmpty()) {
4566                    continue;
4567                }
4568                if (pkgs == null) {
4569                    pkgs = new HashSet<String>();
4570                }
4571                pkgs.add(p.packageName);
4572            }
4573        }
4574        return pkgs;
4575    }
4576
4577    public void shutdown() {
4578        mPackageUsage.write(true);
4579    }
4580
4581    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4582             boolean forceDex, boolean defer, HashSet<String> done) {
4583        for (int i=0; i<libs.size(); i++) {
4584            PackageParser.Package libPkg;
4585            String libName;
4586            synchronized (mPackages) {
4587                libName = libs.get(i);
4588                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4589                if (lib != null && lib.apk != null) {
4590                    libPkg = mPackages.get(lib.apk);
4591                } else {
4592                    libPkg = null;
4593                }
4594            }
4595            if (libPkg != null && !done.contains(libName)) {
4596                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4597            }
4598        }
4599    }
4600
4601    static final int DEX_OPT_SKIPPED = 0;
4602    static final int DEX_OPT_PERFORMED = 1;
4603    static final int DEX_OPT_DEFERRED = 2;
4604    static final int DEX_OPT_FAILED = -1;
4605
4606    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4607            boolean forceDex, boolean defer, HashSet<String> done) {
4608        final String[] instructionSets = targetInstructionSets != null ?
4609                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4610
4611        if (done != null) {
4612            done.add(pkg.packageName);
4613            if (pkg.usesLibraries != null) {
4614                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4615            }
4616            if (pkg.usesOptionalLibraries != null) {
4617                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4618            }
4619        }
4620
4621        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4622            return DEX_OPT_SKIPPED;
4623        }
4624
4625        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4626
4627        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4628        boolean performedDexOpt = false;
4629        // There are three basic cases here:
4630        // 1.) we need to dexopt, either because we are forced or it is needed
4631        // 2.) we are defering a needed dexopt
4632        // 3.) we are skipping an unneeded dexopt
4633        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4634        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4635            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4636                continue;
4637            }
4638
4639            for (String path : paths) {
4640                try {
4641                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4642                    // patckage or the one we find does not match the image checksum (i.e. it was
4643                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4644                    // odex file and it matches the checksum of the image but not its base address,
4645                    // meaning we need to move it.
4646                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4647                            pkg.packageName, dexCodeInstructionSet, defer);
4648                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4649                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4650                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4651                                + " vmSafeMode=" + vmSafeMode);
4652                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4653                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4654                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4655
4656                        if (ret < 0) {
4657                            // Don't bother running dexopt again if we failed, it will probably
4658                            // just result in an error again. Also, don't bother dexopting for other
4659                            // paths & ISAs.
4660                            return DEX_OPT_FAILED;
4661                        }
4662
4663                        performedDexOpt = true;
4664                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4665                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4666                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4667                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4668                                pkg.packageName, dexCodeInstructionSet);
4669
4670                        if (ret < 0) {
4671                            // Don't bother running patchoat again if we failed, it will probably
4672                            // just result in an error again. Also, don't bother dexopting for other
4673                            // paths & ISAs.
4674                            return DEX_OPT_FAILED;
4675                        }
4676
4677                        performedDexOpt = true;
4678                    }
4679
4680                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4681                    // paths and instruction sets. We'll deal with them all together when we process
4682                    // our list of deferred dexopts.
4683                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4684                        if (mDeferredDexOpt == null) {
4685                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4686                        }
4687                        mDeferredDexOpt.add(pkg);
4688                        return DEX_OPT_DEFERRED;
4689                    }
4690                } catch (FileNotFoundException e) {
4691                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4692                    return DEX_OPT_FAILED;
4693                } catch (IOException e) {
4694                    Slog.w(TAG, "IOException reading apk: " + path, e);
4695                    return DEX_OPT_FAILED;
4696                } catch (StaleDexCacheError e) {
4697                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4698                    return DEX_OPT_FAILED;
4699                } catch (Exception e) {
4700                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4701                    return DEX_OPT_FAILED;
4702                }
4703            }
4704
4705            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4706            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4707            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4708            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4709            // it.
4710            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4711        }
4712
4713        // If we've gotten here, we're sure that no error occurred and that we haven't
4714        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4715        // we've skipped all of them because they are up to date. In both cases this
4716        // package doesn't need dexopt any longer.
4717        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4718    }
4719
4720    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4721        if (info.primaryCpuAbi != null) {
4722            if (info.secondaryCpuAbi != null) {
4723                return new String[] {
4724                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4725                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4726            } else {
4727                return new String[] {
4728                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4729            }
4730        }
4731
4732        return new String[] { getPreferredInstructionSet() };
4733    }
4734
4735    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4736        if (ps.primaryCpuAbiString != null) {
4737            if (ps.secondaryCpuAbiString != null) {
4738                return new String[] {
4739                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4740                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4741            } else {
4742                return new String[] {
4743                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4744            }
4745        }
4746
4747        return new String[] { getPreferredInstructionSet() };
4748    }
4749
4750    private static String getPreferredInstructionSet() {
4751        if (sPreferredInstructionSet == null) {
4752            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4753        }
4754
4755        return sPreferredInstructionSet;
4756    }
4757
4758    private static List<String> getAllInstructionSets() {
4759        final String[] allAbis = Build.SUPPORTED_ABIS;
4760        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4761
4762        for (String abi : allAbis) {
4763            final String instructionSet = VMRuntime.getInstructionSet(abi);
4764            if (!allInstructionSets.contains(instructionSet)) {
4765                allInstructionSets.add(instructionSet);
4766            }
4767        }
4768
4769        return allInstructionSets;
4770    }
4771
4772    /**
4773     * Returns the instruction set that should be used to compile dex code. In the presence of
4774     * a native bridge this might be different than the one shared libraries use.
4775     */
4776    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4777        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4778        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4779    }
4780
4781    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4782        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4783        for (String instructionSet : instructionSets) {
4784            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4785        }
4786        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4787    }
4788
4789    @Override
4790    public void forceDexOpt(String packageName) {
4791        enforceSystemOrRoot("forceDexOpt");
4792
4793        PackageParser.Package pkg;
4794        synchronized (mPackages) {
4795            pkg = mPackages.get(packageName);
4796            if (pkg == null) {
4797                throw new IllegalArgumentException("Missing package: " + packageName);
4798            }
4799        }
4800
4801        synchronized (mInstallLock) {
4802            final String[] instructionSets = new String[] {
4803                    getPrimaryInstructionSet(pkg.applicationInfo) };
4804            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4805            if (res != DEX_OPT_PERFORMED) {
4806                throw new IllegalStateException("Failed to dexopt: " + res);
4807            }
4808        }
4809    }
4810
4811    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4812                                boolean forceDex, boolean defer, boolean inclDependencies) {
4813        HashSet<String> done;
4814        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4815            done = new HashSet<String>();
4816            done.add(pkg.packageName);
4817        } else {
4818            done = null;
4819        }
4820        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4821    }
4822
4823    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4824        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4825            Slog.w(TAG, "Unable to update from " + oldPkg.name
4826                    + " to " + newPkg.packageName
4827                    + ": old package not in system partition");
4828            return false;
4829        } else if (mPackages.get(oldPkg.name) != null) {
4830            Slog.w(TAG, "Unable to update from " + oldPkg.name
4831                    + " to " + newPkg.packageName
4832                    + ": old package still exists");
4833            return false;
4834        }
4835        return true;
4836    }
4837
4838    File getDataPathForUser(int userId) {
4839        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4840    }
4841
4842    private File getDataPathForPackage(String packageName, int userId) {
4843        /*
4844         * Until we fully support multiple users, return the directory we
4845         * previously would have. The PackageManagerTests will need to be
4846         * revised when this is changed back..
4847         */
4848        if (userId == 0) {
4849            return new File(mAppDataDir, packageName);
4850        } else {
4851            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4852                + File.separator + packageName);
4853        }
4854    }
4855
4856    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4857        int[] users = sUserManager.getUserIds();
4858        int res = mInstaller.install(packageName, uid, uid, seinfo);
4859        if (res < 0) {
4860            return res;
4861        }
4862        for (int user : users) {
4863            if (user != 0) {
4864                res = mInstaller.createUserData(packageName,
4865                        UserHandle.getUid(user, uid), user, seinfo);
4866                if (res < 0) {
4867                    return res;
4868                }
4869            }
4870        }
4871        return res;
4872    }
4873
4874    private int removeDataDirsLI(String packageName) {
4875        int[] users = sUserManager.getUserIds();
4876        int res = 0;
4877        for (int user : users) {
4878            int resInner = mInstaller.remove(packageName, user);
4879            if (resInner < 0) {
4880                res = resInner;
4881            }
4882        }
4883
4884        return res;
4885    }
4886
4887    private int deleteCodeCacheDirsLI(String packageName) {
4888        int[] users = sUserManager.getUserIds();
4889        int res = 0;
4890        for (int user : users) {
4891            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4892            if (resInner < 0) {
4893                res = resInner;
4894            }
4895        }
4896        return res;
4897    }
4898
4899    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4900            PackageParser.Package changingLib) {
4901        if (file.path != null) {
4902            usesLibraryFiles.add(file.path);
4903            return;
4904        }
4905        PackageParser.Package p = mPackages.get(file.apk);
4906        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4907            // If we are doing this while in the middle of updating a library apk,
4908            // then we need to make sure to use that new apk for determining the
4909            // dependencies here.  (We haven't yet finished committing the new apk
4910            // to the package manager state.)
4911            if (p == null || p.packageName.equals(changingLib.packageName)) {
4912                p = changingLib;
4913            }
4914        }
4915        if (p != null) {
4916            usesLibraryFiles.addAll(p.getAllCodePaths());
4917        }
4918    }
4919
4920    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4921            PackageParser.Package changingLib) throws PackageManagerException {
4922        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4923            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4924            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4925            for (int i=0; i<N; i++) {
4926                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4927                if (file == null) {
4928                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4929                            "Package " + pkg.packageName + " requires unavailable shared library "
4930                            + pkg.usesLibraries.get(i) + "; failing!");
4931                }
4932                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4933            }
4934            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4935            for (int i=0; i<N; i++) {
4936                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4937                if (file == null) {
4938                    Slog.w(TAG, "Package " + pkg.packageName
4939                            + " desires unavailable shared library "
4940                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4941                } else {
4942                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4943                }
4944            }
4945            N = usesLibraryFiles.size();
4946            if (N > 0) {
4947                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4948            } else {
4949                pkg.usesLibraryFiles = null;
4950            }
4951        }
4952    }
4953
4954    private static boolean hasString(List<String> list, List<String> which) {
4955        if (list == null) {
4956            return false;
4957        }
4958        for (int i=list.size()-1; i>=0; i--) {
4959            for (int j=which.size()-1; j>=0; j--) {
4960                if (which.get(j).equals(list.get(i))) {
4961                    return true;
4962                }
4963            }
4964        }
4965        return false;
4966    }
4967
4968    private void updateAllSharedLibrariesLPw() {
4969        for (PackageParser.Package pkg : mPackages.values()) {
4970            try {
4971                updateSharedLibrariesLPw(pkg, null);
4972            } catch (PackageManagerException e) {
4973                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4974            }
4975        }
4976    }
4977
4978    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4979            PackageParser.Package changingPkg) {
4980        ArrayList<PackageParser.Package> res = null;
4981        for (PackageParser.Package pkg : mPackages.values()) {
4982            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4983                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4984                if (res == null) {
4985                    res = new ArrayList<PackageParser.Package>();
4986                }
4987                res.add(pkg);
4988                try {
4989                    updateSharedLibrariesLPw(pkg, changingPkg);
4990                } catch (PackageManagerException e) {
4991                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4992                }
4993            }
4994        }
4995        return res;
4996    }
4997
4998    /**
4999     * Derive the value of the {@code cpuAbiOverride} based on the provided
5000     * value and an optional stored value from the package settings.
5001     */
5002    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5003        String cpuAbiOverride = null;
5004
5005        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5006            cpuAbiOverride = null;
5007        } else if (abiOverride != null) {
5008            cpuAbiOverride = abiOverride;
5009        } else if (settings != null) {
5010            cpuAbiOverride = settings.cpuAbiOverrideString;
5011        }
5012
5013        return cpuAbiOverride;
5014    }
5015
5016    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5017            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5018        final File scanFile = new File(pkg.codePath);
5019        if (pkg.applicationInfo.getCodePath() == null ||
5020                pkg.applicationInfo.getResourcePath() == null) {
5021            // Bail out. The resource and code paths haven't been set.
5022            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5023                    "Code and resource paths haven't been set correctly");
5024        }
5025
5026        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5027            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5028        }
5029
5030        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5031            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5032        }
5033
5034        if (mCustomResolverComponentName != null &&
5035                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5036            setUpCustomResolverActivity(pkg);
5037        }
5038
5039        if (pkg.packageName.equals("android")) {
5040            synchronized (mPackages) {
5041                if (mAndroidApplication != null) {
5042                    Slog.w(TAG, "*************************************************");
5043                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5044                    Slog.w(TAG, " file=" + scanFile);
5045                    Slog.w(TAG, "*************************************************");
5046                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5047                            "Core android package being redefined.  Skipping.");
5048                }
5049
5050                // Set up information for our fall-back user intent resolution activity.
5051                mPlatformPackage = pkg;
5052                pkg.mVersionCode = mSdkVersion;
5053                mAndroidApplication = pkg.applicationInfo;
5054
5055                if (!mResolverReplaced) {
5056                    mResolveActivity.applicationInfo = mAndroidApplication;
5057                    mResolveActivity.name = ResolverActivity.class.getName();
5058                    mResolveActivity.packageName = mAndroidApplication.packageName;
5059                    mResolveActivity.processName = "system:ui";
5060                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5061                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5062                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5063                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5064                    mResolveActivity.exported = true;
5065                    mResolveActivity.enabled = true;
5066                    mResolveInfo.activityInfo = mResolveActivity;
5067                    mResolveInfo.priority = 0;
5068                    mResolveInfo.preferredOrder = 0;
5069                    mResolveInfo.match = 0;
5070                    mResolveComponentName = new ComponentName(
5071                            mAndroidApplication.packageName, mResolveActivity.name);
5072                }
5073            }
5074        }
5075
5076        if (DEBUG_PACKAGE_SCANNING) {
5077            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5078                Log.d(TAG, "Scanning package " + pkg.packageName);
5079        }
5080
5081        if (mPackages.containsKey(pkg.packageName)
5082                || mSharedLibraries.containsKey(pkg.packageName)) {
5083            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5084                    "Application package " + pkg.packageName
5085                    + " already installed.  Skipping duplicate.");
5086        }
5087
5088        // Initialize package source and resource directories
5089        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5090        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5091
5092        SharedUserSetting suid = null;
5093        PackageSetting pkgSetting = null;
5094
5095        if (!isSystemApp(pkg)) {
5096            // Only system apps can use these features.
5097            pkg.mOriginalPackages = null;
5098            pkg.mRealPackage = null;
5099            pkg.mAdoptPermissions = null;
5100        }
5101
5102        // writer
5103        synchronized (mPackages) {
5104            if (pkg.mSharedUserId != null) {
5105                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5106                if (suid == null) {
5107                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5108                            "Creating application package " + pkg.packageName
5109                            + " for shared user failed");
5110                }
5111                if (DEBUG_PACKAGE_SCANNING) {
5112                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5113                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5114                                + "): packages=" + suid.packages);
5115                }
5116            }
5117
5118            // Check if we are renaming from an original package name.
5119            PackageSetting origPackage = null;
5120            String realName = null;
5121            if (pkg.mOriginalPackages != null) {
5122                // This package may need to be renamed to a previously
5123                // installed name.  Let's check on that...
5124                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5125                if (pkg.mOriginalPackages.contains(renamed)) {
5126                    // This package had originally been installed as the
5127                    // original name, and we have already taken care of
5128                    // transitioning to the new one.  Just update the new
5129                    // one to continue using the old name.
5130                    realName = pkg.mRealPackage;
5131                    if (!pkg.packageName.equals(renamed)) {
5132                        // Callers into this function may have already taken
5133                        // care of renaming the package; only do it here if
5134                        // it is not already done.
5135                        pkg.setPackageName(renamed);
5136                    }
5137
5138                } else {
5139                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5140                        if ((origPackage = mSettings.peekPackageLPr(
5141                                pkg.mOriginalPackages.get(i))) != null) {
5142                            // We do have the package already installed under its
5143                            // original name...  should we use it?
5144                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5145                                // New package is not compatible with original.
5146                                origPackage = null;
5147                                continue;
5148                            } else if (origPackage.sharedUser != null) {
5149                                // Make sure uid is compatible between packages.
5150                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5151                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5152                                            + " to " + pkg.packageName + ": old uid "
5153                                            + origPackage.sharedUser.name
5154                                            + " differs from " + pkg.mSharedUserId);
5155                                    origPackage = null;
5156                                    continue;
5157                                }
5158                            } else {
5159                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5160                                        + pkg.packageName + " to old name " + origPackage.name);
5161                            }
5162                            break;
5163                        }
5164                    }
5165                }
5166            }
5167
5168            if (mTransferedPackages.contains(pkg.packageName)) {
5169                Slog.w(TAG, "Package " + pkg.packageName
5170                        + " was transferred to another, but its .apk remains");
5171            }
5172
5173            // Just create the setting, don't add it yet. For already existing packages
5174            // the PkgSetting exists already and doesn't have to be created.
5175            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5176                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5177                    pkg.applicationInfo.primaryCpuAbi,
5178                    pkg.applicationInfo.secondaryCpuAbi,
5179                    pkg.applicationInfo.flags, user, false);
5180            if (pkgSetting == null) {
5181                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5182                        "Creating application package " + pkg.packageName + " failed");
5183            }
5184
5185            if (pkgSetting.origPackage != null) {
5186                // If we are first transitioning from an original package,
5187                // fix up the new package's name now.  We need to do this after
5188                // looking up the package under its new name, so getPackageLP
5189                // can take care of fiddling things correctly.
5190                pkg.setPackageName(origPackage.name);
5191
5192                // File a report about this.
5193                String msg = "New package " + pkgSetting.realName
5194                        + " renamed to replace old package " + pkgSetting.name;
5195                reportSettingsProblem(Log.WARN, msg);
5196
5197                // Make a note of it.
5198                mTransferedPackages.add(origPackage.name);
5199
5200                // No longer need to retain this.
5201                pkgSetting.origPackage = null;
5202            }
5203
5204            if (realName != null) {
5205                // Make a note of it.
5206                mTransferedPackages.add(pkg.packageName);
5207            }
5208
5209            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5210                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5211            }
5212
5213            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5214                // Check all shared libraries and map to their actual file path.
5215                // We only do this here for apps not on a system dir, because those
5216                // are the only ones that can fail an install due to this.  We
5217                // will take care of the system apps by updating all of their
5218                // library paths after the scan is done.
5219                updateSharedLibrariesLPw(pkg, null);
5220            }
5221
5222            if (mFoundPolicyFile) {
5223                SELinuxMMAC.assignSeinfoValue(pkg);
5224            }
5225
5226            pkg.applicationInfo.uid = pkgSetting.appId;
5227            pkg.mExtras = pkgSetting;
5228            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5229                try {
5230                    verifySignaturesLP(pkgSetting, pkg);
5231                } catch (PackageManagerException e) {
5232                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5233                        throw e;
5234                    }
5235                    // The signature has changed, but this package is in the system
5236                    // image...  let's recover!
5237                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5238                    // However...  if this package is part of a shared user, but it
5239                    // doesn't match the signature of the shared user, let's fail.
5240                    // What this means is that you can't change the signatures
5241                    // associated with an overall shared user, which doesn't seem all
5242                    // that unreasonable.
5243                    if (pkgSetting.sharedUser != null) {
5244                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5245                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5246                            throw new PackageManagerException(
5247                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5248                                            "Signature mismatch for shared user : "
5249                                            + pkgSetting.sharedUser);
5250                        }
5251                    }
5252                    // File a report about this.
5253                    String msg = "System package " + pkg.packageName
5254                        + " signature changed; retaining data.";
5255                    reportSettingsProblem(Log.WARN, msg);
5256                }
5257            } else {
5258                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5259                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5260                            + pkg.packageName + " upgrade keys do not match the "
5261                            + "previously installed version");
5262                } else {
5263                    // signatures may have changed as result of upgrade
5264                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5265                }
5266            }
5267            // Verify that this new package doesn't have any content providers
5268            // that conflict with existing packages.  Only do this if the
5269            // package isn't already installed, since we don't want to break
5270            // things that are installed.
5271            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5272                final int N = pkg.providers.size();
5273                int i;
5274                for (i=0; i<N; i++) {
5275                    PackageParser.Provider p = pkg.providers.get(i);
5276                    if (p.info.authority != null) {
5277                        String names[] = p.info.authority.split(";");
5278                        for (int j = 0; j < names.length; j++) {
5279                            if (mProvidersByAuthority.containsKey(names[j])) {
5280                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5281                                final String otherPackageName =
5282                                        ((other != null && other.getComponentName() != null) ?
5283                                                other.getComponentName().getPackageName() : "?");
5284                                throw new PackageManagerException(
5285                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5286                                                "Can't install because provider name " + names[j]
5287                                                + " (in package " + pkg.applicationInfo.packageName
5288                                                + ") is already used by " + otherPackageName);
5289                            }
5290                        }
5291                    }
5292                }
5293            }
5294
5295            if (pkg.mAdoptPermissions != null) {
5296                // This package wants to adopt ownership of permissions from
5297                // another package.
5298                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5299                    final String origName = pkg.mAdoptPermissions.get(i);
5300                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5301                    if (orig != null) {
5302                        if (verifyPackageUpdateLPr(orig, pkg)) {
5303                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5304                                    + pkg.packageName);
5305                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5306                        }
5307                    }
5308                }
5309            }
5310        }
5311
5312        final String pkgName = pkg.packageName;
5313
5314        final long scanFileTime = scanFile.lastModified();
5315        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5316        pkg.applicationInfo.processName = fixProcessName(
5317                pkg.applicationInfo.packageName,
5318                pkg.applicationInfo.processName,
5319                pkg.applicationInfo.uid);
5320
5321        File dataPath;
5322        if (mPlatformPackage == pkg) {
5323            // The system package is special.
5324            dataPath = new File (Environment.getDataDirectory(), "system");
5325            pkg.applicationInfo.dataDir = dataPath.getPath();
5326
5327        } else {
5328            // This is a normal package, need to make its data directory.
5329            dataPath = getDataPathForPackage(pkg.packageName, 0);
5330
5331            boolean uidError = false;
5332
5333            if (dataPath.exists()) {
5334                int currentUid = 0;
5335                try {
5336                    StructStat stat = Os.stat(dataPath.getPath());
5337                    currentUid = stat.st_uid;
5338                } catch (ErrnoException e) {
5339                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5340                }
5341
5342                // If we have mismatched owners for the data path, we have a problem.
5343                if (currentUid != pkg.applicationInfo.uid) {
5344                    boolean recovered = false;
5345                    if (currentUid == 0) {
5346                        // The directory somehow became owned by root.  Wow.
5347                        // This is probably because the system was stopped while
5348                        // installd was in the middle of messing with its libs
5349                        // directory.  Ask installd to fix that.
5350                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5351                                pkg.applicationInfo.uid);
5352                        if (ret >= 0) {
5353                            recovered = true;
5354                            String msg = "Package " + pkg.packageName
5355                                    + " unexpectedly changed to uid 0; recovered to " +
5356                                    + pkg.applicationInfo.uid;
5357                            reportSettingsProblem(Log.WARN, msg);
5358                        }
5359                    }
5360                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5361                            || (scanFlags&SCAN_BOOTING) != 0)) {
5362                        // If this is a system app, we can at least delete its
5363                        // current data so the application will still work.
5364                        int ret = removeDataDirsLI(pkgName);
5365                        if (ret >= 0) {
5366                            // TODO: Kill the processes first
5367                            // Old data gone!
5368                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5369                                    ? "System package " : "Third party package ";
5370                            String msg = prefix + pkg.packageName
5371                                    + " has changed from uid: "
5372                                    + currentUid + " to "
5373                                    + pkg.applicationInfo.uid + "; old data erased";
5374                            reportSettingsProblem(Log.WARN, msg);
5375                            recovered = true;
5376
5377                            // And now re-install the app.
5378                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5379                                                   pkg.applicationInfo.seinfo);
5380                            if (ret == -1) {
5381                                // Ack should not happen!
5382                                msg = prefix + pkg.packageName
5383                                        + " could not have data directory re-created after delete.";
5384                                reportSettingsProblem(Log.WARN, msg);
5385                                throw new PackageManagerException(
5386                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5387                            }
5388                        }
5389                        if (!recovered) {
5390                            mHasSystemUidErrors = true;
5391                        }
5392                    } else if (!recovered) {
5393                        // If we allow this install to proceed, we will be broken.
5394                        // Abort, abort!
5395                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5396                                "scanPackageLI");
5397                    }
5398                    if (!recovered) {
5399                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5400                            + pkg.applicationInfo.uid + "/fs_"
5401                            + currentUid;
5402                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5403                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5404                        String msg = "Package " + pkg.packageName
5405                                + " has mismatched uid: "
5406                                + currentUid + " on disk, "
5407                                + pkg.applicationInfo.uid + " in settings";
5408                        // writer
5409                        synchronized (mPackages) {
5410                            mSettings.mReadMessages.append(msg);
5411                            mSettings.mReadMessages.append('\n');
5412                            uidError = true;
5413                            if (!pkgSetting.uidError) {
5414                                reportSettingsProblem(Log.ERROR, msg);
5415                            }
5416                        }
5417                    }
5418                }
5419                pkg.applicationInfo.dataDir = dataPath.getPath();
5420                if (mShouldRestoreconData) {
5421                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5422                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5423                                pkg.applicationInfo.uid);
5424                }
5425            } else {
5426                if (DEBUG_PACKAGE_SCANNING) {
5427                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5428                        Log.v(TAG, "Want this data dir: " + dataPath);
5429                }
5430                //invoke installer to do the actual installation
5431                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5432                                           pkg.applicationInfo.seinfo);
5433                if (ret < 0) {
5434                    // Error from installer
5435                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5436                            "Unable to create data dirs [errorCode=" + ret + "]");
5437                }
5438
5439                if (dataPath.exists()) {
5440                    pkg.applicationInfo.dataDir = dataPath.getPath();
5441                } else {
5442                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5443                    pkg.applicationInfo.dataDir = null;
5444                }
5445            }
5446
5447            pkgSetting.uidError = uidError;
5448        }
5449
5450        final String path = scanFile.getPath();
5451        final String codePath = pkg.applicationInfo.getCodePath();
5452        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5453        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5454            setBundledAppAbisAndRoots(pkg, pkgSetting);
5455
5456            // If we haven't found any native libraries for the app, check if it has
5457            // renderscript code. We'll need to force the app to 32 bit if it has
5458            // renderscript bitcode.
5459            if (pkg.applicationInfo.primaryCpuAbi == null
5460                    && pkg.applicationInfo.secondaryCpuAbi == null
5461                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5462                NativeLibraryHelper.Handle handle = null;
5463                try {
5464                    handle = NativeLibraryHelper.Handle.create(scanFile);
5465                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5466                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5467                    }
5468                } catch (IOException ioe) {
5469                    Slog.w(TAG, "Error scanning system app : " + ioe);
5470                } finally {
5471                    IoUtils.closeQuietly(handle);
5472                }
5473            }
5474
5475            setNativeLibraryPaths(pkg);
5476        } else {
5477            // TODO: We can probably be smarter about this stuff. For installed apps,
5478            // we can calculate this information at install time once and for all. For
5479            // system apps, we can probably assume that this information doesn't change
5480            // after the first boot scan. As things stand, we do lots of unnecessary work.
5481
5482            // Give ourselves some initial paths; we'll come back for another
5483            // pass once we've determined ABI below.
5484            setNativeLibraryPaths(pkg);
5485
5486            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5487            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5488            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5489
5490            NativeLibraryHelper.Handle handle = null;
5491            try {
5492                handle = NativeLibraryHelper.Handle.create(scanFile);
5493                // TODO(multiArch): This can be null for apps that didn't go through the
5494                // usual installation process. We can calculate it again, like we
5495                // do during install time.
5496                //
5497                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5498                // unnecessary.
5499                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5500
5501                // Null out the abis so that they can be recalculated.
5502                pkg.applicationInfo.primaryCpuAbi = null;
5503                pkg.applicationInfo.secondaryCpuAbi = null;
5504                if (isMultiArch(pkg.applicationInfo)) {
5505                    // Warn if we've set an abiOverride for multi-lib packages..
5506                    // By definition, we need to copy both 32 and 64 bit libraries for
5507                    // such packages.
5508                    if (pkg.cpuAbiOverride != null
5509                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5510                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5511                    }
5512
5513                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5514                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5515                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5516                        if (isAsec) {
5517                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5518                        } else {
5519                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5520                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5521                                    useIsaSpecificSubdirs);
5522                        }
5523                    }
5524
5525                    maybeThrowExceptionForMultiArchCopy(
5526                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5527
5528                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5529                        if (isAsec) {
5530                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5531                        } else {
5532                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5533                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5534                                    useIsaSpecificSubdirs);
5535                        }
5536                    }
5537
5538                    maybeThrowExceptionForMultiArchCopy(
5539                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5540
5541                    if (abi64 >= 0) {
5542                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5543                    }
5544
5545                    if (abi32 >= 0) {
5546                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5547                        if (abi64 >= 0) {
5548                            pkg.applicationInfo.secondaryCpuAbi = abi;
5549                        } else {
5550                            pkg.applicationInfo.primaryCpuAbi = abi;
5551                        }
5552                    }
5553                } else {
5554                    String[] abiList = (cpuAbiOverride != null) ?
5555                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5556
5557                    // Enable gross and lame hacks for apps that are built with old
5558                    // SDK tools. We must scan their APKs for renderscript bitcode and
5559                    // not launch them if it's present. Don't bother checking on devices
5560                    // that don't have 64 bit support.
5561                    boolean needsRenderScriptOverride = false;
5562                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5563                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5564                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5565                        needsRenderScriptOverride = true;
5566                    }
5567
5568                    final int copyRet;
5569                    if (isAsec) {
5570                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5571                    } else {
5572                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5573                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5574                    }
5575
5576                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5577                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5578                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5579                    }
5580
5581                    if (copyRet >= 0) {
5582                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5583                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5584                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5585                    } else if (needsRenderScriptOverride) {
5586                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5587                    }
5588                }
5589            } catch (IOException ioe) {
5590                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5591            } finally {
5592                IoUtils.closeQuietly(handle);
5593            }
5594
5595            // Now that we've calculated the ABIs and determined if it's an internal app,
5596            // we will go ahead and populate the nativeLibraryPath.
5597            setNativeLibraryPaths(pkg);
5598
5599            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5600            final int[] userIds = sUserManager.getUserIds();
5601            synchronized (mInstallLock) {
5602                // Create a native library symlink only if we have native libraries
5603                // and if the native libraries are 32 bit libraries. We do not provide
5604                // this symlink for 64 bit libraries.
5605                if (pkg.applicationInfo.primaryCpuAbi != null &&
5606                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5607                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5608                    for (int userId : userIds) {
5609                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5610                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5611                                    "Failed linking native library dir (user=" + userId + ")");
5612                        }
5613                    }
5614                }
5615            }
5616        }
5617
5618        // This is a special case for the "system" package, where the ABI is
5619        // dictated by the zygote configuration (and init.rc). We should keep track
5620        // of this ABI so that we can deal with "normal" applications that run under
5621        // the same UID correctly.
5622        if (mPlatformPackage == pkg) {
5623            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5624                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5625        }
5626
5627        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5628        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5629        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5630        // Copy the derived override back to the parsed package, so that we can
5631        // update the package settings accordingly.
5632        pkg.cpuAbiOverride = cpuAbiOverride;
5633
5634        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5635                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5636                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5637
5638        // Push the derived path down into PackageSettings so we know what to
5639        // clean up at uninstall time.
5640        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5641
5642        if (DEBUG_ABI_SELECTION) {
5643            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5644                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5645                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5646        }
5647
5648        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5649            // We don't do this here during boot because we can do it all
5650            // at once after scanning all existing packages.
5651            //
5652            // We also do this *before* we perform dexopt on this package, so that
5653            // we can avoid redundant dexopts, and also to make sure we've got the
5654            // code and package path correct.
5655            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5656                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5657        }
5658
5659        if ((scanFlags&SCAN_NO_DEX) == 0) {
5660            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5661                    == DEX_OPT_FAILED) {
5662                if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5663                    removeDataDirsLI(pkg.packageName);
5664                }
5665
5666                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5667            }
5668        }
5669
5670        if (mFactoryTest && pkg.requestedPermissions.contains(
5671                android.Manifest.permission.FACTORY_TEST)) {
5672            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5673        }
5674
5675        ArrayList<PackageParser.Package> clientLibPkgs = null;
5676
5677        // writer
5678        synchronized (mPackages) {
5679            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5680                // Only system apps can add new shared libraries.
5681                if (pkg.libraryNames != null) {
5682                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5683                        String name = pkg.libraryNames.get(i);
5684                        boolean allowed = false;
5685                        if (isUpdatedSystemApp(pkg)) {
5686                            // New library entries can only be added through the
5687                            // system image.  This is important to get rid of a lot
5688                            // of nasty edge cases: for example if we allowed a non-
5689                            // system update of the app to add a library, then uninstalling
5690                            // the update would make the library go away, and assumptions
5691                            // we made such as through app install filtering would now
5692                            // have allowed apps on the device which aren't compatible
5693                            // with it.  Better to just have the restriction here, be
5694                            // conservative, and create many fewer cases that can negatively
5695                            // impact the user experience.
5696                            final PackageSetting sysPs = mSettings
5697                                    .getDisabledSystemPkgLPr(pkg.packageName);
5698                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5699                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5700                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5701                                        allowed = true;
5702                                        allowed = true;
5703                                        break;
5704                                    }
5705                                }
5706                            }
5707                        } else {
5708                            allowed = true;
5709                        }
5710                        if (allowed) {
5711                            if (!mSharedLibraries.containsKey(name)) {
5712                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5713                            } else if (!name.equals(pkg.packageName)) {
5714                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5715                                        + name + " already exists; skipping");
5716                            }
5717                        } else {
5718                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5719                                    + name + " that is not declared on system image; skipping");
5720                        }
5721                    }
5722                    if ((scanFlags&SCAN_BOOTING) == 0) {
5723                        // If we are not booting, we need to update any applications
5724                        // that are clients of our shared library.  If we are booting,
5725                        // this will all be done once the scan is complete.
5726                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5727                    }
5728                }
5729            }
5730        }
5731
5732        // We also need to dexopt any apps that are dependent on this library.  Note that
5733        // if these fail, we should abort the install since installing the library will
5734        // result in some apps being broken.
5735        if (clientLibPkgs != null) {
5736            if ((scanFlags&SCAN_NO_DEX) == 0) {
5737                for (int i=0; i<clientLibPkgs.size(); i++) {
5738                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5739                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5740                            forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5741                            == DEX_OPT_FAILED) {
5742                        if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5743                            removeDataDirsLI(pkg.packageName);
5744                        }
5745
5746                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5747                                "scanPackageLI failed to dexopt clientLibPkgs");
5748                    }
5749                }
5750            }
5751        }
5752
5753        // Request the ActivityManager to kill the process(only for existing packages)
5754        // so that we do not end up in a confused state while the user is still using the older
5755        // version of the application while the new one gets installed.
5756        if ((scanFlags & SCAN_REPLACING) != 0) {
5757            killApplication(pkg.applicationInfo.packageName,
5758                        pkg.applicationInfo.uid, "update pkg");
5759        }
5760
5761        // Also need to kill any apps that are dependent on the library.
5762        if (clientLibPkgs != null) {
5763            for (int i=0; i<clientLibPkgs.size(); i++) {
5764                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5765                killApplication(clientPkg.applicationInfo.packageName,
5766                        clientPkg.applicationInfo.uid, "update lib");
5767            }
5768        }
5769
5770        // writer
5771        synchronized (mPackages) {
5772            // We don't expect installation to fail beyond this point
5773
5774            // Add the new setting to mSettings
5775            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5776            // Add the new setting to mPackages
5777            mPackages.put(pkg.applicationInfo.packageName, pkg);
5778            // Make sure we don't accidentally delete its data.
5779            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5780            while (iter.hasNext()) {
5781                PackageCleanItem item = iter.next();
5782                if (pkgName.equals(item.packageName)) {
5783                    iter.remove();
5784                }
5785            }
5786
5787            // Take care of first install / last update times.
5788            if (currentTime != 0) {
5789                if (pkgSetting.firstInstallTime == 0) {
5790                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5791                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5792                    pkgSetting.lastUpdateTime = currentTime;
5793                }
5794            } else if (pkgSetting.firstInstallTime == 0) {
5795                // We need *something*.  Take time time stamp of the file.
5796                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5797            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5798                if (scanFileTime != pkgSetting.timeStamp) {
5799                    // A package on the system image has changed; consider this
5800                    // to be an update.
5801                    pkgSetting.lastUpdateTime = scanFileTime;
5802                }
5803            }
5804
5805            // Add the package's KeySets to the global KeySetManagerService
5806            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5807            try {
5808                // Old KeySetData no longer valid.
5809                ksms.removeAppKeySetDataLPw(pkg.packageName);
5810                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5811                if (pkg.mKeySetMapping != null) {
5812                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5813                            pkg.mKeySetMapping.entrySet()) {
5814                        if (entry.getValue() != null) {
5815                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5816                                                          entry.getValue(), entry.getKey());
5817                        }
5818                    }
5819                    if (pkg.mUpgradeKeySets != null) {
5820                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5821                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5822                        }
5823                    }
5824                }
5825            } catch (NullPointerException e) {
5826                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5827            } catch (IllegalArgumentException e) {
5828                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5829            }
5830
5831            int N = pkg.providers.size();
5832            StringBuilder r = null;
5833            int i;
5834            for (i=0; i<N; i++) {
5835                PackageParser.Provider p = pkg.providers.get(i);
5836                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5837                        p.info.processName, pkg.applicationInfo.uid);
5838                mProviders.addProvider(p);
5839                p.syncable = p.info.isSyncable;
5840                if (p.info.authority != null) {
5841                    String names[] = p.info.authority.split(";");
5842                    p.info.authority = null;
5843                    for (int j = 0; j < names.length; j++) {
5844                        if (j == 1 && p.syncable) {
5845                            // We only want the first authority for a provider to possibly be
5846                            // syncable, so if we already added this provider using a different
5847                            // authority clear the syncable flag. We copy the provider before
5848                            // changing it because the mProviders object contains a reference
5849                            // to a provider that we don't want to change.
5850                            // Only do this for the second authority since the resulting provider
5851                            // object can be the same for all future authorities for this provider.
5852                            p = new PackageParser.Provider(p);
5853                            p.syncable = false;
5854                        }
5855                        if (!mProvidersByAuthority.containsKey(names[j])) {
5856                            mProvidersByAuthority.put(names[j], p);
5857                            if (p.info.authority == null) {
5858                                p.info.authority = names[j];
5859                            } else {
5860                                p.info.authority = p.info.authority + ";" + names[j];
5861                            }
5862                            if (DEBUG_PACKAGE_SCANNING) {
5863                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5864                                    Log.d(TAG, "Registered content provider: " + names[j]
5865                                            + ", className = " + p.info.name + ", isSyncable = "
5866                                            + p.info.isSyncable);
5867                            }
5868                        } else {
5869                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5870                            Slog.w(TAG, "Skipping provider name " + names[j] +
5871                                    " (in package " + pkg.applicationInfo.packageName +
5872                                    "): name already used by "
5873                                    + ((other != null && other.getComponentName() != null)
5874                                            ? other.getComponentName().getPackageName() : "?"));
5875                        }
5876                    }
5877                }
5878                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5879                    if (r == null) {
5880                        r = new StringBuilder(256);
5881                    } else {
5882                        r.append(' ');
5883                    }
5884                    r.append(p.info.name);
5885                }
5886            }
5887            if (r != null) {
5888                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5889            }
5890
5891            N = pkg.services.size();
5892            r = null;
5893            for (i=0; i<N; i++) {
5894                PackageParser.Service s = pkg.services.get(i);
5895                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5896                        s.info.processName, pkg.applicationInfo.uid);
5897                mServices.addService(s);
5898                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5899                    if (r == null) {
5900                        r = new StringBuilder(256);
5901                    } else {
5902                        r.append(' ');
5903                    }
5904                    r.append(s.info.name);
5905                }
5906            }
5907            if (r != null) {
5908                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5909            }
5910
5911            N = pkg.receivers.size();
5912            r = null;
5913            for (i=0; i<N; i++) {
5914                PackageParser.Activity a = pkg.receivers.get(i);
5915                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5916                        a.info.processName, pkg.applicationInfo.uid);
5917                mReceivers.addActivity(a, "receiver");
5918                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5919                    if (r == null) {
5920                        r = new StringBuilder(256);
5921                    } else {
5922                        r.append(' ');
5923                    }
5924                    r.append(a.info.name);
5925                }
5926            }
5927            if (r != null) {
5928                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5929            }
5930
5931            N = pkg.activities.size();
5932            r = null;
5933            for (i=0; i<N; i++) {
5934                PackageParser.Activity a = pkg.activities.get(i);
5935                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5936                        a.info.processName, pkg.applicationInfo.uid);
5937                mActivities.addActivity(a, "activity");
5938                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5939                    if (r == null) {
5940                        r = new StringBuilder(256);
5941                    } else {
5942                        r.append(' ');
5943                    }
5944                    r.append(a.info.name);
5945                }
5946            }
5947            if (r != null) {
5948                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5949            }
5950
5951            N = pkg.permissionGroups.size();
5952            r = null;
5953            for (i=0; i<N; i++) {
5954                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5955                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5956                if (cur == null) {
5957                    mPermissionGroups.put(pg.info.name, pg);
5958                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5959                        if (r == null) {
5960                            r = new StringBuilder(256);
5961                        } else {
5962                            r.append(' ');
5963                        }
5964                        r.append(pg.info.name);
5965                    }
5966                } else {
5967                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5968                            + pg.info.packageName + " ignored: original from "
5969                            + cur.info.packageName);
5970                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5971                        if (r == null) {
5972                            r = new StringBuilder(256);
5973                        } else {
5974                            r.append(' ');
5975                        }
5976                        r.append("DUP:");
5977                        r.append(pg.info.name);
5978                    }
5979                }
5980            }
5981            if (r != null) {
5982                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5983            }
5984
5985            N = pkg.permissions.size();
5986            r = null;
5987            for (i=0; i<N; i++) {
5988                PackageParser.Permission p = pkg.permissions.get(i);
5989                HashMap<String, BasePermission> permissionMap =
5990                        p.tree ? mSettings.mPermissionTrees
5991                        : mSettings.mPermissions;
5992                p.group = mPermissionGroups.get(p.info.group);
5993                if (p.info.group == null || p.group != null) {
5994                    BasePermission bp = permissionMap.get(p.info.name);
5995                    if (bp == null) {
5996                        bp = new BasePermission(p.info.name, p.info.packageName,
5997                                BasePermission.TYPE_NORMAL);
5998                        permissionMap.put(p.info.name, bp);
5999                    }
6000                    if (bp.perm == null) {
6001                        if (bp.sourcePackage != null
6002                                && !bp.sourcePackage.equals(p.info.packageName)) {
6003                            // If this is a permission that was formerly defined by a non-system
6004                            // app, but is now defined by a system app (following an upgrade),
6005                            // discard the previous declaration and consider the system's to be
6006                            // canonical.
6007                            if (isSystemApp(p.owner)) {
6008                                String msg = "New decl " + p.owner + " of permission  "
6009                                        + p.info.name + " is system";
6010                                reportSettingsProblem(Log.WARN, msg);
6011                                bp.sourcePackage = null;
6012                            }
6013                        }
6014                        if (bp.sourcePackage == null
6015                                || bp.sourcePackage.equals(p.info.packageName)) {
6016                            BasePermission tree = findPermissionTreeLP(p.info.name);
6017                            if (tree == null
6018                                    || tree.sourcePackage.equals(p.info.packageName)) {
6019                                bp.packageSetting = pkgSetting;
6020                                bp.perm = p;
6021                                bp.uid = pkg.applicationInfo.uid;
6022                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6023                                    if (r == null) {
6024                                        r = new StringBuilder(256);
6025                                    } else {
6026                                        r.append(' ');
6027                                    }
6028                                    r.append(p.info.name);
6029                                }
6030                            } else {
6031                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6032                                        + p.info.packageName + " ignored: base tree "
6033                                        + tree.name + " is from package "
6034                                        + tree.sourcePackage);
6035                            }
6036                        } else {
6037                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6038                                    + p.info.packageName + " ignored: original from "
6039                                    + bp.sourcePackage);
6040                        }
6041                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6042                        if (r == null) {
6043                            r = new StringBuilder(256);
6044                        } else {
6045                            r.append(' ');
6046                        }
6047                        r.append("DUP:");
6048                        r.append(p.info.name);
6049                    }
6050                    if (bp.perm == p) {
6051                        bp.protectionLevel = p.info.protectionLevel;
6052                    }
6053                } else {
6054                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6055                            + p.info.packageName + " ignored: no group "
6056                            + p.group);
6057                }
6058            }
6059            if (r != null) {
6060                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6061            }
6062
6063            N = pkg.instrumentation.size();
6064            r = null;
6065            for (i=0; i<N; i++) {
6066                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6067                a.info.packageName = pkg.applicationInfo.packageName;
6068                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6069                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6070                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6071                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6072                a.info.dataDir = pkg.applicationInfo.dataDir;
6073
6074                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6075                // need other information about the application, like the ABI and what not ?
6076                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6077                mInstrumentation.put(a.getComponentName(), a);
6078                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6079                    if (r == null) {
6080                        r = new StringBuilder(256);
6081                    } else {
6082                        r.append(' ');
6083                    }
6084                    r.append(a.info.name);
6085                }
6086            }
6087            if (r != null) {
6088                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6089            }
6090
6091            if (pkg.protectedBroadcasts != null) {
6092                N = pkg.protectedBroadcasts.size();
6093                for (i=0; i<N; i++) {
6094                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6095                }
6096            }
6097
6098            pkgSetting.setTimeStamp(scanFileTime);
6099
6100            // Create idmap files for pairs of (packages, overlay packages).
6101            // Note: "android", ie framework-res.apk, is handled by native layers.
6102            if (pkg.mOverlayTarget != null) {
6103                // This is an overlay package.
6104                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6105                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6106                        mOverlays.put(pkg.mOverlayTarget,
6107                                new HashMap<String, PackageParser.Package>());
6108                    }
6109                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6110                    map.put(pkg.packageName, pkg);
6111                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6112                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6113                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6114                                "scanPackageLI failed to createIdmap");
6115                    }
6116                }
6117            } else if (mOverlays.containsKey(pkg.packageName) &&
6118                    !pkg.packageName.equals("android")) {
6119                // This is a regular package, with one or more known overlay packages.
6120                createIdmapsForPackageLI(pkg);
6121            }
6122        }
6123
6124        return pkg;
6125    }
6126
6127    /**
6128     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6129     * i.e, so that all packages can be run inside a single process if required.
6130     *
6131     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6132     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6133     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6134     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6135     * updating a package that belongs to a shared user.
6136     *
6137     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6138     * adds unnecessary complexity.
6139     */
6140    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6141            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6142        String requiredInstructionSet = null;
6143        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6144            requiredInstructionSet = VMRuntime.getInstructionSet(
6145                     scannedPackage.applicationInfo.primaryCpuAbi);
6146        }
6147
6148        PackageSetting requirer = null;
6149        for (PackageSetting ps : packagesForUser) {
6150            // If packagesForUser contains scannedPackage, we skip it. This will happen
6151            // when scannedPackage is an update of an existing package. Without this check,
6152            // we will never be able to change the ABI of any package belonging to a shared
6153            // user, even if it's compatible with other packages.
6154            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6155                if (ps.primaryCpuAbiString == null) {
6156                    continue;
6157                }
6158
6159                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6160                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6161                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6162                    // this but there's not much we can do.
6163                    String errorMessage = "Instruction set mismatch, "
6164                            + ((requirer == null) ? "[caller]" : requirer)
6165                            + " requires " + requiredInstructionSet + " whereas " + ps
6166                            + " requires " + instructionSet;
6167                    Slog.w(TAG, errorMessage);
6168                }
6169
6170                if (requiredInstructionSet == null) {
6171                    requiredInstructionSet = instructionSet;
6172                    requirer = ps;
6173                }
6174            }
6175        }
6176
6177        if (requiredInstructionSet != null) {
6178            String adjustedAbi;
6179            if (requirer != null) {
6180                // requirer != null implies that either scannedPackage was null or that scannedPackage
6181                // did not require an ABI, in which case we have to adjust scannedPackage to match
6182                // the ABI of the set (which is the same as requirer's ABI)
6183                adjustedAbi = requirer.primaryCpuAbiString;
6184                if (scannedPackage != null) {
6185                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6186                }
6187            } else {
6188                // requirer == null implies that we're updating all ABIs in the set to
6189                // match scannedPackage.
6190                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6191            }
6192
6193            for (PackageSetting ps : packagesForUser) {
6194                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6195                    if (ps.primaryCpuAbiString != null) {
6196                        continue;
6197                    }
6198
6199                    ps.primaryCpuAbiString = adjustedAbi;
6200                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6201                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6202                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6203
6204                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6205                                deferDexOpt, true) == DEX_OPT_FAILED) {
6206                            ps.primaryCpuAbiString = null;
6207                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6208                            return;
6209                        } else {
6210                            mInstaller.rmdex(ps.codePathString,
6211                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6212                        }
6213                    }
6214                }
6215            }
6216        }
6217    }
6218
6219    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6220        synchronized (mPackages) {
6221            mResolverReplaced = true;
6222            // Set up information for custom user intent resolution activity.
6223            mResolveActivity.applicationInfo = pkg.applicationInfo;
6224            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6225            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6226            mResolveActivity.processName = null;
6227            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6228            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6229                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6230            mResolveActivity.theme = 0;
6231            mResolveActivity.exported = true;
6232            mResolveActivity.enabled = true;
6233            mResolveInfo.activityInfo = mResolveActivity;
6234            mResolveInfo.priority = 0;
6235            mResolveInfo.preferredOrder = 0;
6236            mResolveInfo.match = 0;
6237            mResolveComponentName = mCustomResolverComponentName;
6238            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6239                    mResolveComponentName);
6240        }
6241    }
6242
6243    private static String calculateBundledApkRoot(final String codePathString) {
6244        final File codePath = new File(codePathString);
6245        final File codeRoot;
6246        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6247            codeRoot = Environment.getRootDirectory();
6248        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6249            codeRoot = Environment.getOemDirectory();
6250        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6251            codeRoot = Environment.getVendorDirectory();
6252        } else {
6253            // Unrecognized code path; take its top real segment as the apk root:
6254            // e.g. /something/app/blah.apk => /something
6255            try {
6256                File f = codePath.getCanonicalFile();
6257                File parent = f.getParentFile();    // non-null because codePath is a file
6258                File tmp;
6259                while ((tmp = parent.getParentFile()) != null) {
6260                    f = parent;
6261                    parent = tmp;
6262                }
6263                codeRoot = f;
6264                Slog.w(TAG, "Unrecognized code path "
6265                        + codePath + " - using " + codeRoot);
6266            } catch (IOException e) {
6267                // Can't canonicalize the code path -- shenanigans?
6268                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6269                return Environment.getRootDirectory().getPath();
6270            }
6271        }
6272        return codeRoot.getPath();
6273    }
6274
6275    /**
6276     * Derive and set the location of native libraries for the given package,
6277     * which varies depending on where and how the package was installed.
6278     */
6279    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6280        final ApplicationInfo info = pkg.applicationInfo;
6281        final String codePath = pkg.codePath;
6282        final File codeFile = new File(codePath);
6283        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6284        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6285
6286        info.nativeLibraryRootDir = null;
6287        info.nativeLibraryRootRequiresIsa = false;
6288        info.nativeLibraryDir = null;
6289        info.secondaryNativeLibraryDir = null;
6290
6291        if (isApkFile(codeFile)) {
6292            // Monolithic install
6293            if (bundledApp) {
6294                // If "/system/lib64/apkname" exists, assume that is the per-package
6295                // native library directory to use; otherwise use "/system/lib/apkname".
6296                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6297                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6298                        getPrimaryInstructionSet(info));
6299
6300                // This is a bundled system app so choose the path based on the ABI.
6301                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6302                // is just the default path.
6303                final String apkName = deriveCodePathName(codePath);
6304                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6305                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6306                        apkName).getAbsolutePath();
6307
6308                if (info.secondaryCpuAbi != null) {
6309                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6310                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6311                            secondaryLibDir, apkName).getAbsolutePath();
6312                }
6313            } else if (asecApp) {
6314                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6315                        .getAbsolutePath();
6316            } else {
6317                final String apkName = deriveCodePathName(codePath);
6318                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6319                        .getAbsolutePath();
6320            }
6321
6322            info.nativeLibraryRootRequiresIsa = false;
6323            info.nativeLibraryDir = info.nativeLibraryRootDir;
6324        } else {
6325            // Cluster install
6326            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6327            info.nativeLibraryRootRequiresIsa = true;
6328
6329            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6330                    getPrimaryInstructionSet(info)).getAbsolutePath();
6331
6332            if (info.secondaryCpuAbi != null) {
6333                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6334                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6335            }
6336        }
6337    }
6338
6339    /**
6340     * Calculate the abis and roots for a bundled app. These can uniquely
6341     * be determined from the contents of the system partition, i.e whether
6342     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6343     * of this information, and instead assume that the system was built
6344     * sensibly.
6345     */
6346    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6347                                           PackageSetting pkgSetting) {
6348        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6349
6350        // If "/system/lib64/apkname" exists, assume that is the per-package
6351        // native library directory to use; otherwise use "/system/lib/apkname".
6352        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6353        setBundledAppAbi(pkg, apkRoot, apkName);
6354        // pkgSetting might be null during rescan following uninstall of updates
6355        // to a bundled app, so accommodate that possibility.  The settings in
6356        // that case will be established later from the parsed package.
6357        //
6358        // If the settings aren't null, sync them up with what we've just derived.
6359        // note that apkRoot isn't stored in the package settings.
6360        if (pkgSetting != null) {
6361            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6362            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6363        }
6364    }
6365
6366    /**
6367     * Deduces the ABI of a bundled app and sets the relevant fields on the
6368     * parsed pkg object.
6369     *
6370     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6371     *        under which system libraries are installed.
6372     * @param apkName the name of the installed package.
6373     */
6374    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6375        final File codeFile = new File(pkg.codePath);
6376
6377        final boolean has64BitLibs;
6378        final boolean has32BitLibs;
6379        if (isApkFile(codeFile)) {
6380            // Monolithic install
6381            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6382            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6383        } else {
6384            // Cluster install
6385            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6386            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6387                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6388                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6389                has64BitLibs = (new File(rootDir, isa)).exists();
6390            } else {
6391                has64BitLibs = false;
6392            }
6393            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6394                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6395                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6396                has32BitLibs = (new File(rootDir, isa)).exists();
6397            } else {
6398                has32BitLibs = false;
6399            }
6400        }
6401
6402        if (has64BitLibs && !has32BitLibs) {
6403            // The package has 64 bit libs, but not 32 bit libs. Its primary
6404            // ABI should be 64 bit. We can safely assume here that the bundled
6405            // native libraries correspond to the most preferred ABI in the list.
6406
6407            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6408            pkg.applicationInfo.secondaryCpuAbi = null;
6409        } else if (has32BitLibs && !has64BitLibs) {
6410            // The package has 32 bit libs but not 64 bit libs. Its primary
6411            // ABI should be 32 bit.
6412
6413            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6414            pkg.applicationInfo.secondaryCpuAbi = null;
6415        } else if (has32BitLibs && has64BitLibs) {
6416            // The application has both 64 and 32 bit bundled libraries. We check
6417            // here that the app declares multiArch support, and warn if it doesn't.
6418            //
6419            // We will be lenient here and record both ABIs. The primary will be the
6420            // ABI that's higher on the list, i.e, a device that's configured to prefer
6421            // 64 bit apps will see a 64 bit primary ABI,
6422
6423            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6424                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6425            }
6426
6427            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6428                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6429                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6430            } else {
6431                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6432                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6433            }
6434        } else {
6435            pkg.applicationInfo.primaryCpuAbi = null;
6436            pkg.applicationInfo.secondaryCpuAbi = null;
6437        }
6438    }
6439
6440    private void killApplication(String pkgName, int appId, String reason) {
6441        // Request the ActivityManager to kill the process(only for existing packages)
6442        // so that we do not end up in a confused state while the user is still using the older
6443        // version of the application while the new one gets installed.
6444        IActivityManager am = ActivityManagerNative.getDefault();
6445        if (am != null) {
6446            try {
6447                am.killApplicationWithAppId(pkgName, appId, reason);
6448            } catch (RemoteException e) {
6449            }
6450        }
6451    }
6452
6453    void removePackageLI(PackageSetting ps, boolean chatty) {
6454        if (DEBUG_INSTALL) {
6455            if (chatty)
6456                Log.d(TAG, "Removing package " + ps.name);
6457        }
6458
6459        // writer
6460        synchronized (mPackages) {
6461            mPackages.remove(ps.name);
6462            final PackageParser.Package pkg = ps.pkg;
6463            if (pkg != null) {
6464                cleanPackageDataStructuresLILPw(pkg, chatty);
6465            }
6466        }
6467    }
6468
6469    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6470        if (DEBUG_INSTALL) {
6471            if (chatty)
6472                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6473        }
6474
6475        // writer
6476        synchronized (mPackages) {
6477            mPackages.remove(pkg.applicationInfo.packageName);
6478            cleanPackageDataStructuresLILPw(pkg, chatty);
6479        }
6480    }
6481
6482    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6483        int N = pkg.providers.size();
6484        StringBuilder r = null;
6485        int i;
6486        for (i=0; i<N; i++) {
6487            PackageParser.Provider p = pkg.providers.get(i);
6488            mProviders.removeProvider(p);
6489            if (p.info.authority == null) {
6490
6491                /* There was another ContentProvider with this authority when
6492                 * this app was installed so this authority is null,
6493                 * Ignore it as we don't have to unregister the provider.
6494                 */
6495                continue;
6496            }
6497            String names[] = p.info.authority.split(";");
6498            for (int j = 0; j < names.length; j++) {
6499                if (mProvidersByAuthority.get(names[j]) == p) {
6500                    mProvidersByAuthority.remove(names[j]);
6501                    if (DEBUG_REMOVE) {
6502                        if (chatty)
6503                            Log.d(TAG, "Unregistered content provider: " + names[j]
6504                                    + ", className = " + p.info.name + ", isSyncable = "
6505                                    + p.info.isSyncable);
6506                    }
6507                }
6508            }
6509            if (DEBUG_REMOVE && chatty) {
6510                if (r == null) {
6511                    r = new StringBuilder(256);
6512                } else {
6513                    r.append(' ');
6514                }
6515                r.append(p.info.name);
6516            }
6517        }
6518        if (r != null) {
6519            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6520        }
6521
6522        N = pkg.services.size();
6523        r = null;
6524        for (i=0; i<N; i++) {
6525            PackageParser.Service s = pkg.services.get(i);
6526            mServices.removeService(s);
6527            if (chatty) {
6528                if (r == null) {
6529                    r = new StringBuilder(256);
6530                } else {
6531                    r.append(' ');
6532                }
6533                r.append(s.info.name);
6534            }
6535        }
6536        if (r != null) {
6537            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6538        }
6539
6540        N = pkg.receivers.size();
6541        r = null;
6542        for (i=0; i<N; i++) {
6543            PackageParser.Activity a = pkg.receivers.get(i);
6544            mReceivers.removeActivity(a, "receiver");
6545            if (DEBUG_REMOVE && chatty) {
6546                if (r == null) {
6547                    r = new StringBuilder(256);
6548                } else {
6549                    r.append(' ');
6550                }
6551                r.append(a.info.name);
6552            }
6553        }
6554        if (r != null) {
6555            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6556        }
6557
6558        N = pkg.activities.size();
6559        r = null;
6560        for (i=0; i<N; i++) {
6561            PackageParser.Activity a = pkg.activities.get(i);
6562            mActivities.removeActivity(a, "activity");
6563            if (DEBUG_REMOVE && chatty) {
6564                if (r == null) {
6565                    r = new StringBuilder(256);
6566                } else {
6567                    r.append(' ');
6568                }
6569                r.append(a.info.name);
6570            }
6571        }
6572        if (r != null) {
6573            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6574        }
6575
6576        N = pkg.permissions.size();
6577        r = null;
6578        for (i=0; i<N; i++) {
6579            PackageParser.Permission p = pkg.permissions.get(i);
6580            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6581            if (bp == null) {
6582                bp = mSettings.mPermissionTrees.get(p.info.name);
6583            }
6584            if (bp != null && bp.perm == p) {
6585                bp.perm = null;
6586                if (DEBUG_REMOVE && chatty) {
6587                    if (r == null) {
6588                        r = new StringBuilder(256);
6589                    } else {
6590                        r.append(' ');
6591                    }
6592                    r.append(p.info.name);
6593                }
6594            }
6595            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6596                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6597                if (appOpPerms != null) {
6598                    appOpPerms.remove(pkg.packageName);
6599                }
6600            }
6601        }
6602        if (r != null) {
6603            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6604        }
6605
6606        N = pkg.requestedPermissions.size();
6607        r = null;
6608        for (i=0; i<N; i++) {
6609            String perm = pkg.requestedPermissions.get(i);
6610            BasePermission bp = mSettings.mPermissions.get(perm);
6611            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6612                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6613                if (appOpPerms != null) {
6614                    appOpPerms.remove(pkg.packageName);
6615                    if (appOpPerms.isEmpty()) {
6616                        mAppOpPermissionPackages.remove(perm);
6617                    }
6618                }
6619            }
6620        }
6621        if (r != null) {
6622            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6623        }
6624
6625        N = pkg.instrumentation.size();
6626        r = null;
6627        for (i=0; i<N; i++) {
6628            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6629            mInstrumentation.remove(a.getComponentName());
6630            if (DEBUG_REMOVE && chatty) {
6631                if (r == null) {
6632                    r = new StringBuilder(256);
6633                } else {
6634                    r.append(' ');
6635                }
6636                r.append(a.info.name);
6637            }
6638        }
6639        if (r != null) {
6640            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6641        }
6642
6643        r = null;
6644        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6645            // Only system apps can hold shared libraries.
6646            if (pkg.libraryNames != null) {
6647                for (i=0; i<pkg.libraryNames.size(); i++) {
6648                    String name = pkg.libraryNames.get(i);
6649                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6650                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6651                        mSharedLibraries.remove(name);
6652                        if (DEBUG_REMOVE && chatty) {
6653                            if (r == null) {
6654                                r = new StringBuilder(256);
6655                            } else {
6656                                r.append(' ');
6657                            }
6658                            r.append(name);
6659                        }
6660                    }
6661                }
6662            }
6663        }
6664        if (r != null) {
6665            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6666        }
6667    }
6668
6669    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6670        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6671            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6672                return true;
6673            }
6674        }
6675        return false;
6676    }
6677
6678    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6679    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6680    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6681
6682    private void updatePermissionsLPw(String changingPkg,
6683            PackageParser.Package pkgInfo, int flags) {
6684        // Make sure there are no dangling permission trees.
6685        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6686        while (it.hasNext()) {
6687            final BasePermission bp = it.next();
6688            if (bp.packageSetting == null) {
6689                // We may not yet have parsed the package, so just see if
6690                // we still know about its settings.
6691                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6692            }
6693            if (bp.packageSetting == null) {
6694                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6695                        + " from package " + bp.sourcePackage);
6696                it.remove();
6697            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6698                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6699                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6700                            + " from package " + bp.sourcePackage);
6701                    flags |= UPDATE_PERMISSIONS_ALL;
6702                    it.remove();
6703                }
6704            }
6705        }
6706
6707        // Make sure all dynamic permissions have been assigned to a package,
6708        // and make sure there are no dangling permissions.
6709        it = mSettings.mPermissions.values().iterator();
6710        while (it.hasNext()) {
6711            final BasePermission bp = it.next();
6712            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6713                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6714                        + bp.name + " pkg=" + bp.sourcePackage
6715                        + " info=" + bp.pendingInfo);
6716                if (bp.packageSetting == null && bp.pendingInfo != null) {
6717                    final BasePermission tree = findPermissionTreeLP(bp.name);
6718                    if (tree != null && tree.perm != null) {
6719                        bp.packageSetting = tree.packageSetting;
6720                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6721                                new PermissionInfo(bp.pendingInfo));
6722                        bp.perm.info.packageName = tree.perm.info.packageName;
6723                        bp.perm.info.name = bp.name;
6724                        bp.uid = tree.uid;
6725                    }
6726                }
6727            }
6728            if (bp.packageSetting == null) {
6729                // We may not yet have parsed the package, so just see if
6730                // we still know about its settings.
6731                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6732            }
6733            if (bp.packageSetting == null) {
6734                Slog.w(TAG, "Removing dangling permission: " + bp.name
6735                        + " from package " + bp.sourcePackage);
6736                it.remove();
6737            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6738                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6739                    Slog.i(TAG, "Removing old permission: " + bp.name
6740                            + " from package " + bp.sourcePackage);
6741                    flags |= UPDATE_PERMISSIONS_ALL;
6742                    it.remove();
6743                }
6744            }
6745        }
6746
6747        // Now update the permissions for all packages, in particular
6748        // replace the granted permissions of the system packages.
6749        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6750            for (PackageParser.Package pkg : mPackages.values()) {
6751                if (pkg != pkgInfo) {
6752                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6753                }
6754            }
6755        }
6756
6757        if (pkgInfo != null) {
6758            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6759        }
6760    }
6761
6762    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6763        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6764        if (ps == null) {
6765            return;
6766        }
6767        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6768        HashSet<String> origPermissions = gp.grantedPermissions;
6769        boolean changedPermission = false;
6770
6771        if (replace) {
6772            ps.permissionsFixed = false;
6773            if (gp == ps) {
6774                origPermissions = new HashSet<String>(gp.grantedPermissions);
6775                gp.grantedPermissions.clear();
6776                gp.gids = mGlobalGids;
6777            }
6778        }
6779
6780        if (gp.gids == null) {
6781            gp.gids = mGlobalGids;
6782        }
6783
6784        final int N = pkg.requestedPermissions.size();
6785        for (int i=0; i<N; i++) {
6786            final String name = pkg.requestedPermissions.get(i);
6787            final boolean required = pkg.requestedPermissionsRequired.get(i);
6788            final BasePermission bp = mSettings.mPermissions.get(name);
6789            if (DEBUG_INSTALL) {
6790                if (gp != ps) {
6791                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6792                }
6793            }
6794
6795            if (bp == null || bp.packageSetting == null) {
6796                Slog.w(TAG, "Unknown permission " + name
6797                        + " in package " + pkg.packageName);
6798                continue;
6799            }
6800
6801            final String perm = bp.name;
6802            boolean allowed;
6803            boolean allowedSig = false;
6804            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6805                // Keep track of app op permissions.
6806                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6807                if (pkgs == null) {
6808                    pkgs = new ArraySet<>();
6809                    mAppOpPermissionPackages.put(bp.name, pkgs);
6810                }
6811                pkgs.add(pkg.packageName);
6812            }
6813            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6814            if (level == PermissionInfo.PROTECTION_NORMAL
6815                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6816                // We grant a normal or dangerous permission if any of the following
6817                // are true:
6818                // 1) The permission is required
6819                // 2) The permission is optional, but was granted in the past
6820                // 3) The permission is optional, but was requested by an
6821                //    app in /system (not /data)
6822                //
6823                // Otherwise, reject the permission.
6824                allowed = (required || origPermissions.contains(perm)
6825                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6826            } else if (bp.packageSetting == null) {
6827                // This permission is invalid; skip it.
6828                allowed = false;
6829            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6830                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6831                if (allowed) {
6832                    allowedSig = true;
6833                }
6834            } else {
6835                allowed = false;
6836            }
6837            if (DEBUG_INSTALL) {
6838                if (gp != ps) {
6839                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6840                }
6841            }
6842            if (allowed) {
6843                if (!isSystemApp(ps) && ps.permissionsFixed) {
6844                    // If this is an existing, non-system package, then
6845                    // we can't add any new permissions to it.
6846                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6847                        // Except...  if this is a permission that was added
6848                        // to the platform (note: need to only do this when
6849                        // updating the platform).
6850                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6851                    }
6852                }
6853                if (allowed) {
6854                    if (!gp.grantedPermissions.contains(perm)) {
6855                        changedPermission = true;
6856                        gp.grantedPermissions.add(perm);
6857                        gp.gids = appendInts(gp.gids, bp.gids);
6858                    } else if (!ps.haveGids) {
6859                        gp.gids = appendInts(gp.gids, bp.gids);
6860                    }
6861                } else {
6862                    Slog.w(TAG, "Not granting permission " + perm
6863                            + " to package " + pkg.packageName
6864                            + " because it was previously installed without");
6865                }
6866            } else {
6867                if (gp.grantedPermissions.remove(perm)) {
6868                    changedPermission = true;
6869                    gp.gids = removeInts(gp.gids, bp.gids);
6870                    Slog.i(TAG, "Un-granting permission " + perm
6871                            + " from package " + pkg.packageName
6872                            + " (protectionLevel=" + bp.protectionLevel
6873                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6874                            + ")");
6875                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6876                    // Don't print warning for app op permissions, since it is fine for them
6877                    // not to be granted, there is a UI for the user to decide.
6878                    Slog.w(TAG, "Not granting permission " + perm
6879                            + " to package " + pkg.packageName
6880                            + " (protectionLevel=" + bp.protectionLevel
6881                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6882                            + ")");
6883                }
6884            }
6885        }
6886
6887        if ((changedPermission || replace) && !ps.permissionsFixed &&
6888                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6889            // This is the first that we have heard about this package, so the
6890            // permissions we have now selected are fixed until explicitly
6891            // changed.
6892            ps.permissionsFixed = true;
6893        }
6894        ps.haveGids = true;
6895    }
6896
6897    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6898        boolean allowed = false;
6899        final int NP = PackageParser.NEW_PERMISSIONS.length;
6900        for (int ip=0; ip<NP; ip++) {
6901            final PackageParser.NewPermissionInfo npi
6902                    = PackageParser.NEW_PERMISSIONS[ip];
6903            if (npi.name.equals(perm)
6904                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6905                allowed = true;
6906                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6907                        + pkg.packageName);
6908                break;
6909            }
6910        }
6911        return allowed;
6912    }
6913
6914    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6915                                          BasePermission bp, HashSet<String> origPermissions) {
6916        boolean allowed;
6917        allowed = (compareSignatures(
6918                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6919                        == PackageManager.SIGNATURE_MATCH)
6920                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6921                        == PackageManager.SIGNATURE_MATCH);
6922        if (!allowed && (bp.protectionLevel
6923                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6924            if (isSystemApp(pkg)) {
6925                // For updated system applications, a system permission
6926                // is granted only if it had been defined by the original application.
6927                if (isUpdatedSystemApp(pkg)) {
6928                    final PackageSetting sysPs = mSettings
6929                            .getDisabledSystemPkgLPr(pkg.packageName);
6930                    final GrantedPermissions origGp = sysPs.sharedUser != null
6931                            ? sysPs.sharedUser : sysPs;
6932
6933                    if (origGp.grantedPermissions.contains(perm)) {
6934                        // If the original was granted this permission, we take
6935                        // that grant decision as read and propagate it to the
6936                        // update.
6937                        allowed = true;
6938                    } else {
6939                        // The system apk may have been updated with an older
6940                        // version of the one on the data partition, but which
6941                        // granted a new system permission that it didn't have
6942                        // before.  In this case we do want to allow the app to
6943                        // now get the new permission if the ancestral apk is
6944                        // privileged to get it.
6945                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6946                            for (int j=0;
6947                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6948                                if (perm.equals(
6949                                        sysPs.pkg.requestedPermissions.get(j))) {
6950                                    allowed = true;
6951                                    break;
6952                                }
6953                            }
6954                        }
6955                    }
6956                } else {
6957                    allowed = isPrivilegedApp(pkg);
6958                }
6959            }
6960        }
6961        if (!allowed && (bp.protectionLevel
6962                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6963            // For development permissions, a development permission
6964            // is granted only if it was already granted.
6965            allowed = origPermissions.contains(perm);
6966        }
6967        return allowed;
6968    }
6969
6970    final class ActivityIntentResolver
6971            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6972        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6973                boolean defaultOnly, int userId) {
6974            if (!sUserManager.exists(userId)) return null;
6975            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6976            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6977        }
6978
6979        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6980                int userId) {
6981            if (!sUserManager.exists(userId)) return null;
6982            mFlags = flags;
6983            return super.queryIntent(intent, resolvedType,
6984                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6985        }
6986
6987        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6988                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6989            if (!sUserManager.exists(userId)) return null;
6990            if (packageActivities == null) {
6991                return null;
6992            }
6993            mFlags = flags;
6994            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6995            final int N = packageActivities.size();
6996            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6997                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6998
6999            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7000            for (int i = 0; i < N; ++i) {
7001                intentFilters = packageActivities.get(i).intents;
7002                if (intentFilters != null && intentFilters.size() > 0) {
7003                    PackageParser.ActivityIntentInfo[] array =
7004                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7005                    intentFilters.toArray(array);
7006                    listCut.add(array);
7007                }
7008            }
7009            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7010        }
7011
7012        public final void addActivity(PackageParser.Activity a, String type) {
7013            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7014            mActivities.put(a.getComponentName(), a);
7015            if (DEBUG_SHOW_INFO)
7016                Log.v(
7017                TAG, "  " + type + " " +
7018                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7019            if (DEBUG_SHOW_INFO)
7020                Log.v(TAG, "    Class=" + a.info.name);
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 (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7025                    intent.setPriority(0);
7026                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7027                            + a.className + " with priority > 0, forcing to 0");
7028                }
7029                if (DEBUG_SHOW_INFO) {
7030                    Log.v(TAG, "    IntentFilter:");
7031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7032                }
7033                if (!intent.debugCheck()) {
7034                    Log.w(TAG, "==> For Activity " + a.info.name);
7035                }
7036                addFilter(intent);
7037            }
7038        }
7039
7040        public final void removeActivity(PackageParser.Activity a, String type) {
7041            mActivities.remove(a.getComponentName());
7042            if (DEBUG_SHOW_INFO) {
7043                Log.v(TAG, "  " + type + " "
7044                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7045                                : a.info.name) + ":");
7046                Log.v(TAG, "    Class=" + a.info.name);
7047            }
7048            final int NI = a.intents.size();
7049            for (int j=0; j<NI; j++) {
7050                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7051                if (DEBUG_SHOW_INFO) {
7052                    Log.v(TAG, "    IntentFilter:");
7053                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7054                }
7055                removeFilter(intent);
7056            }
7057        }
7058
7059        @Override
7060        protected boolean allowFilterResult(
7061                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7062            ActivityInfo filterAi = filter.activity.info;
7063            for (int i=dest.size()-1; i>=0; i--) {
7064                ActivityInfo destAi = dest.get(i).activityInfo;
7065                if (destAi.name == filterAi.name
7066                        && destAi.packageName == filterAi.packageName) {
7067                    return false;
7068                }
7069            }
7070            return true;
7071        }
7072
7073        @Override
7074        protected ActivityIntentInfo[] newArray(int size) {
7075            return new ActivityIntentInfo[size];
7076        }
7077
7078        @Override
7079        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7080            if (!sUserManager.exists(userId)) return true;
7081            PackageParser.Package p = filter.activity.owner;
7082            if (p != null) {
7083                PackageSetting ps = (PackageSetting)p.mExtras;
7084                if (ps != null) {
7085                    // System apps are never considered stopped for purposes of
7086                    // filtering, because there may be no way for the user to
7087                    // actually re-launch them.
7088                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7089                            && ps.getStopped(userId);
7090                }
7091            }
7092            return false;
7093        }
7094
7095        @Override
7096        protected boolean isPackageForFilter(String packageName,
7097                PackageParser.ActivityIntentInfo info) {
7098            return packageName.equals(info.activity.owner.packageName);
7099        }
7100
7101        @Override
7102        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7103                int match, int userId) {
7104            if (!sUserManager.exists(userId)) return null;
7105            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7106                return null;
7107            }
7108            final PackageParser.Activity activity = info.activity;
7109            if (mSafeMode && (activity.info.applicationInfo.flags
7110                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7111                return null;
7112            }
7113            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7114            if (ps == null) {
7115                return null;
7116            }
7117            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7118                    ps.readUserState(userId), userId);
7119            if (ai == null) {
7120                return null;
7121            }
7122            final ResolveInfo res = new ResolveInfo();
7123            res.activityInfo = ai;
7124            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7125                res.filter = info;
7126            }
7127            res.priority = info.getPriority();
7128            res.preferredOrder = activity.owner.mPreferredOrder;
7129            //System.out.println("Result: " + res.activityInfo.className +
7130            //                   " = " + res.priority);
7131            res.match = match;
7132            res.isDefault = info.hasDefault;
7133            res.labelRes = info.labelRes;
7134            res.nonLocalizedLabel = info.nonLocalizedLabel;
7135            if (userNeedsBadging(userId)) {
7136                res.noResourceId = true;
7137            } else {
7138                res.icon = info.icon;
7139            }
7140            res.system = isSystemApp(res.activityInfo.applicationInfo);
7141            return res;
7142        }
7143
7144        @Override
7145        protected void sortResults(List<ResolveInfo> results) {
7146            Collections.sort(results, mResolvePrioritySorter);
7147        }
7148
7149        @Override
7150        protected void dumpFilter(PrintWriter out, String prefix,
7151                PackageParser.ActivityIntentInfo filter) {
7152            out.print(prefix); out.print(
7153                    Integer.toHexString(System.identityHashCode(filter.activity)));
7154                    out.print(' ');
7155                    filter.activity.printComponentShortName(out);
7156                    out.print(" filter ");
7157                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7158        }
7159
7160//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7161//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7162//            final List<ResolveInfo> retList = Lists.newArrayList();
7163//            while (i.hasNext()) {
7164//                final ResolveInfo resolveInfo = i.next();
7165//                if (isEnabledLP(resolveInfo.activityInfo)) {
7166//                    retList.add(resolveInfo);
7167//                }
7168//            }
7169//            return retList;
7170//        }
7171
7172        // Keys are String (activity class name), values are Activity.
7173        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7174                = new HashMap<ComponentName, PackageParser.Activity>();
7175        private int mFlags;
7176    }
7177
7178    private final class ServiceIntentResolver
7179            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7180        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7181                boolean defaultOnly, int userId) {
7182            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7183            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7184        }
7185
7186        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7187                int userId) {
7188            if (!sUserManager.exists(userId)) return null;
7189            mFlags = flags;
7190            return super.queryIntent(intent, resolvedType,
7191                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7192        }
7193
7194        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7195                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7196            if (!sUserManager.exists(userId)) return null;
7197            if (packageServices == null) {
7198                return null;
7199            }
7200            mFlags = flags;
7201            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7202            final int N = packageServices.size();
7203            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7204                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7205
7206            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7207            for (int i = 0; i < N; ++i) {
7208                intentFilters = packageServices.get(i).intents;
7209                if (intentFilters != null && intentFilters.size() > 0) {
7210                    PackageParser.ServiceIntentInfo[] array =
7211                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7212                    intentFilters.toArray(array);
7213                    listCut.add(array);
7214                }
7215            }
7216            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7217        }
7218
7219        public final void addService(PackageParser.Service s) {
7220            mServices.put(s.getComponentName(), s);
7221            if (DEBUG_SHOW_INFO) {
7222                Log.v(TAG, "  "
7223                        + (s.info.nonLocalizedLabel != null
7224                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7225                Log.v(TAG, "    Class=" + s.info.name);
7226            }
7227            final int NI = s.intents.size();
7228            int j;
7229            for (j=0; j<NI; j++) {
7230                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7231                if (DEBUG_SHOW_INFO) {
7232                    Log.v(TAG, "    IntentFilter:");
7233                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7234                }
7235                if (!intent.debugCheck()) {
7236                    Log.w(TAG, "==> For Service " + s.info.name);
7237                }
7238                addFilter(intent);
7239            }
7240        }
7241
7242        public final void removeService(PackageParser.Service s) {
7243            mServices.remove(s.getComponentName());
7244            if (DEBUG_SHOW_INFO) {
7245                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7246                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7247                Log.v(TAG, "    Class=" + s.info.name);
7248            }
7249            final int NI = s.intents.size();
7250            int j;
7251            for (j=0; j<NI; j++) {
7252                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7253                if (DEBUG_SHOW_INFO) {
7254                    Log.v(TAG, "    IntentFilter:");
7255                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7256                }
7257                removeFilter(intent);
7258            }
7259        }
7260
7261        @Override
7262        protected boolean allowFilterResult(
7263                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7264            ServiceInfo filterSi = filter.service.info;
7265            for (int i=dest.size()-1; i>=0; i--) {
7266                ServiceInfo destAi = dest.get(i).serviceInfo;
7267                if (destAi.name == filterSi.name
7268                        && destAi.packageName == filterSi.packageName) {
7269                    return false;
7270                }
7271            }
7272            return true;
7273        }
7274
7275        @Override
7276        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7277            return new PackageParser.ServiceIntentInfo[size];
7278        }
7279
7280        @Override
7281        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7282            if (!sUserManager.exists(userId)) return true;
7283            PackageParser.Package p = filter.service.owner;
7284            if (p != null) {
7285                PackageSetting ps = (PackageSetting)p.mExtras;
7286                if (ps != null) {
7287                    // System apps are never considered stopped for purposes of
7288                    // filtering, because there may be no way for the user to
7289                    // actually re-launch them.
7290                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7291                            && ps.getStopped(userId);
7292                }
7293            }
7294            return false;
7295        }
7296
7297        @Override
7298        protected boolean isPackageForFilter(String packageName,
7299                PackageParser.ServiceIntentInfo info) {
7300            return packageName.equals(info.service.owner.packageName);
7301        }
7302
7303        @Override
7304        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7305                int match, int userId) {
7306            if (!sUserManager.exists(userId)) return null;
7307            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7308            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7309                return null;
7310            }
7311            final PackageParser.Service service = info.service;
7312            if (mSafeMode && (service.info.applicationInfo.flags
7313                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7314                return null;
7315            }
7316            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7317            if (ps == null) {
7318                return null;
7319            }
7320            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7321                    ps.readUserState(userId), userId);
7322            if (si == null) {
7323                return null;
7324            }
7325            final ResolveInfo res = new ResolveInfo();
7326            res.serviceInfo = si;
7327            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7328                res.filter = filter;
7329            }
7330            res.priority = info.getPriority();
7331            res.preferredOrder = service.owner.mPreferredOrder;
7332            //System.out.println("Result: " + res.activityInfo.className +
7333            //                   " = " + res.priority);
7334            res.match = match;
7335            res.isDefault = info.hasDefault;
7336            res.labelRes = info.labelRes;
7337            res.nonLocalizedLabel = info.nonLocalizedLabel;
7338            res.icon = info.icon;
7339            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7340            return res;
7341        }
7342
7343        @Override
7344        protected void sortResults(List<ResolveInfo> results) {
7345            Collections.sort(results, mResolvePrioritySorter);
7346        }
7347
7348        @Override
7349        protected void dumpFilter(PrintWriter out, String prefix,
7350                PackageParser.ServiceIntentInfo filter) {
7351            out.print(prefix); out.print(
7352                    Integer.toHexString(System.identityHashCode(filter.service)));
7353                    out.print(' ');
7354                    filter.service.printComponentShortName(out);
7355                    out.print(" filter ");
7356                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7357        }
7358
7359//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7360//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7361//            final List<ResolveInfo> retList = Lists.newArrayList();
7362//            while (i.hasNext()) {
7363//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7364//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7365//                    retList.add(resolveInfo);
7366//                }
7367//            }
7368//            return retList;
7369//        }
7370
7371        // Keys are String (activity class name), values are Activity.
7372        private final HashMap<ComponentName, PackageParser.Service> mServices
7373                = new HashMap<ComponentName, PackageParser.Service>();
7374        private int mFlags;
7375    };
7376
7377    private final class ProviderIntentResolver
7378            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7379        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7380                boolean defaultOnly, int userId) {
7381            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7382            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7383        }
7384
7385        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7386                int userId) {
7387            if (!sUserManager.exists(userId))
7388                return null;
7389            mFlags = flags;
7390            return super.queryIntent(intent, resolvedType,
7391                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7392        }
7393
7394        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7395                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7396            if (!sUserManager.exists(userId))
7397                return null;
7398            if (packageProviders == null) {
7399                return null;
7400            }
7401            mFlags = flags;
7402            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7403            final int N = packageProviders.size();
7404            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7405                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7406
7407            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7408            for (int i = 0; i < N; ++i) {
7409                intentFilters = packageProviders.get(i).intents;
7410                if (intentFilters != null && intentFilters.size() > 0) {
7411                    PackageParser.ProviderIntentInfo[] array =
7412                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7413                    intentFilters.toArray(array);
7414                    listCut.add(array);
7415                }
7416            }
7417            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7418        }
7419
7420        public final void addProvider(PackageParser.Provider p) {
7421            if (mProviders.containsKey(p.getComponentName())) {
7422                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7423                return;
7424            }
7425
7426            mProviders.put(p.getComponentName(), p);
7427            if (DEBUG_SHOW_INFO) {
7428                Log.v(TAG, "  "
7429                        + (p.info.nonLocalizedLabel != null
7430                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7431                Log.v(TAG, "    Class=" + p.info.name);
7432            }
7433            final int NI = p.intents.size();
7434            int j;
7435            for (j = 0; j < NI; j++) {
7436                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7437                if (DEBUG_SHOW_INFO) {
7438                    Log.v(TAG, "    IntentFilter:");
7439                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7440                }
7441                if (!intent.debugCheck()) {
7442                    Log.w(TAG, "==> For Provider " + p.info.name);
7443                }
7444                addFilter(intent);
7445            }
7446        }
7447
7448        public final void removeProvider(PackageParser.Provider p) {
7449            mProviders.remove(p.getComponentName());
7450            if (DEBUG_SHOW_INFO) {
7451                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7452                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7453                Log.v(TAG, "    Class=" + p.info.name);
7454            }
7455            final int NI = p.intents.size();
7456            int j;
7457            for (j = 0; j < NI; j++) {
7458                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7459                if (DEBUG_SHOW_INFO) {
7460                    Log.v(TAG, "    IntentFilter:");
7461                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7462                }
7463                removeFilter(intent);
7464            }
7465        }
7466
7467        @Override
7468        protected boolean allowFilterResult(
7469                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7470            ProviderInfo filterPi = filter.provider.info;
7471            for (int i = dest.size() - 1; i >= 0; i--) {
7472                ProviderInfo destPi = dest.get(i).providerInfo;
7473                if (destPi.name == filterPi.name
7474                        && destPi.packageName == filterPi.packageName) {
7475                    return false;
7476                }
7477            }
7478            return true;
7479        }
7480
7481        @Override
7482        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7483            return new PackageParser.ProviderIntentInfo[size];
7484        }
7485
7486        @Override
7487        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7488            if (!sUserManager.exists(userId))
7489                return true;
7490            PackageParser.Package p = filter.provider.owner;
7491            if (p != null) {
7492                PackageSetting ps = (PackageSetting) p.mExtras;
7493                if (ps != null) {
7494                    // System apps are never considered stopped for purposes of
7495                    // filtering, because there may be no way for the user to
7496                    // actually re-launch them.
7497                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7498                            && ps.getStopped(userId);
7499                }
7500            }
7501            return false;
7502        }
7503
7504        @Override
7505        protected boolean isPackageForFilter(String packageName,
7506                PackageParser.ProviderIntentInfo info) {
7507            return packageName.equals(info.provider.owner.packageName);
7508        }
7509
7510        @Override
7511        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7512                int match, int userId) {
7513            if (!sUserManager.exists(userId))
7514                return null;
7515            final PackageParser.ProviderIntentInfo info = filter;
7516            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7517                return null;
7518            }
7519            final PackageParser.Provider provider = info.provider;
7520            if (mSafeMode && (provider.info.applicationInfo.flags
7521                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7522                return null;
7523            }
7524            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7525            if (ps == null) {
7526                return null;
7527            }
7528            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7529                    ps.readUserState(userId), userId);
7530            if (pi == null) {
7531                return null;
7532            }
7533            final ResolveInfo res = new ResolveInfo();
7534            res.providerInfo = pi;
7535            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7536                res.filter = filter;
7537            }
7538            res.priority = info.getPriority();
7539            res.preferredOrder = provider.owner.mPreferredOrder;
7540            res.match = match;
7541            res.isDefault = info.hasDefault;
7542            res.labelRes = info.labelRes;
7543            res.nonLocalizedLabel = info.nonLocalizedLabel;
7544            res.icon = info.icon;
7545            res.system = isSystemApp(res.providerInfo.applicationInfo);
7546            return res;
7547        }
7548
7549        @Override
7550        protected void sortResults(List<ResolveInfo> results) {
7551            Collections.sort(results, mResolvePrioritySorter);
7552        }
7553
7554        @Override
7555        protected void dumpFilter(PrintWriter out, String prefix,
7556                PackageParser.ProviderIntentInfo filter) {
7557            out.print(prefix);
7558            out.print(
7559                    Integer.toHexString(System.identityHashCode(filter.provider)));
7560            out.print(' ');
7561            filter.provider.printComponentShortName(out);
7562            out.print(" filter ");
7563            out.println(Integer.toHexString(System.identityHashCode(filter)));
7564        }
7565
7566        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7567                = new HashMap<ComponentName, PackageParser.Provider>();
7568        private int mFlags;
7569    };
7570
7571    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7572            new Comparator<ResolveInfo>() {
7573        public int compare(ResolveInfo r1, ResolveInfo r2) {
7574            int v1 = r1.priority;
7575            int v2 = r2.priority;
7576            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7577            if (v1 != v2) {
7578                return (v1 > v2) ? -1 : 1;
7579            }
7580            v1 = r1.preferredOrder;
7581            v2 = r2.preferredOrder;
7582            if (v1 != v2) {
7583                return (v1 > v2) ? -1 : 1;
7584            }
7585            if (r1.isDefault != r2.isDefault) {
7586                return r1.isDefault ? -1 : 1;
7587            }
7588            v1 = r1.match;
7589            v2 = r2.match;
7590            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7591            if (v1 != v2) {
7592                return (v1 > v2) ? -1 : 1;
7593            }
7594            if (r1.system != r2.system) {
7595                return r1.system ? -1 : 1;
7596            }
7597            return 0;
7598        }
7599    };
7600
7601    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7602            new Comparator<ProviderInfo>() {
7603        public int compare(ProviderInfo p1, ProviderInfo p2) {
7604            final int v1 = p1.initOrder;
7605            final int v2 = p2.initOrder;
7606            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7607        }
7608    };
7609
7610    static final void sendPackageBroadcast(String action, String pkg,
7611            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7612            int[] userIds) {
7613        IActivityManager am = ActivityManagerNative.getDefault();
7614        if (am != null) {
7615            try {
7616                if (userIds == null) {
7617                    userIds = am.getRunningUserIds();
7618                }
7619                for (int id : userIds) {
7620                    final Intent intent = new Intent(action,
7621                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7622                    if (extras != null) {
7623                        intent.putExtras(extras);
7624                    }
7625                    if (targetPkg != null) {
7626                        intent.setPackage(targetPkg);
7627                    }
7628                    // Modify the UID when posting to other users
7629                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7630                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7631                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7632                        intent.putExtra(Intent.EXTRA_UID, uid);
7633                    }
7634                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7635                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7636                    if (DEBUG_BROADCASTS) {
7637                        RuntimeException here = new RuntimeException("here");
7638                        here.fillInStackTrace();
7639                        Slog.d(TAG, "Sending to user " + id + ": "
7640                                + intent.toShortString(false, true, false, false)
7641                                + " " + intent.getExtras(), here);
7642                    }
7643                    am.broadcastIntent(null, intent, null, finishedReceiver,
7644                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7645                            finishedReceiver != null, false, id);
7646                }
7647            } catch (RemoteException ex) {
7648            }
7649        }
7650    }
7651
7652    /**
7653     * Check if the external storage media is available. This is true if there
7654     * is a mounted external storage medium or if the external storage is
7655     * emulated.
7656     */
7657    private boolean isExternalMediaAvailable() {
7658        return mMediaMounted || Environment.isExternalStorageEmulated();
7659    }
7660
7661    @Override
7662    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7663        // writer
7664        synchronized (mPackages) {
7665            if (!isExternalMediaAvailable()) {
7666                // If the external storage is no longer mounted at this point,
7667                // the caller may not have been able to delete all of this
7668                // packages files and can not delete any more.  Bail.
7669                return null;
7670            }
7671            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7672            if (lastPackage != null) {
7673                pkgs.remove(lastPackage);
7674            }
7675            if (pkgs.size() > 0) {
7676                return pkgs.get(0);
7677            }
7678        }
7679        return null;
7680    }
7681
7682    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7683        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7684                userId, andCode ? 1 : 0, packageName);
7685        if (mSystemReady) {
7686            msg.sendToTarget();
7687        } else {
7688            if (mPostSystemReadyMessages == null) {
7689                mPostSystemReadyMessages = new ArrayList<>();
7690            }
7691            mPostSystemReadyMessages.add(msg);
7692        }
7693    }
7694
7695    void startCleaningPackages() {
7696        // reader
7697        synchronized (mPackages) {
7698            if (!isExternalMediaAvailable()) {
7699                return;
7700            }
7701            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7702                return;
7703            }
7704        }
7705        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7706        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7707        IActivityManager am = ActivityManagerNative.getDefault();
7708        if (am != null) {
7709            try {
7710                am.startService(null, intent, null, UserHandle.USER_OWNER);
7711            } catch (RemoteException e) {
7712            }
7713        }
7714    }
7715
7716    @Override
7717    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7718            int installFlags, String installerPackageName, VerificationParams verificationParams,
7719            String packageAbiOverride) {
7720        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7721                packageAbiOverride, UserHandle.getCallingUserId());
7722    }
7723
7724    @Override
7725    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7726            int installFlags, String installerPackageName, VerificationParams verificationParams,
7727            String packageAbiOverride, int userId) {
7728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7729                null);
7730        if (UserHandle.getCallingUserId() != userId) {
7731            mContext.enforceCallingOrSelfPermission(
7732                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7733                    "installPackage " + userId);
7734        }
7735
7736        final File originFile = new File(originPath);
7737        final int uid = Binder.getCallingUid();
7738        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7739            try {
7740                if (observer != null) {
7741                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7742                }
7743            } catch (RemoteException re) {
7744            }
7745            return;
7746        }
7747
7748        UserHandle user;
7749        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7750            user = UserHandle.ALL;
7751        } else {
7752            user = new UserHandle(userId);
7753        }
7754
7755        final int filteredInstallFlags;
7756        if (uid == Process.SHELL_UID || uid == 0) {
7757            if (DEBUG_INSTALL) {
7758                Slog.v(TAG, "Install from ADB");
7759            }
7760            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7761        } else {
7762            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7763        }
7764
7765        verificationParams.setInstallerUid(uid);
7766
7767        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7768
7769        final Message msg = mHandler.obtainMessage(INIT_COPY);
7770        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7771                installerPackageName, verificationParams, user, packageAbiOverride);
7772        mHandler.sendMessage(msg);
7773    }
7774
7775    void installStage(String packageName, File stagedDir, String stagedCid,
7776            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7777            String installerPackageName, int installerUid, UserHandle user) {
7778        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7779                params.referrerUri, installerUid, null);
7780
7781        final OriginInfo origin;
7782        if (stagedDir != null) {
7783            origin = OriginInfo.fromStagedFile(stagedDir);
7784        } else {
7785            origin = OriginInfo.fromStagedContainer(stagedCid);
7786        }
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        msg.obj = new InstallParams(origin, observer, params.installFlags,
7790                installerPackageName, verifParams, user, params.abiOverride);
7791        mHandler.sendMessage(msg);
7792    }
7793
7794    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7795        Bundle extras = new Bundle(1);
7796        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7797
7798        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7799                packageName, extras, null, null, new int[] {userId});
7800        try {
7801            IActivityManager am = ActivityManagerNative.getDefault();
7802            final boolean isSystem =
7803                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7804            if (isSystem && am.isUserRunning(userId, false)) {
7805                // The just-installed/enabled app is bundled on the system, so presumed
7806                // to be able to run automatically without needing an explicit launch.
7807                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7808                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7809                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7810                        .setPackage(packageName);
7811                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7812                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7813            }
7814        } catch (RemoteException e) {
7815            // shouldn't happen
7816            Slog.w(TAG, "Unable to bootstrap installed package", e);
7817        }
7818    }
7819
7820    @Override
7821    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7822            int userId) {
7823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7824        PackageSetting pkgSetting;
7825        final int uid = Binder.getCallingUid();
7826        if (UserHandle.getUserId(uid) != userId) {
7827            mContext.enforceCallingOrSelfPermission(
7828                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7829                    "setApplicationHiddenSetting for user " + userId);
7830        }
7831
7832        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7833            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7834            return false;
7835        }
7836
7837        long callingId = Binder.clearCallingIdentity();
7838        try {
7839            boolean sendAdded = false;
7840            boolean sendRemoved = false;
7841            // writer
7842            synchronized (mPackages) {
7843                pkgSetting = mSettings.mPackages.get(packageName);
7844                if (pkgSetting == null) {
7845                    return false;
7846                }
7847                if (pkgSetting.getHidden(userId) != hidden) {
7848                    pkgSetting.setHidden(hidden, userId);
7849                    mSettings.writePackageRestrictionsLPr(userId);
7850                    if (hidden) {
7851                        sendRemoved = true;
7852                    } else {
7853                        sendAdded = true;
7854                    }
7855                }
7856            }
7857            if (sendAdded) {
7858                sendPackageAddedForUser(packageName, pkgSetting, userId);
7859                return true;
7860            }
7861            if (sendRemoved) {
7862                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7863                        "hiding pkg");
7864                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7865            }
7866        } finally {
7867            Binder.restoreCallingIdentity(callingId);
7868        }
7869        return false;
7870    }
7871
7872    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7873            int userId) {
7874        final PackageRemovedInfo info = new PackageRemovedInfo();
7875        info.removedPackage = packageName;
7876        info.removedUsers = new int[] {userId};
7877        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7878        info.sendBroadcast(false, false, false);
7879    }
7880
7881    /**
7882     * Returns true if application is not found or there was an error. Otherwise it returns
7883     * the hidden state of the package for the given user.
7884     */
7885    @Override
7886    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7888        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7889                "getApplicationHidden for user " + userId);
7890        PackageSetting pkgSetting;
7891        long callingId = Binder.clearCallingIdentity();
7892        try {
7893            // writer
7894            synchronized (mPackages) {
7895                pkgSetting = mSettings.mPackages.get(packageName);
7896                if (pkgSetting == null) {
7897                    return true;
7898                }
7899                return pkgSetting.getHidden(userId);
7900            }
7901        } finally {
7902            Binder.restoreCallingIdentity(callingId);
7903        }
7904    }
7905
7906    /**
7907     * @hide
7908     */
7909    @Override
7910    public int installExistingPackageAsUser(String packageName, int userId) {
7911        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7912                null);
7913        PackageSetting pkgSetting;
7914        final int uid = Binder.getCallingUid();
7915        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7916        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7917            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7918        }
7919
7920        long callingId = Binder.clearCallingIdentity();
7921        try {
7922            boolean sendAdded = false;
7923            Bundle extras = new Bundle(1);
7924
7925            // writer
7926            synchronized (mPackages) {
7927                pkgSetting = mSettings.mPackages.get(packageName);
7928                if (pkgSetting == null) {
7929                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7930                }
7931                if (!pkgSetting.getInstalled(userId)) {
7932                    pkgSetting.setInstalled(true, userId);
7933                    pkgSetting.setHidden(false, userId);
7934                    mSettings.writePackageRestrictionsLPr(userId);
7935                    sendAdded = true;
7936                }
7937            }
7938
7939            if (sendAdded) {
7940                sendPackageAddedForUser(packageName, pkgSetting, userId);
7941            }
7942        } finally {
7943            Binder.restoreCallingIdentity(callingId);
7944        }
7945
7946        return PackageManager.INSTALL_SUCCEEDED;
7947    }
7948
7949    boolean isUserRestricted(int userId, String restrictionKey) {
7950        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7951        if (restrictions.getBoolean(restrictionKey, false)) {
7952            Log.w(TAG, "User is restricted: " + restrictionKey);
7953            return true;
7954        }
7955        return false;
7956    }
7957
7958    @Override
7959    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7960        mContext.enforceCallingOrSelfPermission(
7961                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7962                "Only package verification agents can verify applications");
7963
7964        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7965        final PackageVerificationResponse response = new PackageVerificationResponse(
7966                verificationCode, Binder.getCallingUid());
7967        msg.arg1 = id;
7968        msg.obj = response;
7969        mHandler.sendMessage(msg);
7970    }
7971
7972    @Override
7973    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7974            long millisecondsToDelay) {
7975        mContext.enforceCallingOrSelfPermission(
7976                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7977                "Only package verification agents can extend verification timeouts");
7978
7979        final PackageVerificationState state = mPendingVerification.get(id);
7980        final PackageVerificationResponse response = new PackageVerificationResponse(
7981                verificationCodeAtTimeout, Binder.getCallingUid());
7982
7983        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7984            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7985        }
7986        if (millisecondsToDelay < 0) {
7987            millisecondsToDelay = 0;
7988        }
7989        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7990                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7991            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7992        }
7993
7994        if ((state != null) && !state.timeoutExtended()) {
7995            state.extendTimeout();
7996
7997            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7998            msg.arg1 = id;
7999            msg.obj = response;
8000            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8001        }
8002    }
8003
8004    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8005            int verificationCode, UserHandle user) {
8006        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8007        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8008        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8009        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8010        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8011
8012        mContext.sendBroadcastAsUser(intent, user,
8013                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8014    }
8015
8016    private ComponentName matchComponentForVerifier(String packageName,
8017            List<ResolveInfo> receivers) {
8018        ActivityInfo targetReceiver = null;
8019
8020        final int NR = receivers.size();
8021        for (int i = 0; i < NR; i++) {
8022            final ResolveInfo info = receivers.get(i);
8023            if (info.activityInfo == null) {
8024                continue;
8025            }
8026
8027            if (packageName.equals(info.activityInfo.packageName)) {
8028                targetReceiver = info.activityInfo;
8029                break;
8030            }
8031        }
8032
8033        if (targetReceiver == null) {
8034            return null;
8035        }
8036
8037        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8038    }
8039
8040    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8041            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8042        if (pkgInfo.verifiers.length == 0) {
8043            return null;
8044        }
8045
8046        final int N = pkgInfo.verifiers.length;
8047        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8048        for (int i = 0; i < N; i++) {
8049            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8050
8051            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8052                    receivers);
8053            if (comp == null) {
8054                continue;
8055            }
8056
8057            final int verifierUid = getUidForVerifier(verifierInfo);
8058            if (verifierUid == -1) {
8059                continue;
8060            }
8061
8062            if (DEBUG_VERIFY) {
8063                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8064                        + " with the correct signature");
8065            }
8066            sufficientVerifiers.add(comp);
8067            verificationState.addSufficientVerifier(verifierUid);
8068        }
8069
8070        return sufficientVerifiers;
8071    }
8072
8073    private int getUidForVerifier(VerifierInfo verifierInfo) {
8074        synchronized (mPackages) {
8075            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8076            if (pkg == null) {
8077                return -1;
8078            } else if (pkg.mSignatures.length != 1) {
8079                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8080                        + " has more than one signature; ignoring");
8081                return -1;
8082            }
8083
8084            /*
8085             * If the public key of the package's signature does not match
8086             * our expected public key, then this is a different package and
8087             * we should skip.
8088             */
8089
8090            final byte[] expectedPublicKey;
8091            try {
8092                final Signature verifierSig = pkg.mSignatures[0];
8093                final PublicKey publicKey = verifierSig.getPublicKey();
8094                expectedPublicKey = publicKey.getEncoded();
8095            } catch (CertificateException e) {
8096                return -1;
8097            }
8098
8099            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8100
8101            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8102                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8103                        + " does not have the expected public key; ignoring");
8104                return -1;
8105            }
8106
8107            return pkg.applicationInfo.uid;
8108        }
8109    }
8110
8111    @Override
8112    public void finishPackageInstall(int token) {
8113        enforceSystemOrRoot("Only the system is allowed to finish installs");
8114
8115        if (DEBUG_INSTALL) {
8116            Slog.v(TAG, "BM finishing package install for " + token);
8117        }
8118
8119        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8120        mHandler.sendMessage(msg);
8121    }
8122
8123    /**
8124     * Get the verification agent timeout.
8125     *
8126     * @return verification timeout in milliseconds
8127     */
8128    private long getVerificationTimeout() {
8129        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8130                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8131                DEFAULT_VERIFICATION_TIMEOUT);
8132    }
8133
8134    /**
8135     * Get the default verification agent response code.
8136     *
8137     * @return default verification response code
8138     */
8139    private int getDefaultVerificationResponse() {
8140        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8141                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8142                DEFAULT_VERIFICATION_RESPONSE);
8143    }
8144
8145    /**
8146     * Check whether or not package verification has been enabled.
8147     *
8148     * @return true if verification should be performed
8149     */
8150    private boolean isVerificationEnabled(int userId, int installFlags) {
8151        if (!DEFAULT_VERIFY_ENABLE) {
8152            return false;
8153        }
8154
8155        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8156
8157        // Check if installing from ADB
8158        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8159            // Do not run verification in a test harness environment
8160            if (ActivityManager.isRunningInTestHarness()) {
8161                return false;
8162            }
8163            if (ensureVerifyAppsEnabled) {
8164                return true;
8165            }
8166            // Check if the developer does not want package verification for ADB installs
8167            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8168                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8169                return false;
8170            }
8171        }
8172
8173        if (ensureVerifyAppsEnabled) {
8174            return true;
8175        }
8176
8177        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8178                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8179    }
8180
8181    /**
8182     * Get the "allow unknown sources" setting.
8183     *
8184     * @return the current "allow unknown sources" setting
8185     */
8186    private int getUnknownSourcesSettings() {
8187        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8188                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8189                -1);
8190    }
8191
8192    @Override
8193    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8194        final int uid = Binder.getCallingUid();
8195        // writer
8196        synchronized (mPackages) {
8197            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8198            if (targetPackageSetting == null) {
8199                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8200            }
8201
8202            PackageSetting installerPackageSetting;
8203            if (installerPackageName != null) {
8204                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8205                if (installerPackageSetting == null) {
8206                    throw new IllegalArgumentException("Unknown installer package: "
8207                            + installerPackageName);
8208                }
8209            } else {
8210                installerPackageSetting = null;
8211            }
8212
8213            Signature[] callerSignature;
8214            Object obj = mSettings.getUserIdLPr(uid);
8215            if (obj != null) {
8216                if (obj instanceof SharedUserSetting) {
8217                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8218                } else if (obj instanceof PackageSetting) {
8219                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8220                } else {
8221                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8222                }
8223            } else {
8224                throw new SecurityException("Unknown calling uid " + uid);
8225            }
8226
8227            // Verify: can't set installerPackageName to a package that is
8228            // not signed with the same cert as the caller.
8229            if (installerPackageSetting != null) {
8230                if (compareSignatures(callerSignature,
8231                        installerPackageSetting.signatures.mSignatures)
8232                        != PackageManager.SIGNATURE_MATCH) {
8233                    throw new SecurityException(
8234                            "Caller does not have same cert as new installer package "
8235                            + installerPackageName);
8236                }
8237            }
8238
8239            // Verify: if target already has an installer package, it must
8240            // be signed with the same cert as the caller.
8241            if (targetPackageSetting.installerPackageName != null) {
8242                PackageSetting setting = mSettings.mPackages.get(
8243                        targetPackageSetting.installerPackageName);
8244                // If the currently set package isn't valid, then it's always
8245                // okay to change it.
8246                if (setting != null) {
8247                    if (compareSignatures(callerSignature,
8248                            setting.signatures.mSignatures)
8249                            != PackageManager.SIGNATURE_MATCH) {
8250                        throw new SecurityException(
8251                                "Caller does not have same cert as old installer package "
8252                                + targetPackageSetting.installerPackageName);
8253                    }
8254                }
8255            }
8256
8257            // Okay!
8258            targetPackageSetting.installerPackageName = installerPackageName;
8259            scheduleWriteSettingsLocked();
8260        }
8261    }
8262
8263    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8264        // Queue up an async operation since the package installation may take a little while.
8265        mHandler.post(new Runnable() {
8266            public void run() {
8267                mHandler.removeCallbacks(this);
8268                 // Result object to be returned
8269                PackageInstalledInfo res = new PackageInstalledInfo();
8270                res.returnCode = currentStatus;
8271                res.uid = -1;
8272                res.pkg = null;
8273                res.removedInfo = new PackageRemovedInfo();
8274                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8275                    args.doPreInstall(res.returnCode);
8276                    synchronized (mInstallLock) {
8277                        installPackageLI(args, res);
8278                    }
8279                    args.doPostInstall(res.returnCode, res.uid);
8280                }
8281
8282                // A restore should be performed at this point if (a) the install
8283                // succeeded, (b) the operation is not an update, and (c) the new
8284                // package has not opted out of backup participation.
8285                final boolean update = res.removedInfo.removedPackage != null;
8286                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8287                boolean doRestore = !update
8288                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8289
8290                // Set up the post-install work request bookkeeping.  This will be used
8291                // and cleaned up by the post-install event handling regardless of whether
8292                // there's a restore pass performed.  Token values are >= 1.
8293                int token;
8294                if (mNextInstallToken < 0) mNextInstallToken = 1;
8295                token = mNextInstallToken++;
8296
8297                PostInstallData data = new PostInstallData(args, res);
8298                mRunningInstalls.put(token, data);
8299                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8300
8301                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8302                    // Pass responsibility to the Backup Manager.  It will perform a
8303                    // restore if appropriate, then pass responsibility back to the
8304                    // Package Manager to run the post-install observer callbacks
8305                    // and broadcasts.
8306                    IBackupManager bm = IBackupManager.Stub.asInterface(
8307                            ServiceManager.getService(Context.BACKUP_SERVICE));
8308                    if (bm != null) {
8309                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8310                                + " to BM for possible restore");
8311                        try {
8312                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8313                        } catch (RemoteException e) {
8314                            // can't happen; the backup manager is local
8315                        } catch (Exception e) {
8316                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8317                            doRestore = false;
8318                        }
8319                    } else {
8320                        Slog.e(TAG, "Backup Manager not found!");
8321                        doRestore = false;
8322                    }
8323                }
8324
8325                if (!doRestore) {
8326                    // No restore possible, or the Backup Manager was mysteriously not
8327                    // available -- just fire the post-install work request directly.
8328                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8329                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8330                    mHandler.sendMessage(msg);
8331                }
8332            }
8333        });
8334    }
8335
8336    private abstract class HandlerParams {
8337        private static final int MAX_RETRIES = 4;
8338
8339        /**
8340         * Number of times startCopy() has been attempted and had a non-fatal
8341         * error.
8342         */
8343        private int mRetries = 0;
8344
8345        /** User handle for the user requesting the information or installation. */
8346        private final UserHandle mUser;
8347
8348        HandlerParams(UserHandle user) {
8349            mUser = user;
8350        }
8351
8352        UserHandle getUser() {
8353            return mUser;
8354        }
8355
8356        final boolean startCopy() {
8357            boolean res;
8358            try {
8359                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8360
8361                if (++mRetries > MAX_RETRIES) {
8362                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8363                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8364                    handleServiceError();
8365                    return false;
8366                } else {
8367                    handleStartCopy();
8368                    res = true;
8369                }
8370            } catch (RemoteException e) {
8371                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8372                mHandler.sendEmptyMessage(MCS_RECONNECT);
8373                res = false;
8374            }
8375            handleReturnCode();
8376            return res;
8377        }
8378
8379        final void serviceError() {
8380            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8381            handleServiceError();
8382            handleReturnCode();
8383        }
8384
8385        abstract void handleStartCopy() throws RemoteException;
8386        abstract void handleServiceError();
8387        abstract void handleReturnCode();
8388    }
8389
8390    class MeasureParams extends HandlerParams {
8391        private final PackageStats mStats;
8392        private boolean mSuccess;
8393
8394        private final IPackageStatsObserver mObserver;
8395
8396        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8397            super(new UserHandle(stats.userHandle));
8398            mObserver = observer;
8399            mStats = stats;
8400        }
8401
8402        @Override
8403        public String toString() {
8404            return "MeasureParams{"
8405                + Integer.toHexString(System.identityHashCode(this))
8406                + " " + mStats.packageName + "}";
8407        }
8408
8409        @Override
8410        void handleStartCopy() throws RemoteException {
8411            synchronized (mInstallLock) {
8412                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8413            }
8414
8415            if (mSuccess) {
8416                final boolean mounted;
8417                if (Environment.isExternalStorageEmulated()) {
8418                    mounted = true;
8419                } else {
8420                    final String status = Environment.getExternalStorageState();
8421                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8422                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8423                }
8424
8425                if (mounted) {
8426                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8427
8428                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8429                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8430
8431                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8432                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8433
8434                    // Always subtract cache size, since it's a subdirectory
8435                    mStats.externalDataSize -= mStats.externalCacheSize;
8436
8437                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8438                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8439
8440                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8441                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8442                }
8443            }
8444        }
8445
8446        @Override
8447        void handleReturnCode() {
8448            if (mObserver != null) {
8449                try {
8450                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8451                } catch (RemoteException e) {
8452                    Slog.i(TAG, "Observer no longer exists.");
8453                }
8454            }
8455        }
8456
8457        @Override
8458        void handleServiceError() {
8459            Slog.e(TAG, "Could not measure application " + mStats.packageName
8460                            + " external storage");
8461        }
8462    }
8463
8464    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8465            throws RemoteException {
8466        long result = 0;
8467        for (File path : paths) {
8468            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8469        }
8470        return result;
8471    }
8472
8473    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8474        for (File path : paths) {
8475            try {
8476                mcs.clearDirectory(path.getAbsolutePath());
8477            } catch (RemoteException e) {
8478            }
8479        }
8480    }
8481
8482    static class OriginInfo {
8483        /**
8484         * Location where install is coming from, before it has been
8485         * copied/renamed into place. This could be a single monolithic APK
8486         * file, or a cluster directory. This location may be untrusted.
8487         */
8488        final File file;
8489        final String cid;
8490
8491        /**
8492         * Flag indicating that {@link #file} or {@link #cid} has already been
8493         * staged, meaning downstream users don't need to defensively copy the
8494         * contents.
8495         */
8496        final boolean staged;
8497
8498        /**
8499         * Flag indicating that {@link #file} or {@link #cid} is an already
8500         * installed app that is being moved.
8501         */
8502        final boolean existing;
8503
8504        final String resolvedPath;
8505        final File resolvedFile;
8506
8507        static OriginInfo fromNothing() {
8508            return new OriginInfo(null, null, false, false);
8509        }
8510
8511        static OriginInfo fromUntrustedFile(File file) {
8512            return new OriginInfo(file, null, false, false);
8513        }
8514
8515        static OriginInfo fromExistingFile(File file) {
8516            return new OriginInfo(file, null, false, true);
8517        }
8518
8519        static OriginInfo fromStagedFile(File file) {
8520            return new OriginInfo(file, null, true, false);
8521        }
8522
8523        static OriginInfo fromStagedContainer(String cid) {
8524            return new OriginInfo(null, cid, true, false);
8525        }
8526
8527        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8528            this.file = file;
8529            this.cid = cid;
8530            this.staged = staged;
8531            this.existing = existing;
8532
8533            if (cid != null) {
8534                resolvedPath = PackageHelper.getSdDir(cid);
8535                resolvedFile = new File(resolvedPath);
8536            } else if (file != null) {
8537                resolvedPath = file.getAbsolutePath();
8538                resolvedFile = file;
8539            } else {
8540                resolvedPath = null;
8541                resolvedFile = null;
8542            }
8543        }
8544    }
8545
8546    class InstallParams extends HandlerParams {
8547        final OriginInfo origin;
8548        final IPackageInstallObserver2 observer;
8549        int installFlags;
8550        final String installerPackageName;
8551        final VerificationParams verificationParams;
8552        private InstallArgs mArgs;
8553        private int mRet;
8554        final String packageAbiOverride;
8555
8556        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8557                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8558                String packageAbiOverride) {
8559            super(user);
8560            this.origin = origin;
8561            this.observer = observer;
8562            this.installFlags = installFlags;
8563            this.installerPackageName = installerPackageName;
8564            this.verificationParams = verificationParams;
8565            this.packageAbiOverride = packageAbiOverride;
8566        }
8567
8568        @Override
8569        public String toString() {
8570            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8571                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8572        }
8573
8574        public ManifestDigest getManifestDigest() {
8575            if (verificationParams == null) {
8576                return null;
8577            }
8578            return verificationParams.getManifestDigest();
8579        }
8580
8581        private int installLocationPolicy(PackageInfoLite pkgLite) {
8582            String packageName = pkgLite.packageName;
8583            int installLocation = pkgLite.installLocation;
8584            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8585            // reader
8586            synchronized (mPackages) {
8587                PackageParser.Package pkg = mPackages.get(packageName);
8588                if (pkg != null) {
8589                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8590                        // Check for downgrading.
8591                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8592                            if (pkgLite.versionCode < pkg.mVersionCode) {
8593                                Slog.w(TAG, "Can't install update of " + packageName
8594                                        + " update version " + pkgLite.versionCode
8595                                        + " is older than installed version "
8596                                        + pkg.mVersionCode);
8597                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8598                            }
8599                        }
8600                        // Check for updated system application.
8601                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8602                            if (onSd) {
8603                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8604                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8605                            }
8606                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8607                        } else {
8608                            if (onSd) {
8609                                // Install flag overrides everything.
8610                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8611                            }
8612                            // If current upgrade specifies particular preference
8613                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8614                                // Application explicitly specified internal.
8615                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8616                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8617                                // App explictly prefers external. Let policy decide
8618                            } else {
8619                                // Prefer previous location
8620                                if (isExternal(pkg)) {
8621                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8622                                }
8623                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8624                            }
8625                        }
8626                    } else {
8627                        // Invalid install. Return error code
8628                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8629                    }
8630                }
8631            }
8632            // All the special cases have been taken care of.
8633            // Return result based on recommended install location.
8634            if (onSd) {
8635                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8636            }
8637            return pkgLite.recommendedInstallLocation;
8638        }
8639
8640        /*
8641         * Invoke remote method to get package information and install
8642         * location values. Override install location based on default
8643         * policy if needed and then create install arguments based
8644         * on the install location.
8645         */
8646        public void handleStartCopy() throws RemoteException {
8647            int ret = PackageManager.INSTALL_SUCCEEDED;
8648
8649            // If we're already staged, we've firmly committed to an install location
8650            if (origin.staged) {
8651                if (origin.file != null) {
8652                    installFlags |= PackageManager.INSTALL_INTERNAL;
8653                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8654                } else if (origin.cid != null) {
8655                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8656                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8657                } else {
8658                    throw new IllegalStateException("Invalid stage location");
8659                }
8660            }
8661
8662            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8663            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8664
8665            PackageInfoLite pkgLite = null;
8666
8667            if (onInt && onSd) {
8668                // Check if both bits are set.
8669                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8670                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8671            } else {
8672                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8673                        packageAbiOverride);
8674
8675                /*
8676                 * If we have too little free space, try to free cache
8677                 * before giving up.
8678                 */
8679                if (!origin.staged && pkgLite.recommendedInstallLocation
8680                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8681                    // TODO: focus freeing disk space on the target device
8682                    final StorageManager storage = StorageManager.from(mContext);
8683                    final long lowThreshold = storage.getStorageLowBytes(
8684                            Environment.getDataDirectory());
8685
8686                    final long sizeBytes = mContainerService.calculateInstalledSize(
8687                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8688
8689                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8690                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8691                                installFlags, packageAbiOverride);
8692                    }
8693
8694                    /*
8695                     * The cache free must have deleted the file we
8696                     * downloaded to install.
8697                     *
8698                     * TODO: fix the "freeCache" call to not delete
8699                     *       the file we care about.
8700                     */
8701                    if (pkgLite.recommendedInstallLocation
8702                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8703                        pkgLite.recommendedInstallLocation
8704                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8705                    }
8706                }
8707            }
8708
8709            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8710                int loc = pkgLite.recommendedInstallLocation;
8711                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8712                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8713                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8714                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8715                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8716                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8717                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8718                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8719                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8720                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8721                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8722                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8723                } else {
8724                    // Override with defaults if needed.
8725                    loc = installLocationPolicy(pkgLite);
8726                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8727                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8728                    } else if (!onSd && !onInt) {
8729                        // Override install location with flags
8730                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8731                            // Set the flag to install on external media.
8732                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8733                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8734                        } else {
8735                            // Make sure the flag for installing on external
8736                            // media is unset
8737                            installFlags |= PackageManager.INSTALL_INTERNAL;
8738                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8739                        }
8740                    }
8741                }
8742            }
8743
8744            final InstallArgs args = createInstallArgs(this);
8745            mArgs = args;
8746
8747            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8748                 /*
8749                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8750                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8751                 */
8752                int userIdentifier = getUser().getIdentifier();
8753                if (userIdentifier == UserHandle.USER_ALL
8754                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8755                    userIdentifier = UserHandle.USER_OWNER;
8756                }
8757
8758                /*
8759                 * Determine if we have any installed package verifiers. If we
8760                 * do, then we'll defer to them to verify the packages.
8761                 */
8762                final int requiredUid = mRequiredVerifierPackage == null ? -1
8763                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8764                if (!origin.existing && requiredUid != -1
8765                        && isVerificationEnabled(userIdentifier, installFlags)) {
8766                    final Intent verification = new Intent(
8767                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8768                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8769                            PACKAGE_MIME_TYPE);
8770                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8771
8772                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8773                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8774                            0 /* TODO: Which userId? */);
8775
8776                    if (DEBUG_VERIFY) {
8777                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8778                                + verification.toString() + " with " + pkgLite.verifiers.length
8779                                + " optional verifiers");
8780                    }
8781
8782                    final int verificationId = mPendingVerificationToken++;
8783
8784                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8785
8786                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8787                            installerPackageName);
8788
8789                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8790                            installFlags);
8791
8792                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8793                            pkgLite.packageName);
8794
8795                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8796                            pkgLite.versionCode);
8797
8798                    if (verificationParams != null) {
8799                        if (verificationParams.getVerificationURI() != null) {
8800                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8801                                 verificationParams.getVerificationURI());
8802                        }
8803                        if (verificationParams.getOriginatingURI() != null) {
8804                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8805                                  verificationParams.getOriginatingURI());
8806                        }
8807                        if (verificationParams.getReferrer() != null) {
8808                            verification.putExtra(Intent.EXTRA_REFERRER,
8809                                  verificationParams.getReferrer());
8810                        }
8811                        if (verificationParams.getOriginatingUid() >= 0) {
8812                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8813                                  verificationParams.getOriginatingUid());
8814                        }
8815                        if (verificationParams.getInstallerUid() >= 0) {
8816                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8817                                  verificationParams.getInstallerUid());
8818                        }
8819                    }
8820
8821                    final PackageVerificationState verificationState = new PackageVerificationState(
8822                            requiredUid, args);
8823
8824                    mPendingVerification.append(verificationId, verificationState);
8825
8826                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8827                            receivers, verificationState);
8828
8829                    /*
8830                     * If any sufficient verifiers were listed in the package
8831                     * manifest, attempt to ask them.
8832                     */
8833                    if (sufficientVerifiers != null) {
8834                        final int N = sufficientVerifiers.size();
8835                        if (N == 0) {
8836                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8837                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8838                        } else {
8839                            for (int i = 0; i < N; i++) {
8840                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8841
8842                                final Intent sufficientIntent = new Intent(verification);
8843                                sufficientIntent.setComponent(verifierComponent);
8844
8845                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8846                            }
8847                        }
8848                    }
8849
8850                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8851                            mRequiredVerifierPackage, receivers);
8852                    if (ret == PackageManager.INSTALL_SUCCEEDED
8853                            && mRequiredVerifierPackage != null) {
8854                        /*
8855                         * Send the intent to the required verification agent,
8856                         * but only start the verification timeout after the
8857                         * target BroadcastReceivers have run.
8858                         */
8859                        verification.setComponent(requiredVerifierComponent);
8860                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8861                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8862                                new BroadcastReceiver() {
8863                                    @Override
8864                                    public void onReceive(Context context, Intent intent) {
8865                                        final Message msg = mHandler
8866                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8867                                        msg.arg1 = verificationId;
8868                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8869                                    }
8870                                }, null, 0, null, null);
8871
8872                        /*
8873                         * We don't want the copy to proceed until verification
8874                         * succeeds, so null out this field.
8875                         */
8876                        mArgs = null;
8877                    }
8878                } else {
8879                    /*
8880                     * No package verification is enabled, so immediately start
8881                     * the remote call to initiate copy using temporary file.
8882                     */
8883                    ret = args.copyApk(mContainerService, true);
8884                }
8885            }
8886
8887            mRet = ret;
8888        }
8889
8890        @Override
8891        void handleReturnCode() {
8892            // If mArgs is null, then MCS couldn't be reached. When it
8893            // reconnects, it will try again to install. At that point, this
8894            // will succeed.
8895            if (mArgs != null) {
8896                processPendingInstall(mArgs, mRet);
8897            }
8898        }
8899
8900        @Override
8901        void handleServiceError() {
8902            mArgs = createInstallArgs(this);
8903            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8904        }
8905
8906        public boolean isForwardLocked() {
8907            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8908        }
8909    }
8910
8911    /**
8912     * Used during creation of InstallArgs
8913     *
8914     * @param installFlags package installation flags
8915     * @return true if should be installed on external storage
8916     */
8917    private static boolean installOnSd(int installFlags) {
8918        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8919            return false;
8920        }
8921        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8922            return true;
8923        }
8924        return false;
8925    }
8926
8927    /**
8928     * Used during creation of InstallArgs
8929     *
8930     * @param installFlags package installation flags
8931     * @return true if should be installed as forward locked
8932     */
8933    private static boolean installForwardLocked(int installFlags) {
8934        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8935    }
8936
8937    private InstallArgs createInstallArgs(InstallParams params) {
8938        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8939            return new AsecInstallArgs(params);
8940        } else {
8941            return new FileInstallArgs(params);
8942        }
8943    }
8944
8945    /**
8946     * Create args that describe an existing installed package. Typically used
8947     * when cleaning up old installs, or used as a move source.
8948     */
8949    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8950            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8951        final boolean isInAsec;
8952        if (installOnSd(installFlags)) {
8953            /* Apps on SD card are always in ASEC containers. */
8954            isInAsec = true;
8955        } else if (installForwardLocked(installFlags)
8956                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8957            /*
8958             * Forward-locked apps are only in ASEC containers if they're the
8959             * new style
8960             */
8961            isInAsec = true;
8962        } else {
8963            isInAsec = false;
8964        }
8965
8966        if (isInAsec) {
8967            return new AsecInstallArgs(codePath, instructionSets,
8968                    installOnSd(installFlags), installForwardLocked(installFlags));
8969        } else {
8970            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8971                    instructionSets);
8972        }
8973    }
8974
8975    static abstract class InstallArgs {
8976        /** @see InstallParams#origin */
8977        final OriginInfo origin;
8978
8979        final IPackageInstallObserver2 observer;
8980        // Always refers to PackageManager flags only
8981        final int installFlags;
8982        final String installerPackageName;
8983        final ManifestDigest manifestDigest;
8984        final UserHandle user;
8985        final String abiOverride;
8986
8987        // The list of instruction sets supported by this app. This is currently
8988        // only used during the rmdex() phase to clean up resources. We can get rid of this
8989        // if we move dex files under the common app path.
8990        /* nullable */ String[] instructionSets;
8991
8992        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8993                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8994                String[] instructionSets, String abiOverride) {
8995            this.origin = origin;
8996            this.installFlags = installFlags;
8997            this.observer = observer;
8998            this.installerPackageName = installerPackageName;
8999            this.manifestDigest = manifestDigest;
9000            this.user = user;
9001            this.instructionSets = instructionSets;
9002            this.abiOverride = abiOverride;
9003        }
9004
9005        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9006        abstract int doPreInstall(int status);
9007
9008        /**
9009         * Rename package into final resting place. All paths on the given
9010         * scanned package should be updated to reflect the rename.
9011         */
9012        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9013        abstract int doPostInstall(int status, int uid);
9014
9015        /** @see PackageSettingBase#codePathString */
9016        abstract String getCodePath();
9017        /** @see PackageSettingBase#resourcePathString */
9018        abstract String getResourcePath();
9019        abstract String getLegacyNativeLibraryPath();
9020
9021        // Need installer lock especially for dex file removal.
9022        abstract void cleanUpResourcesLI();
9023        abstract boolean doPostDeleteLI(boolean delete);
9024        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9025
9026        /**
9027         * Called before the source arguments are copied. This is used mostly
9028         * for MoveParams when it needs to read the source file to put it in the
9029         * destination.
9030         */
9031        int doPreCopy() {
9032            return PackageManager.INSTALL_SUCCEEDED;
9033        }
9034
9035        /**
9036         * Called after the source arguments are copied. This is used mostly for
9037         * MoveParams when it needs to read the source file to put it in the
9038         * destination.
9039         *
9040         * @return
9041         */
9042        int doPostCopy(int uid) {
9043            return PackageManager.INSTALL_SUCCEEDED;
9044        }
9045
9046        protected boolean isFwdLocked() {
9047            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9048        }
9049
9050        protected boolean isExternal() {
9051            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9052        }
9053
9054        UserHandle getUser() {
9055            return user;
9056        }
9057    }
9058
9059    /**
9060     * Logic to handle installation of non-ASEC applications, including copying
9061     * and renaming logic.
9062     */
9063    class FileInstallArgs extends InstallArgs {
9064        private File codeFile;
9065        private File resourceFile;
9066        private File legacyNativeLibraryPath;
9067
9068        // Example topology:
9069        // /data/app/com.example/base.apk
9070        // /data/app/com.example/split_foo.apk
9071        // /data/app/com.example/lib/arm/libfoo.so
9072        // /data/app/com.example/lib/arm64/libfoo.so
9073        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9074
9075        /** New install */
9076        FileInstallArgs(InstallParams params) {
9077            super(params.origin, params.observer, params.installFlags,
9078                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9079                    null /* instruction sets */, params.packageAbiOverride);
9080            if (isFwdLocked()) {
9081                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9082            }
9083        }
9084
9085        /** Existing install */
9086        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9087                String[] instructionSets) {
9088            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9089            this.codeFile = (codePath != null) ? new File(codePath) : null;
9090            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9091            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9092                    new File(legacyNativeLibraryPath) : null;
9093        }
9094
9095        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9096            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9097                    isFwdLocked(), abiOverride);
9098
9099            final StorageManager storage = StorageManager.from(mContext);
9100            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9101        }
9102
9103        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9104            if (origin.staged) {
9105                Slog.d(TAG, origin.file + " already staged; skipping copy");
9106                codeFile = origin.file;
9107                resourceFile = origin.file;
9108                return PackageManager.INSTALL_SUCCEEDED;
9109            }
9110
9111            try {
9112                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9113                codeFile = tempDir;
9114                resourceFile = tempDir;
9115            } catch (IOException e) {
9116                Slog.w(TAG, "Failed to create copy file: " + e);
9117                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9118            }
9119
9120            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9121                @Override
9122                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9123                    if (!FileUtils.isValidExtFilename(name)) {
9124                        throw new IllegalArgumentException("Invalid filename: " + name);
9125                    }
9126                    try {
9127                        final File file = new File(codeFile, name);
9128                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9129                                O_RDWR | O_CREAT, 0644);
9130                        Os.chmod(file.getAbsolutePath(), 0644);
9131                        return new ParcelFileDescriptor(fd);
9132                    } catch (ErrnoException e) {
9133                        throw new RemoteException("Failed to open: " + e.getMessage());
9134                    }
9135                }
9136            };
9137
9138            int ret = PackageManager.INSTALL_SUCCEEDED;
9139            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9140            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9141                Slog.e(TAG, "Failed to copy package");
9142                return ret;
9143            }
9144
9145            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9146            NativeLibraryHelper.Handle handle = null;
9147            try {
9148                handle = NativeLibraryHelper.Handle.create(codeFile);
9149                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9150                        abiOverride);
9151            } catch (IOException e) {
9152                Slog.e(TAG, "Copying native libraries failed", e);
9153                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9154            } finally {
9155                IoUtils.closeQuietly(handle);
9156            }
9157
9158            return ret;
9159        }
9160
9161        int doPreInstall(int status) {
9162            if (status != PackageManager.INSTALL_SUCCEEDED) {
9163                cleanUp();
9164            }
9165            return status;
9166        }
9167
9168        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9169            if (status != PackageManager.INSTALL_SUCCEEDED) {
9170                cleanUp();
9171                return false;
9172            } else {
9173                final File beforeCodeFile = codeFile;
9174                final File afterCodeFile = getNextCodePath(pkg.packageName);
9175
9176                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9177                try {
9178                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9179                } catch (ErrnoException e) {
9180                    Slog.d(TAG, "Failed to rename", e);
9181                    return false;
9182                }
9183
9184                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9185                    Slog.d(TAG, "Failed to restorecon");
9186                    return false;
9187                }
9188
9189                // Reflect the rename internally
9190                codeFile = afterCodeFile;
9191                resourceFile = afterCodeFile;
9192
9193                // Reflect the rename in scanned details
9194                pkg.codePath = afterCodeFile.getAbsolutePath();
9195                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9196                        pkg.baseCodePath);
9197                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9198                        pkg.splitCodePaths);
9199
9200                // Reflect the rename in app info
9201                pkg.applicationInfo.setCodePath(pkg.codePath);
9202                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9203                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9204                pkg.applicationInfo.setResourcePath(pkg.codePath);
9205                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9206                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9207
9208                return true;
9209            }
9210        }
9211
9212        int doPostInstall(int status, int uid) {
9213            if (status != PackageManager.INSTALL_SUCCEEDED) {
9214                cleanUp();
9215            }
9216            return status;
9217        }
9218
9219        @Override
9220        String getCodePath() {
9221            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9222        }
9223
9224        @Override
9225        String getResourcePath() {
9226            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9227        }
9228
9229        @Override
9230        String getLegacyNativeLibraryPath() {
9231            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9232        }
9233
9234        private boolean cleanUp() {
9235            if (codeFile == null || !codeFile.exists()) {
9236                return false;
9237            }
9238
9239            if (codeFile.isDirectory()) {
9240                FileUtils.deleteContents(codeFile);
9241            }
9242            codeFile.delete();
9243
9244            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9245                resourceFile.delete();
9246            }
9247
9248            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9249                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9250                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9251                }
9252                legacyNativeLibraryPath.delete();
9253            }
9254
9255            return true;
9256        }
9257
9258        void cleanUpResourcesLI() {
9259            // Try enumerating all code paths before deleting
9260            List<String> allCodePaths = Collections.EMPTY_LIST;
9261            if (codeFile != null && codeFile.exists()) {
9262                try {
9263                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9264                    allCodePaths = pkg.getAllCodePaths();
9265                } catch (PackageParserException e) {
9266                    // Ignored; we tried our best
9267                }
9268            }
9269
9270            cleanUp();
9271
9272            if (!allCodePaths.isEmpty()) {
9273                if (instructionSets == null) {
9274                    throw new IllegalStateException("instructionSet == null");
9275                }
9276                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9277                for (String codePath : allCodePaths) {
9278                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9279                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9280                        if (retCode < 0) {
9281                            Slog.w(TAG, "Couldn't remove dex file for package: "
9282                                    + " at location " + codePath + ", retcode=" + retCode);
9283                            // we don't consider this to be a failure of the core package deletion
9284                        }
9285                    }
9286                }
9287            }
9288        }
9289
9290        boolean doPostDeleteLI(boolean delete) {
9291            // XXX err, shouldn't we respect the delete flag?
9292            cleanUpResourcesLI();
9293            return true;
9294        }
9295    }
9296
9297    private boolean isAsecExternal(String cid) {
9298        final String asecPath = PackageHelper.getSdFilesystem(cid);
9299        return !asecPath.startsWith(mAsecInternalPath);
9300    }
9301
9302    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9303            PackageManagerException {
9304        if (copyRet < 0) {
9305            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9306                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9307                throw new PackageManagerException(copyRet, message);
9308            }
9309        }
9310    }
9311
9312    /**
9313     * Extract the MountService "container ID" from the full code path of an
9314     * .apk.
9315     */
9316    static String cidFromCodePath(String fullCodePath) {
9317        int eidx = fullCodePath.lastIndexOf("/");
9318        String subStr1 = fullCodePath.substring(0, eidx);
9319        int sidx = subStr1.lastIndexOf("/");
9320        return subStr1.substring(sidx+1, eidx);
9321    }
9322
9323    /**
9324     * Logic to handle installation of ASEC applications, including copying and
9325     * renaming logic.
9326     */
9327    class AsecInstallArgs extends InstallArgs {
9328        static final String RES_FILE_NAME = "pkg.apk";
9329        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9330
9331        String cid;
9332        String packagePath;
9333        String resourcePath;
9334        String legacyNativeLibraryDir;
9335
9336        /** New install */
9337        AsecInstallArgs(InstallParams params) {
9338            super(params.origin, params.observer, params.installFlags,
9339                    params.installerPackageName, params.getManifestDigest(),
9340                    params.getUser(), null /* instruction sets */,
9341                    params.packageAbiOverride);
9342        }
9343
9344        /** Existing install */
9345        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9346                        boolean isExternal, boolean isForwardLocked) {
9347            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9348                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9349                    instructionSets, null);
9350            // Hackily pretend we're still looking at a full code path
9351            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9352                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9353            }
9354
9355            // Extract cid from fullCodePath
9356            int eidx = fullCodePath.lastIndexOf("/");
9357            String subStr1 = fullCodePath.substring(0, eidx);
9358            int sidx = subStr1.lastIndexOf("/");
9359            cid = subStr1.substring(sidx+1, eidx);
9360            setMountPath(subStr1);
9361        }
9362
9363        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9364            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9365                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9366                    instructionSets, null);
9367            this.cid = cid;
9368            setMountPath(PackageHelper.getSdDir(cid));
9369        }
9370
9371        void createCopyFile() {
9372            cid = mInstallerService.allocateExternalStageCidLegacy();
9373        }
9374
9375        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9376            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9377                    abiOverride);
9378
9379            final File target;
9380            if (isExternal()) {
9381                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9382            } else {
9383                target = Environment.getDataDirectory();
9384            }
9385
9386            final StorageManager storage = StorageManager.from(mContext);
9387            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9388        }
9389
9390        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9391            if (origin.staged) {
9392                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9393                cid = origin.cid;
9394                setMountPath(PackageHelper.getSdDir(cid));
9395                return PackageManager.INSTALL_SUCCEEDED;
9396            }
9397
9398            if (temp) {
9399                createCopyFile();
9400            } else {
9401                /*
9402                 * Pre-emptively destroy the container since it's destroyed if
9403                 * copying fails due to it existing anyway.
9404                 */
9405                PackageHelper.destroySdDir(cid);
9406            }
9407
9408            final String newMountPath = imcs.copyPackageToContainer(
9409                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9410                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9411
9412            if (newMountPath != null) {
9413                setMountPath(newMountPath);
9414                return PackageManager.INSTALL_SUCCEEDED;
9415            } else {
9416                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9417            }
9418        }
9419
9420        @Override
9421        String getCodePath() {
9422            return packagePath;
9423        }
9424
9425        @Override
9426        String getResourcePath() {
9427            return resourcePath;
9428        }
9429
9430        @Override
9431        String getLegacyNativeLibraryPath() {
9432            return legacyNativeLibraryDir;
9433        }
9434
9435        int doPreInstall(int status) {
9436            if (status != PackageManager.INSTALL_SUCCEEDED) {
9437                // Destroy container
9438                PackageHelper.destroySdDir(cid);
9439            } else {
9440                boolean mounted = PackageHelper.isContainerMounted(cid);
9441                if (!mounted) {
9442                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9443                            Process.SYSTEM_UID);
9444                    if (newMountPath != null) {
9445                        setMountPath(newMountPath);
9446                    } else {
9447                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9448                    }
9449                }
9450            }
9451            return status;
9452        }
9453
9454        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9455            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9456            String newMountPath = null;
9457            if (PackageHelper.isContainerMounted(cid)) {
9458                // Unmount the container
9459                if (!PackageHelper.unMountSdDir(cid)) {
9460                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9461                    return false;
9462                }
9463            }
9464            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9465                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9466                        " which might be stale. Will try to clean up.");
9467                // Clean up the stale container and proceed to recreate.
9468                if (!PackageHelper.destroySdDir(newCacheId)) {
9469                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9470                    return false;
9471                }
9472                // Successfully cleaned up stale container. Try to rename again.
9473                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9474                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9475                            + " inspite of cleaning it up.");
9476                    return false;
9477                }
9478            }
9479            if (!PackageHelper.isContainerMounted(newCacheId)) {
9480                Slog.w(TAG, "Mounting container " + newCacheId);
9481                newMountPath = PackageHelper.mountSdDir(newCacheId,
9482                        getEncryptKey(), Process.SYSTEM_UID);
9483            } else {
9484                newMountPath = PackageHelper.getSdDir(newCacheId);
9485            }
9486            if (newMountPath == null) {
9487                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9488                return false;
9489            }
9490            Log.i(TAG, "Succesfully renamed " + cid +
9491                    " to " + newCacheId +
9492                    " at new path: " + newMountPath);
9493            cid = newCacheId;
9494
9495            final File beforeCodeFile = new File(packagePath);
9496            setMountPath(newMountPath);
9497            final File afterCodeFile = new File(packagePath);
9498
9499            // Reflect the rename in scanned details
9500            pkg.codePath = afterCodeFile.getAbsolutePath();
9501            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9502                    pkg.baseCodePath);
9503            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9504                    pkg.splitCodePaths);
9505
9506            // Reflect the rename in app info
9507            pkg.applicationInfo.setCodePath(pkg.codePath);
9508            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9509            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9510            pkg.applicationInfo.setResourcePath(pkg.codePath);
9511            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9512            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9513
9514            return true;
9515        }
9516
9517        private void setMountPath(String mountPath) {
9518            final File mountFile = new File(mountPath);
9519
9520            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9521            if (monolithicFile.exists()) {
9522                packagePath = monolithicFile.getAbsolutePath();
9523                if (isFwdLocked()) {
9524                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9525                } else {
9526                    resourcePath = packagePath;
9527                }
9528            } else {
9529                packagePath = mountFile.getAbsolutePath();
9530                resourcePath = packagePath;
9531            }
9532
9533            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9534        }
9535
9536        int doPostInstall(int status, int uid) {
9537            if (status != PackageManager.INSTALL_SUCCEEDED) {
9538                cleanUp();
9539            } else {
9540                final int groupOwner;
9541                final String protectedFile;
9542                if (isFwdLocked()) {
9543                    groupOwner = UserHandle.getSharedAppGid(uid);
9544                    protectedFile = RES_FILE_NAME;
9545                } else {
9546                    groupOwner = -1;
9547                    protectedFile = null;
9548                }
9549
9550                if (uid < Process.FIRST_APPLICATION_UID
9551                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9552                    Slog.e(TAG, "Failed to finalize " + cid);
9553                    PackageHelper.destroySdDir(cid);
9554                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9555                }
9556
9557                boolean mounted = PackageHelper.isContainerMounted(cid);
9558                if (!mounted) {
9559                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9560                }
9561            }
9562            return status;
9563        }
9564
9565        private void cleanUp() {
9566            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9567
9568            // Destroy secure container
9569            PackageHelper.destroySdDir(cid);
9570        }
9571
9572        private List<String> getAllCodePaths() {
9573            final File codeFile = new File(getCodePath());
9574            if (codeFile != null && codeFile.exists()) {
9575                try {
9576                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9577                    return pkg.getAllCodePaths();
9578                } catch (PackageParserException e) {
9579                    // Ignored; we tried our best
9580                }
9581            }
9582            return Collections.EMPTY_LIST;
9583        }
9584
9585        void cleanUpResourcesLI() {
9586            // Enumerate all code paths before deleting
9587            cleanUpResourcesLI(getAllCodePaths());
9588        }
9589
9590        private void cleanUpResourcesLI(List<String> allCodePaths) {
9591            cleanUp();
9592
9593            if (!allCodePaths.isEmpty()) {
9594                if (instructionSets == null) {
9595                    throw new IllegalStateException("instructionSet == null");
9596                }
9597                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9598                for (String codePath : allCodePaths) {
9599                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9600                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9601                        if (retCode < 0) {
9602                            Slog.w(TAG, "Couldn't remove dex file for package: "
9603                                    + " at location " + codePath + ", retcode=" + retCode);
9604                            // we don't consider this to be a failure of the core package deletion
9605                        }
9606                    }
9607                }
9608            }
9609        }
9610
9611        boolean matchContainer(String app) {
9612            if (cid.startsWith(app)) {
9613                return true;
9614            }
9615            return false;
9616        }
9617
9618        String getPackageName() {
9619            return getAsecPackageName(cid);
9620        }
9621
9622        boolean doPostDeleteLI(boolean delete) {
9623            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9624            final List<String> allCodePaths = getAllCodePaths();
9625            boolean mounted = PackageHelper.isContainerMounted(cid);
9626            if (mounted) {
9627                // Unmount first
9628                if (PackageHelper.unMountSdDir(cid)) {
9629                    mounted = false;
9630                }
9631            }
9632            if (!mounted && delete) {
9633                cleanUpResourcesLI(allCodePaths);
9634            }
9635            return !mounted;
9636        }
9637
9638        @Override
9639        int doPreCopy() {
9640            if (isFwdLocked()) {
9641                if (!PackageHelper.fixSdPermissions(cid,
9642                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9643                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9644                }
9645            }
9646
9647            return PackageManager.INSTALL_SUCCEEDED;
9648        }
9649
9650        @Override
9651        int doPostCopy(int uid) {
9652            if (isFwdLocked()) {
9653                if (uid < Process.FIRST_APPLICATION_UID
9654                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9655                                RES_FILE_NAME)) {
9656                    Slog.e(TAG, "Failed to finalize " + cid);
9657                    PackageHelper.destroySdDir(cid);
9658                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9659                }
9660            }
9661
9662            return PackageManager.INSTALL_SUCCEEDED;
9663        }
9664    }
9665
9666    static String getAsecPackageName(String packageCid) {
9667        int idx = packageCid.lastIndexOf("-");
9668        if (idx == -1) {
9669            return packageCid;
9670        }
9671        return packageCid.substring(0, idx);
9672    }
9673
9674    // Utility method used to create code paths based on package name and available index.
9675    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9676        String idxStr = "";
9677        int idx = 1;
9678        // Fall back to default value of idx=1 if prefix is not
9679        // part of oldCodePath
9680        if (oldCodePath != null) {
9681            String subStr = oldCodePath;
9682            // Drop the suffix right away
9683            if (suffix != null && subStr.endsWith(suffix)) {
9684                subStr = subStr.substring(0, subStr.length() - suffix.length());
9685            }
9686            // If oldCodePath already contains prefix find out the
9687            // ending index to either increment or decrement.
9688            int sidx = subStr.lastIndexOf(prefix);
9689            if (sidx != -1) {
9690                subStr = subStr.substring(sidx + prefix.length());
9691                if (subStr != null) {
9692                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9693                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9694                    }
9695                    try {
9696                        idx = Integer.parseInt(subStr);
9697                        if (idx <= 1) {
9698                            idx++;
9699                        } else {
9700                            idx--;
9701                        }
9702                    } catch(NumberFormatException e) {
9703                    }
9704                }
9705            }
9706        }
9707        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9708        return prefix + idxStr;
9709    }
9710
9711    private File getNextCodePath(String packageName) {
9712        int suffix = 1;
9713        File result;
9714        do {
9715            result = new File(mAppInstallDir, packageName + "-" + suffix);
9716            suffix++;
9717        } while (result.exists());
9718        return result;
9719    }
9720
9721    // Utility method used to ignore ADD/REMOVE events
9722    // by directory observer.
9723    private static boolean ignoreCodePath(String fullPathStr) {
9724        String apkName = deriveCodePathName(fullPathStr);
9725        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9726        if (idx != -1 && ((idx+1) < apkName.length())) {
9727            // Make sure the package ends with a numeral
9728            String version = apkName.substring(idx+1);
9729            try {
9730                Integer.parseInt(version);
9731                return true;
9732            } catch (NumberFormatException e) {}
9733        }
9734        return false;
9735    }
9736
9737    // Utility method that returns the relative package path with respect
9738    // to the installation directory. Like say for /data/data/com.test-1.apk
9739    // string com.test-1 is returned.
9740    static String deriveCodePathName(String codePath) {
9741        if (codePath == null) {
9742            return null;
9743        }
9744        final File codeFile = new File(codePath);
9745        final String name = codeFile.getName();
9746        if (codeFile.isDirectory()) {
9747            return name;
9748        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9749            final int lastDot = name.lastIndexOf('.');
9750            return name.substring(0, lastDot);
9751        } else {
9752            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9753            return null;
9754        }
9755    }
9756
9757    class PackageInstalledInfo {
9758        String name;
9759        int uid;
9760        // The set of users that originally had this package installed.
9761        int[] origUsers;
9762        // The set of users that now have this package installed.
9763        int[] newUsers;
9764        PackageParser.Package pkg;
9765        int returnCode;
9766        String returnMsg;
9767        PackageRemovedInfo removedInfo;
9768
9769        public void setError(int code, String msg) {
9770            returnCode = code;
9771            returnMsg = msg;
9772            Slog.w(TAG, msg);
9773        }
9774
9775        public void setError(String msg, PackageParserException e) {
9776            returnCode = e.error;
9777            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9778            Slog.w(TAG, msg, e);
9779        }
9780
9781        public void setError(String msg, PackageManagerException e) {
9782            returnCode = e.error;
9783            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9784            Slog.w(TAG, msg, e);
9785        }
9786
9787        // In some error cases we want to convey more info back to the observer
9788        String origPackage;
9789        String origPermission;
9790    }
9791
9792    /*
9793     * Install a non-existing package.
9794     */
9795    private void installNewPackageLI(PackageParser.Package pkg,
9796            int parseFlags, int scanFlags, UserHandle user,
9797            String installerPackageName, PackageInstalledInfo res) {
9798        // Remember this for later, in case we need to rollback this install
9799        String pkgName = pkg.packageName;
9800
9801        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9802        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9803        synchronized(mPackages) {
9804            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9805                // A package with the same name is already installed, though
9806                // it has been renamed to an older name.  The package we
9807                // are trying to install should be installed as an update to
9808                // the existing one, but that has not been requested, so bail.
9809                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9810                        + " without first uninstalling package running as "
9811                        + mSettings.mRenamedPackages.get(pkgName));
9812                return;
9813            }
9814            if (mPackages.containsKey(pkgName)) {
9815                // Don't allow installation over an existing package with the same name.
9816                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9817                        + " without first uninstalling.");
9818                return;
9819            }
9820        }
9821
9822        try {
9823            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9824                    System.currentTimeMillis(), user);
9825
9826            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9827            // delete the partially installed application. the data directory will have to be
9828            // restored if it was already existing
9829            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9830                // remove package from internal structures.  Note that we want deletePackageX to
9831                // delete the package data and cache directories that it created in
9832                // scanPackageLocked, unless those directories existed before we even tried to
9833                // install.
9834                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9835                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9836                                res.removedInfo, true);
9837            }
9838
9839        } catch (PackageManagerException e) {
9840            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9841        }
9842    }
9843
9844    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9845        // Upgrade keysets are being used.  Determine if new package has a superset of the
9846        // required keys.
9847        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9848        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9849        for (int i = 0; i < upgradeKeySets.length; i++) {
9850            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9851            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9852                return true;
9853            }
9854        }
9855        return false;
9856    }
9857
9858    private void replacePackageLI(PackageParser.Package pkg,
9859            int parseFlags, int scanFlags, UserHandle user,
9860            String installerPackageName, PackageInstalledInfo res) {
9861        PackageParser.Package oldPackage;
9862        String pkgName = pkg.packageName;
9863        int[] allUsers;
9864        boolean[] perUserInstalled;
9865
9866        // First find the old package info and check signatures
9867        synchronized(mPackages) {
9868            oldPackage = mPackages.get(pkgName);
9869            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9870            PackageSetting ps = mSettings.mPackages.get(pkgName);
9871            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9872                // default to original signature matching
9873                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9874                    != PackageManager.SIGNATURE_MATCH) {
9875                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9876                            "New package has a different signature: " + pkgName);
9877                    return;
9878                }
9879            } else {
9880                if(!checkUpgradeKeySetLP(ps, pkg)) {
9881                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9882                            "New package not signed by keys specified by upgrade-keysets: "
9883                            + pkgName);
9884                    return;
9885                }
9886            }
9887
9888            // In case of rollback, remember per-user/profile install state
9889            allUsers = sUserManager.getUserIds();
9890            perUserInstalled = new boolean[allUsers.length];
9891            for (int i = 0; i < allUsers.length; i++) {
9892                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9893            }
9894        }
9895
9896        boolean sysPkg = (isSystemApp(oldPackage));
9897        if (sysPkg) {
9898            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9899                    user, allUsers, perUserInstalled, installerPackageName, res);
9900        } else {
9901            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9902                    user, allUsers, perUserInstalled, installerPackageName, res);
9903        }
9904    }
9905
9906    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9907            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9908            int[] allUsers, boolean[] perUserInstalled,
9909            String installerPackageName, PackageInstalledInfo res) {
9910        String pkgName = deletedPackage.packageName;
9911        boolean deletedPkg = true;
9912        boolean updatedSettings = false;
9913
9914        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9915                + deletedPackage);
9916        long origUpdateTime;
9917        if (pkg.mExtras != null) {
9918            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9919        } else {
9920            origUpdateTime = 0;
9921        }
9922
9923        // First delete the existing package while retaining the data directory
9924        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9925                res.removedInfo, true)) {
9926            // If the existing package wasn't successfully deleted
9927            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9928            deletedPkg = false;
9929        } else {
9930            // Successfully deleted the old package; proceed with replace.
9931
9932            // If deleted package lived in a container, give users a chance to
9933            // relinquish resources before killing.
9934            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9935                if (DEBUG_INSTALL) {
9936                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9937                }
9938                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9939                final ArrayList<String> pkgList = new ArrayList<String>(1);
9940                pkgList.add(deletedPackage.applicationInfo.packageName);
9941                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9942            }
9943
9944            deleteCodeCacheDirsLI(pkgName);
9945            try {
9946                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9947                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9948                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9949                updatedSettings = true;
9950            } catch (PackageManagerException e) {
9951                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9952            }
9953        }
9954
9955        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9956            // remove package from internal structures.  Note that we want deletePackageX to
9957            // delete the package data and cache directories that it created in
9958            // scanPackageLocked, unless those directories existed before we even tried to
9959            // install.
9960            if(updatedSettings) {
9961                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9962                deletePackageLI(
9963                        pkgName, null, true, allUsers, perUserInstalled,
9964                        PackageManager.DELETE_KEEP_DATA,
9965                                res.removedInfo, true);
9966            }
9967            // Since we failed to install the new package we need to restore the old
9968            // package that we deleted.
9969            if (deletedPkg) {
9970                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9971                File restoreFile = new File(deletedPackage.codePath);
9972                // Parse old package
9973                boolean oldOnSd = isExternal(deletedPackage);
9974                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9975                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9976                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9977                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9978                try {
9979                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9980                } catch (PackageManagerException e) {
9981                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9982                            + e.getMessage());
9983                    return;
9984                }
9985                // Restore of old package succeeded. Update permissions.
9986                // writer
9987                synchronized (mPackages) {
9988                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9989                            UPDATE_PERMISSIONS_ALL);
9990                    // can downgrade to reader
9991                    mSettings.writeLPr();
9992                }
9993                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9994            }
9995        }
9996    }
9997
9998    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9999            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10000            int[] allUsers, boolean[] perUserInstalled,
10001            String installerPackageName, PackageInstalledInfo res) {
10002        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10003                + ", old=" + deletedPackage);
10004        boolean updatedSettings = false;
10005        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10006        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10007            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10008        }
10009        String packageName = deletedPackage.packageName;
10010        if (packageName == null) {
10011            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10012                    "Attempt to delete null packageName.");
10013            return;
10014        }
10015        PackageParser.Package oldPkg;
10016        PackageSetting oldPkgSetting;
10017        // reader
10018        synchronized (mPackages) {
10019            oldPkg = mPackages.get(packageName);
10020            oldPkgSetting = mSettings.mPackages.get(packageName);
10021            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10022                    (oldPkgSetting == null)) {
10023                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10024                        "Couldn't find package:" + packageName + " information");
10025                return;
10026            }
10027        }
10028
10029        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10030
10031        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10032        res.removedInfo.removedPackage = packageName;
10033        // Remove existing system package
10034        removePackageLI(oldPkgSetting, true);
10035        // writer
10036        synchronized (mPackages) {
10037            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10038                // We didn't need to disable the .apk as a current system package,
10039                // which means we are replacing another update that is already
10040                // installed.  We need to make sure to delete the older one's .apk.
10041                res.removedInfo.args = createInstallArgsForExisting(0,
10042                        deletedPackage.applicationInfo.getCodePath(),
10043                        deletedPackage.applicationInfo.getResourcePath(),
10044                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10045                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10046            } else {
10047                res.removedInfo.args = null;
10048            }
10049        }
10050
10051        // Successfully disabled the old package. Now proceed with re-installation
10052        deleteCodeCacheDirsLI(packageName);
10053
10054        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10055        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10056
10057        PackageParser.Package newPackage = null;
10058        try {
10059            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10060            if (newPackage.mExtras != null) {
10061                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10062                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10063                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10064
10065                // is the update attempting to change shared user? that isn't going to work...
10066                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10067                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10068                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10069                            + " to " + newPkgSetting.sharedUser);
10070                    updatedSettings = true;
10071                }
10072            }
10073
10074            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10075                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10076                updatedSettings = true;
10077            }
10078
10079        } catch (PackageManagerException e) {
10080            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10081        }
10082
10083        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10084            // Re installation failed. Restore old information
10085            // Remove new pkg information
10086            if (newPackage != null) {
10087                removeInstalledPackageLI(newPackage, true);
10088            }
10089            // Add back the old system package
10090            try {
10091                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10092            } catch (PackageManagerException e) {
10093                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10094            }
10095            // Restore the old system information in Settings
10096            synchronized(mPackages) {
10097                if (updatedSettings) {
10098                    mSettings.enableSystemPackageLPw(packageName);
10099                    mSettings.setInstallerPackageName(packageName,
10100                            oldPkgSetting.installerPackageName);
10101                }
10102                mSettings.writeLPr();
10103            }
10104        }
10105    }
10106
10107    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10108            int[] allUsers, boolean[] perUserInstalled,
10109            PackageInstalledInfo res) {
10110        String pkgName = newPackage.packageName;
10111        synchronized (mPackages) {
10112            //write settings. the installStatus will be incomplete at this stage.
10113            //note that the new package setting would have already been
10114            //added to mPackages. It hasn't been persisted yet.
10115            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10116            mSettings.writeLPr();
10117        }
10118
10119        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10120
10121        synchronized (mPackages) {
10122            updatePermissionsLPw(newPackage.packageName, newPackage,
10123                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10124                            ? UPDATE_PERMISSIONS_ALL : 0));
10125            // For system-bundled packages, we assume that installing an upgraded version
10126            // of the package implies that the user actually wants to run that new code,
10127            // so we enable the package.
10128            if (isSystemApp(newPackage)) {
10129                // NB: implicit assumption that system package upgrades apply to all users
10130                if (DEBUG_INSTALL) {
10131                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10132                }
10133                PackageSetting ps = mSettings.mPackages.get(pkgName);
10134                if (ps != null) {
10135                    if (res.origUsers != null) {
10136                        for (int userHandle : res.origUsers) {
10137                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10138                                    userHandle, installerPackageName);
10139                        }
10140                    }
10141                    // Also convey the prior install/uninstall state
10142                    if (allUsers != null && perUserInstalled != null) {
10143                        for (int i = 0; i < allUsers.length; i++) {
10144                            if (DEBUG_INSTALL) {
10145                                Slog.d(TAG, "    user " + allUsers[i]
10146                                        + " => " + perUserInstalled[i]);
10147                            }
10148                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10149                        }
10150                        // these install state changes will be persisted in the
10151                        // upcoming call to mSettings.writeLPr().
10152                    }
10153                }
10154            }
10155            res.name = pkgName;
10156            res.uid = newPackage.applicationInfo.uid;
10157            res.pkg = newPackage;
10158            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10159            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10160            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10161            //to update install status
10162            mSettings.writeLPr();
10163        }
10164    }
10165
10166    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10167        final int installFlags = args.installFlags;
10168        String installerPackageName = args.installerPackageName;
10169        File tmpPackageFile = new File(args.getCodePath());
10170        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10171        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10172        boolean replace = false;
10173        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10174        // Result object to be returned
10175        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10176
10177        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10178        // Retrieve PackageSettings and parse package
10179        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10180                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10181                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10182        PackageParser pp = new PackageParser();
10183        pp.setSeparateProcesses(mSeparateProcesses);
10184        pp.setDisplayMetrics(mMetrics);
10185
10186        final PackageParser.Package pkg;
10187        try {
10188            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10189        } catch (PackageParserException e) {
10190            res.setError("Failed parse during installPackageLI", e);
10191            return;
10192        }
10193
10194        // Mark that we have an install time CPU ABI override.
10195        pkg.cpuAbiOverride = args.abiOverride;
10196
10197        String pkgName = res.name = pkg.packageName;
10198        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10199            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10200                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10201                return;
10202            }
10203        }
10204
10205        try {
10206            pp.collectCertificates(pkg, parseFlags);
10207            pp.collectManifestDigest(pkg);
10208        } catch (PackageParserException e) {
10209            res.setError("Failed collect during installPackageLI", e);
10210            return;
10211        }
10212
10213        /* If the installer passed in a manifest digest, compare it now. */
10214        if (args.manifestDigest != null) {
10215            if (DEBUG_INSTALL) {
10216                final String parsedManifest = pkg.manifestDigest == null ? "null"
10217                        : pkg.manifestDigest.toString();
10218                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10219                        + parsedManifest);
10220            }
10221
10222            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10223                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10224                return;
10225            }
10226        } else if (DEBUG_INSTALL) {
10227            final String parsedManifest = pkg.manifestDigest == null
10228                    ? "null" : pkg.manifestDigest.toString();
10229            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10230        }
10231
10232        // Get rid of all references to package scan path via parser.
10233        pp = null;
10234        String oldCodePath = null;
10235        boolean systemApp = false;
10236        synchronized (mPackages) {
10237            // Check whether the newly-scanned package wants to define an already-defined perm
10238            int N = pkg.permissions.size();
10239            for (int i = N-1; i >= 0; i--) {
10240                PackageParser.Permission perm = pkg.permissions.get(i);
10241                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10242                if (bp != null) {
10243                    // If the defining package is signed with our cert, it's okay.  This
10244                    // also includes the "updating the same package" case, of course.
10245                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10246                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10247                        // If the owning package is the system itself, we log but allow
10248                        // install to proceed; we fail the install on all other permission
10249                        // redefinitions.
10250                        if (!bp.sourcePackage.equals("android")) {
10251                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10252                                    + pkg.packageName + " attempting to redeclare permission "
10253                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10254                            res.origPermission = perm.info.name;
10255                            res.origPackage = bp.sourcePackage;
10256                            return;
10257                        } else {
10258                            Slog.w(TAG, "Package " + pkg.packageName
10259                                    + " attempting to redeclare system permission "
10260                                    + perm.info.name + "; ignoring new declaration");
10261                            pkg.permissions.remove(i);
10262                        }
10263                    }
10264                }
10265            }
10266
10267            // Check if installing already existing package
10268            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10269                String oldName = mSettings.mRenamedPackages.get(pkgName);
10270                if (pkg.mOriginalPackages != null
10271                        && pkg.mOriginalPackages.contains(oldName)
10272                        && mPackages.containsKey(oldName)) {
10273                    // This package is derived from an original package,
10274                    // and this device has been updating from that original
10275                    // name.  We must continue using the original name, so
10276                    // rename the new package here.
10277                    pkg.setPackageName(oldName);
10278                    pkgName = pkg.packageName;
10279                    replace = true;
10280                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10281                            + oldName + " pkgName=" + pkgName);
10282                } else if (mPackages.containsKey(pkgName)) {
10283                    // This package, under its official name, already exists
10284                    // on the device; we should replace it.
10285                    replace = true;
10286                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10287                }
10288            }
10289            PackageSetting ps = mSettings.mPackages.get(pkgName);
10290            if (ps != null) {
10291                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10292                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10293                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10294                    systemApp = (ps.pkg.applicationInfo.flags &
10295                            ApplicationInfo.FLAG_SYSTEM) != 0;
10296                }
10297                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10298            }
10299        }
10300
10301        if (systemApp && onSd) {
10302            // Disable updates to system apps on sdcard
10303            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10304                    "Cannot install updates to system apps on sdcard");
10305            return;
10306        }
10307
10308        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10309            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10310            return;
10311        }
10312
10313        if (replace) {
10314            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10315                    installerPackageName, res);
10316        } else {
10317            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10318                    args.user, installerPackageName, res);
10319        }
10320        synchronized (mPackages) {
10321            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10322            if (ps != null) {
10323                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10324            }
10325        }
10326    }
10327
10328    private static boolean isForwardLocked(PackageParser.Package pkg) {
10329        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10330    }
10331
10332    private static boolean isForwardLocked(ApplicationInfo info) {
10333        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10334    }
10335
10336    private boolean isForwardLocked(PackageSetting ps) {
10337        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10338    }
10339
10340    private static boolean isMultiArch(PackageSetting ps) {
10341        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10342    }
10343
10344    private static boolean isMultiArch(ApplicationInfo info) {
10345        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10346    }
10347
10348    private static boolean isExternal(PackageParser.Package pkg) {
10349        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10350    }
10351
10352    private static boolean isExternal(PackageSetting ps) {
10353        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10354    }
10355
10356    private static boolean isExternal(ApplicationInfo info) {
10357        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10358    }
10359
10360    private static boolean isSystemApp(PackageParser.Package pkg) {
10361        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10362    }
10363
10364    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10365        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10366    }
10367
10368    private static boolean isSystemApp(ApplicationInfo info) {
10369        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10370    }
10371
10372    private static boolean isSystemApp(PackageSetting ps) {
10373        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10374    }
10375
10376    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10377        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10378    }
10379
10380    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10381        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10382    }
10383
10384    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10385        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10386    }
10387
10388    private int packageFlagsToInstallFlags(PackageSetting ps) {
10389        int installFlags = 0;
10390        if (isExternal(ps)) {
10391            installFlags |= PackageManager.INSTALL_EXTERNAL;
10392        }
10393        if (isForwardLocked(ps)) {
10394            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10395        }
10396        return installFlags;
10397    }
10398
10399    private void deleteTempPackageFiles() {
10400        final FilenameFilter filter = new FilenameFilter() {
10401            public boolean accept(File dir, String name) {
10402                return name.startsWith("vmdl") && name.endsWith(".tmp");
10403            }
10404        };
10405        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10406            file.delete();
10407        }
10408    }
10409
10410    @Override
10411    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10412            int flags) {
10413        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10414                flags);
10415    }
10416
10417    @Override
10418    public void deletePackage(final String packageName,
10419            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10420        mContext.enforceCallingOrSelfPermission(
10421                android.Manifest.permission.DELETE_PACKAGES, null);
10422        final int uid = Binder.getCallingUid();
10423        if (UserHandle.getUserId(uid) != userId) {
10424            mContext.enforceCallingPermission(
10425                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10426                    "deletePackage for user " + userId);
10427        }
10428        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10429            try {
10430                observer.onPackageDeleted(packageName,
10431                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10432            } catch (RemoteException re) {
10433            }
10434            return;
10435        }
10436
10437        boolean uninstallBlocked = false;
10438        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10439            int[] users = sUserManager.getUserIds();
10440            for (int i = 0; i < users.length; ++i) {
10441                if (getBlockUninstallForUser(packageName, users[i])) {
10442                    uninstallBlocked = true;
10443                    break;
10444                }
10445            }
10446        } else {
10447            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10448        }
10449        if (uninstallBlocked) {
10450            try {
10451                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10452                        null);
10453            } catch (RemoteException re) {
10454            }
10455            return;
10456        }
10457
10458        if (DEBUG_REMOVE) {
10459            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10460        }
10461        // Queue up an async operation since the package deletion may take a little while.
10462        mHandler.post(new Runnable() {
10463            public void run() {
10464                mHandler.removeCallbacks(this);
10465                final int returnCode = deletePackageX(packageName, userId, flags);
10466                if (observer != null) {
10467                    try {
10468                        observer.onPackageDeleted(packageName, returnCode, null);
10469                    } catch (RemoteException e) {
10470                        Log.i(TAG, "Observer no longer exists.");
10471                    } //end catch
10472                } //end if
10473            } //end run
10474        });
10475    }
10476
10477    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10478        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10479                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10480        try {
10481            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10482                    || dpm.isDeviceOwner(packageName))) {
10483                return true;
10484            }
10485        } catch (RemoteException e) {
10486        }
10487        return false;
10488    }
10489
10490    /**
10491     *  This method is an internal method that could be get invoked either
10492     *  to delete an installed package or to clean up a failed installation.
10493     *  After deleting an installed package, a broadcast is sent to notify any
10494     *  listeners that the package has been installed. For cleaning up a failed
10495     *  installation, the broadcast is not necessary since the package's
10496     *  installation wouldn't have sent the initial broadcast either
10497     *  The key steps in deleting a package are
10498     *  deleting the package information in internal structures like mPackages,
10499     *  deleting the packages base directories through installd
10500     *  updating mSettings to reflect current status
10501     *  persisting settings for later use
10502     *  sending a broadcast if necessary
10503     */
10504    private int deletePackageX(String packageName, int userId, int flags) {
10505        final PackageRemovedInfo info = new PackageRemovedInfo();
10506        final boolean res;
10507
10508        if (isPackageDeviceAdmin(packageName, userId)) {
10509            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10510            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10511        }
10512
10513        boolean removedForAllUsers = false;
10514        boolean systemUpdate = false;
10515
10516        // for the uninstall-updates case and restricted profiles, remember the per-
10517        // userhandle installed state
10518        int[] allUsers;
10519        boolean[] perUserInstalled;
10520        synchronized (mPackages) {
10521            PackageSetting ps = mSettings.mPackages.get(packageName);
10522            allUsers = sUserManager.getUserIds();
10523            perUserInstalled = new boolean[allUsers.length];
10524            for (int i = 0; i < allUsers.length; i++) {
10525                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10526            }
10527        }
10528
10529        synchronized (mInstallLock) {
10530            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10531            res = deletePackageLI(packageName,
10532                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10533                            ? UserHandle.ALL : new UserHandle(userId),
10534                    true, allUsers, perUserInstalled,
10535                    flags | REMOVE_CHATTY, info, true);
10536            systemUpdate = info.isRemovedPackageSystemUpdate;
10537            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10538                removedForAllUsers = true;
10539            }
10540            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10541                    + " removedForAllUsers=" + removedForAllUsers);
10542        }
10543
10544        if (res) {
10545            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10546
10547            // If the removed package was a system update, the old system package
10548            // was re-enabled; we need to broadcast this information
10549            if (systemUpdate) {
10550                Bundle extras = new Bundle(1);
10551                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10552                        ? info.removedAppId : info.uid);
10553                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10554
10555                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10556                        extras, null, null, null);
10557                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10558                        extras, null, null, null);
10559                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10560                        null, packageName, null, null);
10561            }
10562        }
10563        // Force a gc here.
10564        Runtime.getRuntime().gc();
10565        // Delete the resources here after sending the broadcast to let
10566        // other processes clean up before deleting resources.
10567        if (info.args != null) {
10568            synchronized (mInstallLock) {
10569                info.args.doPostDeleteLI(true);
10570            }
10571        }
10572
10573        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10574    }
10575
10576    static class PackageRemovedInfo {
10577        String removedPackage;
10578        int uid = -1;
10579        int removedAppId = -1;
10580        int[] removedUsers = null;
10581        boolean isRemovedPackageSystemUpdate = false;
10582        // Clean up resources deleted packages.
10583        InstallArgs args = null;
10584
10585        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10586            Bundle extras = new Bundle(1);
10587            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10588            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10589            if (replacing) {
10590                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10591            }
10592            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10593            if (removedPackage != null) {
10594                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10595                        extras, null, null, removedUsers);
10596                if (fullRemove && !replacing) {
10597                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10598                            extras, null, null, removedUsers);
10599                }
10600            }
10601            if (removedAppId >= 0) {
10602                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10603                        removedUsers);
10604            }
10605        }
10606    }
10607
10608    /*
10609     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10610     * flag is not set, the data directory is removed as well.
10611     * make sure this flag is set for partially installed apps. If not its meaningless to
10612     * delete a partially installed application.
10613     */
10614    private void removePackageDataLI(PackageSetting ps,
10615            int[] allUserHandles, boolean[] perUserInstalled,
10616            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10617        String packageName = ps.name;
10618        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10619        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10620        // Retrieve object to delete permissions for shared user later on
10621        final PackageSetting deletedPs;
10622        // reader
10623        synchronized (mPackages) {
10624            deletedPs = mSettings.mPackages.get(packageName);
10625            if (outInfo != null) {
10626                outInfo.removedPackage = packageName;
10627                outInfo.removedUsers = deletedPs != null
10628                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10629                        : null;
10630            }
10631        }
10632        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10633            removeDataDirsLI(packageName);
10634            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10635        }
10636        // writer
10637        synchronized (mPackages) {
10638            if (deletedPs != null) {
10639                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10640                    if (outInfo != null) {
10641                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10642                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10643                    }
10644                    if (deletedPs != null) {
10645                        updatePermissionsLPw(deletedPs.name, null, 0);
10646                        if (deletedPs.sharedUser != null) {
10647                            // remove permissions associated with package
10648                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10649                        }
10650                    }
10651                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10652                }
10653                // make sure to preserve per-user disabled state if this removal was just
10654                // a downgrade of a system app to the factory package
10655                if (allUserHandles != null && perUserInstalled != null) {
10656                    if (DEBUG_REMOVE) {
10657                        Slog.d(TAG, "Propagating install state across downgrade");
10658                    }
10659                    for (int i = 0; i < allUserHandles.length; i++) {
10660                        if (DEBUG_REMOVE) {
10661                            Slog.d(TAG, "    user " + allUserHandles[i]
10662                                    + " => " + perUserInstalled[i]);
10663                        }
10664                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10665                    }
10666                }
10667            }
10668            // can downgrade to reader
10669            if (writeSettings) {
10670                // Save settings now
10671                mSettings.writeLPr();
10672            }
10673        }
10674        if (outInfo != null) {
10675            // A user ID was deleted here. Go through all users and remove it
10676            // from KeyStore.
10677            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10678        }
10679    }
10680
10681    static boolean locationIsPrivileged(File path) {
10682        try {
10683            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10684                    .getCanonicalPath();
10685            return path.getCanonicalPath().startsWith(privilegedAppDir);
10686        } catch (IOException e) {
10687            Slog.e(TAG, "Unable to access code path " + path);
10688        }
10689        return false;
10690    }
10691
10692    /*
10693     * Tries to delete system package.
10694     */
10695    private boolean deleteSystemPackageLI(PackageSetting newPs,
10696            int[] allUserHandles, boolean[] perUserInstalled,
10697            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10698        final boolean applyUserRestrictions
10699                = (allUserHandles != null) && (perUserInstalled != null);
10700        PackageSetting disabledPs = null;
10701        // Confirm if the system package has been updated
10702        // An updated system app can be deleted. This will also have to restore
10703        // the system pkg from system partition
10704        // reader
10705        synchronized (mPackages) {
10706            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10707        }
10708        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10709                + " disabledPs=" + disabledPs);
10710        if (disabledPs == null) {
10711            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10712            return false;
10713        } else if (DEBUG_REMOVE) {
10714            Slog.d(TAG, "Deleting system pkg from data partition");
10715        }
10716        if (DEBUG_REMOVE) {
10717            if (applyUserRestrictions) {
10718                Slog.d(TAG, "Remembering install states:");
10719                for (int i = 0; i < allUserHandles.length; i++) {
10720                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10721                }
10722            }
10723        }
10724        // Delete the updated package
10725        outInfo.isRemovedPackageSystemUpdate = true;
10726        if (disabledPs.versionCode < newPs.versionCode) {
10727            // Delete data for downgrades
10728            flags &= ~PackageManager.DELETE_KEEP_DATA;
10729        } else {
10730            // Preserve data by setting flag
10731            flags |= PackageManager.DELETE_KEEP_DATA;
10732        }
10733        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10734                allUserHandles, perUserInstalled, outInfo, writeSettings);
10735        if (!ret) {
10736            return false;
10737        }
10738        // writer
10739        synchronized (mPackages) {
10740            // Reinstate the old system package
10741            mSettings.enableSystemPackageLPw(newPs.name);
10742            // Remove any native libraries from the upgraded package.
10743            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10744        }
10745        // Install the system package
10746        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10747        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10748        if (locationIsPrivileged(disabledPs.codePath)) {
10749            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10750        }
10751
10752        final PackageParser.Package newPkg;
10753        try {
10754            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10755        } catch (PackageManagerException e) {
10756            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10757            return false;
10758        }
10759
10760        // writer
10761        synchronized (mPackages) {
10762            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10763            updatePermissionsLPw(newPkg.packageName, newPkg,
10764                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10765            if (applyUserRestrictions) {
10766                if (DEBUG_REMOVE) {
10767                    Slog.d(TAG, "Propagating install state across reinstall");
10768                }
10769                for (int i = 0; i < allUserHandles.length; i++) {
10770                    if (DEBUG_REMOVE) {
10771                        Slog.d(TAG, "    user " + allUserHandles[i]
10772                                + " => " + perUserInstalled[i]);
10773                    }
10774                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10775                }
10776                // Regardless of writeSettings we need to ensure that this restriction
10777                // state propagation is persisted
10778                mSettings.writeAllUsersPackageRestrictionsLPr();
10779            }
10780            // can downgrade to reader here
10781            if (writeSettings) {
10782                mSettings.writeLPr();
10783            }
10784        }
10785        return true;
10786    }
10787
10788    private boolean deleteInstalledPackageLI(PackageSetting ps,
10789            boolean deleteCodeAndResources, int flags,
10790            int[] allUserHandles, boolean[] perUserInstalled,
10791            PackageRemovedInfo outInfo, boolean writeSettings) {
10792        if (outInfo != null) {
10793            outInfo.uid = ps.appId;
10794        }
10795
10796        // Delete package data from internal structures and also remove data if flag is set
10797        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10798
10799        // Delete application code and resources
10800        if (deleteCodeAndResources && (outInfo != null)) {
10801            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10802                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10803                    getAppDexInstructionSets(ps));
10804            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10805        }
10806        return true;
10807    }
10808
10809    @Override
10810    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10811            int userId) {
10812        mContext.enforceCallingOrSelfPermission(
10813                android.Manifest.permission.DELETE_PACKAGES, null);
10814        synchronized (mPackages) {
10815            PackageSetting ps = mSettings.mPackages.get(packageName);
10816            if (ps == null) {
10817                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10818                return false;
10819            }
10820            if (!ps.getInstalled(userId)) {
10821                // Can't block uninstall for an app that is not installed or enabled.
10822                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10823                return false;
10824            }
10825            ps.setBlockUninstall(blockUninstall, userId);
10826            mSettings.writePackageRestrictionsLPr(userId);
10827        }
10828        return true;
10829    }
10830
10831    @Override
10832    public boolean getBlockUninstallForUser(String packageName, int userId) {
10833        synchronized (mPackages) {
10834            PackageSetting ps = mSettings.mPackages.get(packageName);
10835            if (ps == null) {
10836                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10837                return false;
10838            }
10839            return ps.getBlockUninstall(userId);
10840        }
10841    }
10842
10843    /*
10844     * This method handles package deletion in general
10845     */
10846    private boolean deletePackageLI(String packageName, UserHandle user,
10847            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10848            int flags, PackageRemovedInfo outInfo,
10849            boolean writeSettings) {
10850        if (packageName == null) {
10851            Slog.w(TAG, "Attempt to delete null packageName.");
10852            return false;
10853        }
10854        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10855        PackageSetting ps;
10856        boolean dataOnly = false;
10857        int removeUser = -1;
10858        int appId = -1;
10859        synchronized (mPackages) {
10860            ps = mSettings.mPackages.get(packageName);
10861            if (ps == null) {
10862                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10863                return false;
10864            }
10865            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10866                    && user.getIdentifier() != UserHandle.USER_ALL) {
10867                // The caller is asking that the package only be deleted for a single
10868                // user.  To do this, we just mark its uninstalled state and delete
10869                // its data.  If this is a system app, we only allow this to happen if
10870                // they have set the special DELETE_SYSTEM_APP which requests different
10871                // semantics than normal for uninstalling system apps.
10872                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10873                ps.setUserState(user.getIdentifier(),
10874                        COMPONENT_ENABLED_STATE_DEFAULT,
10875                        false, //installed
10876                        true,  //stopped
10877                        true,  //notLaunched
10878                        false, //hidden
10879                        null, null, null,
10880                        false // blockUninstall
10881                        );
10882                if (!isSystemApp(ps)) {
10883                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10884                        // Other user still have this package installed, so all
10885                        // we need to do is clear this user's data and save that
10886                        // it is uninstalled.
10887                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10888                        removeUser = user.getIdentifier();
10889                        appId = ps.appId;
10890                        mSettings.writePackageRestrictionsLPr(removeUser);
10891                    } else {
10892                        // We need to set it back to 'installed' so the uninstall
10893                        // broadcasts will be sent correctly.
10894                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10895                        ps.setInstalled(true, user.getIdentifier());
10896                    }
10897                } else {
10898                    // This is a system app, so we assume that the
10899                    // other users still have this package installed, so all
10900                    // we need to do is clear this user's data and save that
10901                    // it is uninstalled.
10902                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10903                    removeUser = user.getIdentifier();
10904                    appId = ps.appId;
10905                    mSettings.writePackageRestrictionsLPr(removeUser);
10906                }
10907            }
10908        }
10909
10910        if (removeUser >= 0) {
10911            // From above, we determined that we are deleting this only
10912            // for a single user.  Continue the work here.
10913            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10914            if (outInfo != null) {
10915                outInfo.removedPackage = packageName;
10916                outInfo.removedAppId = appId;
10917                outInfo.removedUsers = new int[] {removeUser};
10918            }
10919            mInstaller.clearUserData(packageName, removeUser);
10920            removeKeystoreDataIfNeeded(removeUser, appId);
10921            schedulePackageCleaning(packageName, removeUser, false);
10922            return true;
10923        }
10924
10925        if (dataOnly) {
10926            // Delete application data first
10927            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10928            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10929            return true;
10930        }
10931
10932        boolean ret = false;
10933        if (isSystemApp(ps)) {
10934            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10935            // When an updated system application is deleted we delete the existing resources as well and
10936            // fall back to existing code in system partition
10937            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10938                    flags, outInfo, writeSettings);
10939        } else {
10940            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10941            // Kill application pre-emptively especially for apps on sd.
10942            killApplication(packageName, ps.appId, "uninstall pkg");
10943            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10944                    allUserHandles, perUserInstalled,
10945                    outInfo, writeSettings);
10946        }
10947
10948        return ret;
10949    }
10950
10951    private final class ClearStorageConnection implements ServiceConnection {
10952        IMediaContainerService mContainerService;
10953
10954        @Override
10955        public void onServiceConnected(ComponentName name, IBinder service) {
10956            synchronized (this) {
10957                mContainerService = IMediaContainerService.Stub.asInterface(service);
10958                notifyAll();
10959            }
10960        }
10961
10962        @Override
10963        public void onServiceDisconnected(ComponentName name) {
10964        }
10965    }
10966
10967    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10968        final boolean mounted;
10969        if (Environment.isExternalStorageEmulated()) {
10970            mounted = true;
10971        } else {
10972            final String status = Environment.getExternalStorageState();
10973
10974            mounted = status.equals(Environment.MEDIA_MOUNTED)
10975                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10976        }
10977
10978        if (!mounted) {
10979            return;
10980        }
10981
10982        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10983        int[] users;
10984        if (userId == UserHandle.USER_ALL) {
10985            users = sUserManager.getUserIds();
10986        } else {
10987            users = new int[] { userId };
10988        }
10989        final ClearStorageConnection conn = new ClearStorageConnection();
10990        if (mContext.bindServiceAsUser(
10991                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10992            try {
10993                for (int curUser : users) {
10994                    long timeout = SystemClock.uptimeMillis() + 5000;
10995                    synchronized (conn) {
10996                        long now = SystemClock.uptimeMillis();
10997                        while (conn.mContainerService == null && now < timeout) {
10998                            try {
10999                                conn.wait(timeout - now);
11000                            } catch (InterruptedException e) {
11001                            }
11002                        }
11003                    }
11004                    if (conn.mContainerService == null) {
11005                        return;
11006                    }
11007
11008                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11009                    clearDirectory(conn.mContainerService,
11010                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11011                    if (allData) {
11012                        clearDirectory(conn.mContainerService,
11013                                userEnv.buildExternalStorageAppDataDirs(packageName));
11014                        clearDirectory(conn.mContainerService,
11015                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11016                    }
11017                }
11018            } finally {
11019                mContext.unbindService(conn);
11020            }
11021        }
11022    }
11023
11024    @Override
11025    public void clearApplicationUserData(final String packageName,
11026            final IPackageDataObserver observer, final int userId) {
11027        mContext.enforceCallingOrSelfPermission(
11028                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11029        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11030        // Queue up an async operation since the package deletion may take a little while.
11031        mHandler.post(new Runnable() {
11032            public void run() {
11033                mHandler.removeCallbacks(this);
11034                final boolean succeeded;
11035                synchronized (mInstallLock) {
11036                    succeeded = clearApplicationUserDataLI(packageName, userId);
11037                }
11038                clearExternalStorageDataSync(packageName, userId, true);
11039                if (succeeded) {
11040                    // invoke DeviceStorageMonitor's update method to clear any notifications
11041                    DeviceStorageMonitorInternal
11042                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11043                    if (dsm != null) {
11044                        dsm.checkMemory();
11045                    }
11046                }
11047                if(observer != null) {
11048                    try {
11049                        observer.onRemoveCompleted(packageName, succeeded);
11050                    } catch (RemoteException e) {
11051                        Log.i(TAG, "Observer no longer exists.");
11052                    }
11053                } //end if observer
11054            } //end run
11055        });
11056    }
11057
11058    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11059        if (packageName == null) {
11060            Slog.w(TAG, "Attempt to delete null packageName.");
11061            return false;
11062        }
11063        PackageParser.Package pkg;
11064        boolean dataOnly = false;
11065        final int appId;
11066        synchronized (mPackages) {
11067            pkg = mPackages.get(packageName);
11068            if (pkg == null) {
11069                dataOnly = true;
11070                PackageSetting ps = mSettings.mPackages.get(packageName);
11071                if ((ps == null) || (ps.pkg == null)) {
11072                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11073                    return false;
11074                }
11075                pkg = ps.pkg;
11076            }
11077            if (!dataOnly) {
11078                // need to check this only for fully installed applications
11079                if (pkg == null) {
11080                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11081                    return false;
11082                }
11083                final ApplicationInfo applicationInfo = pkg.applicationInfo;
11084                if (applicationInfo == null) {
11085                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11086                    return false;
11087                }
11088            }
11089            if (pkg != null && pkg.applicationInfo != null) {
11090                appId = pkg.applicationInfo.uid;
11091            } else {
11092                appId = -1;
11093            }
11094        }
11095        int retCode = mInstaller.clearUserData(packageName, userId);
11096        if (retCode < 0) {
11097            Slog.w(TAG, "Couldn't remove cache files for package: "
11098                    + packageName);
11099            return false;
11100        }
11101        removeKeystoreDataIfNeeded(userId, appId);
11102
11103        // Create a native library symlink only if we have native libraries
11104        // and if the native libraries are 32 bit libraries. We do not provide
11105        // this symlink for 64 bit libraries.
11106        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11107                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11108            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11109            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11110                Slog.w(TAG, "Failed linking native library dir");
11111                return false;
11112            }
11113        }
11114
11115        return true;
11116    }
11117
11118    /**
11119     * Remove entries from the keystore daemon. Will only remove it if the
11120     * {@code appId} is valid.
11121     */
11122    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11123        if (appId < 0) {
11124            return;
11125        }
11126
11127        final KeyStore keyStore = KeyStore.getInstance();
11128        if (keyStore != null) {
11129            if (userId == UserHandle.USER_ALL) {
11130                for (final int individual : sUserManager.getUserIds()) {
11131                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11132                }
11133            } else {
11134                keyStore.clearUid(UserHandle.getUid(userId, appId));
11135            }
11136        } else {
11137            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11138        }
11139    }
11140
11141    @Override
11142    public void deleteApplicationCacheFiles(final String packageName,
11143            final IPackageDataObserver observer) {
11144        mContext.enforceCallingOrSelfPermission(
11145                android.Manifest.permission.DELETE_CACHE_FILES, null);
11146        // Queue up an async operation since the package deletion may take a little while.
11147        final int userId = UserHandle.getCallingUserId();
11148        mHandler.post(new Runnable() {
11149            public void run() {
11150                mHandler.removeCallbacks(this);
11151                final boolean succeded;
11152                synchronized (mInstallLock) {
11153                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11154                }
11155                clearExternalStorageDataSync(packageName, userId, false);
11156                if(observer != null) {
11157                    try {
11158                        observer.onRemoveCompleted(packageName, succeded);
11159                    } catch (RemoteException e) {
11160                        Log.i(TAG, "Observer no longer exists.");
11161                    }
11162                } //end if observer
11163            } //end run
11164        });
11165    }
11166
11167    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11168        if (packageName == null) {
11169            Slog.w(TAG, "Attempt to delete null packageName.");
11170            return false;
11171        }
11172        PackageParser.Package p;
11173        synchronized (mPackages) {
11174            p = mPackages.get(packageName);
11175        }
11176        if (p == null) {
11177            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11178            return false;
11179        }
11180        final ApplicationInfo applicationInfo = p.applicationInfo;
11181        if (applicationInfo == null) {
11182            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11183            return false;
11184        }
11185        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11186        if (retCode < 0) {
11187            Slog.w(TAG, "Couldn't remove cache files for package: "
11188                       + packageName + " u" + userId);
11189            return false;
11190        }
11191        return true;
11192    }
11193
11194    @Override
11195    public void getPackageSizeInfo(final String packageName, int userHandle,
11196            final IPackageStatsObserver observer) {
11197        mContext.enforceCallingOrSelfPermission(
11198                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11199        if (packageName == null) {
11200            throw new IllegalArgumentException("Attempt to get size of null packageName");
11201        }
11202
11203        PackageStats stats = new PackageStats(packageName, userHandle);
11204
11205        /*
11206         * Queue up an async operation since the package measurement may take a
11207         * little while.
11208         */
11209        Message msg = mHandler.obtainMessage(INIT_COPY);
11210        msg.obj = new MeasureParams(stats, observer);
11211        mHandler.sendMessage(msg);
11212    }
11213
11214    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11215            PackageStats pStats) {
11216        if (packageName == null) {
11217            Slog.w(TAG, "Attempt to get size of null packageName.");
11218            return false;
11219        }
11220        PackageParser.Package p;
11221        boolean dataOnly = false;
11222        String libDirRoot = null;
11223        String asecPath = null;
11224        PackageSetting ps = null;
11225        synchronized (mPackages) {
11226            p = mPackages.get(packageName);
11227            ps = mSettings.mPackages.get(packageName);
11228            if(p == null) {
11229                dataOnly = true;
11230                if((ps == null) || (ps.pkg == null)) {
11231                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11232                    return false;
11233                }
11234                p = ps.pkg;
11235            }
11236            if (ps != null) {
11237                libDirRoot = ps.legacyNativeLibraryPathString;
11238            }
11239            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11240                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11241                if (secureContainerId != null) {
11242                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11243                }
11244            }
11245        }
11246        String publicSrcDir = null;
11247        if(!dataOnly) {
11248            final ApplicationInfo applicationInfo = p.applicationInfo;
11249            if (applicationInfo == null) {
11250                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11251                return false;
11252            }
11253            if (isForwardLocked(p)) {
11254                publicSrcDir = applicationInfo.getBaseResourcePath();
11255            }
11256        }
11257        // TODO: extend to measure size of split APKs
11258        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11259        // not just the first level.
11260        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11261        // just the primary.
11262        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11263        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11264                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11265        if (res < 0) {
11266            return false;
11267        }
11268
11269        // Fix-up for forward-locked applications in ASEC containers.
11270        if (!isExternal(p)) {
11271            pStats.codeSize += pStats.externalCodeSize;
11272            pStats.externalCodeSize = 0L;
11273        }
11274
11275        return true;
11276    }
11277
11278
11279    @Override
11280    public void addPackageToPreferred(String packageName) {
11281        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11282    }
11283
11284    @Override
11285    public void removePackageFromPreferred(String packageName) {
11286        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11287    }
11288
11289    @Override
11290    public List<PackageInfo> getPreferredPackages(int flags) {
11291        return new ArrayList<PackageInfo>();
11292    }
11293
11294    private int getUidTargetSdkVersionLockedLPr(int uid) {
11295        Object obj = mSettings.getUserIdLPr(uid);
11296        if (obj instanceof SharedUserSetting) {
11297            final SharedUserSetting sus = (SharedUserSetting) obj;
11298            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11299            final Iterator<PackageSetting> it = sus.packages.iterator();
11300            while (it.hasNext()) {
11301                final PackageSetting ps = it.next();
11302                if (ps.pkg != null) {
11303                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11304                    if (v < vers) vers = v;
11305                }
11306            }
11307            return vers;
11308        } else if (obj instanceof PackageSetting) {
11309            final PackageSetting ps = (PackageSetting) obj;
11310            if (ps.pkg != null) {
11311                return ps.pkg.applicationInfo.targetSdkVersion;
11312            }
11313        }
11314        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11315    }
11316
11317    @Override
11318    public void addPreferredActivity(IntentFilter filter, int match,
11319            ComponentName[] set, ComponentName activity, int userId) {
11320        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11321                "Adding preferred");
11322    }
11323
11324    private void addPreferredActivityInternal(IntentFilter filter, int match,
11325            ComponentName[] set, ComponentName activity, boolean always, int userId,
11326            String opname) {
11327        // writer
11328        int callingUid = Binder.getCallingUid();
11329        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11330        if (filter.countActions() == 0) {
11331            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11332            return;
11333        }
11334        synchronized (mPackages) {
11335            if (mContext.checkCallingOrSelfPermission(
11336                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11337                    != PackageManager.PERMISSION_GRANTED) {
11338                if (getUidTargetSdkVersionLockedLPr(callingUid)
11339                        < Build.VERSION_CODES.FROYO) {
11340                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11341                            + callingUid);
11342                    return;
11343                }
11344                mContext.enforceCallingOrSelfPermission(
11345                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11346            }
11347
11348            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11349            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11350                    + userId + ":");
11351            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11352            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11353            mSettings.writePackageRestrictionsLPr(userId);
11354        }
11355    }
11356
11357    @Override
11358    public void replacePreferredActivity(IntentFilter filter, int match,
11359            ComponentName[] set, ComponentName activity, int userId) {
11360        if (filter.countActions() != 1) {
11361            throw new IllegalArgumentException(
11362                    "replacePreferredActivity expects filter to have only 1 action.");
11363        }
11364        if (filter.countDataAuthorities() != 0
11365                || filter.countDataPaths() != 0
11366                || filter.countDataSchemes() > 1
11367                || filter.countDataTypes() != 0) {
11368            throw new IllegalArgumentException(
11369                    "replacePreferredActivity expects filter to have no data authorities, " +
11370                    "paths, or types; and at most one scheme.");
11371        }
11372
11373        final int callingUid = Binder.getCallingUid();
11374        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11375        synchronized (mPackages) {
11376            if (mContext.checkCallingOrSelfPermission(
11377                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11378                    != PackageManager.PERMISSION_GRANTED) {
11379                if (getUidTargetSdkVersionLockedLPr(callingUid)
11380                        < Build.VERSION_CODES.FROYO) {
11381                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11382                            + Binder.getCallingUid());
11383                    return;
11384                }
11385                mContext.enforceCallingOrSelfPermission(
11386                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11387            }
11388
11389            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11390            if (pir != null) {
11391                // Get all of the existing entries that exactly match this filter.
11392                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11393                if (existing != null && existing.size() == 1) {
11394                    PreferredActivity cur = existing.get(0);
11395                    if (DEBUG_PREFERRED) {
11396                        Slog.i(TAG, "Checking replace of preferred:");
11397                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11398                        if (!cur.mPref.mAlways) {
11399                            Slog.i(TAG, "  -- CUR; not mAlways!");
11400                        } else {
11401                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11402                            Slog.i(TAG, "  -- CUR: mSet="
11403                                    + Arrays.toString(cur.mPref.mSetComponents));
11404                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11405                            Slog.i(TAG, "  -- NEW: mMatch="
11406                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11407                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11408                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11409                        }
11410                    }
11411                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11412                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11413                            && cur.mPref.sameSet(set)) {
11414                        if (DEBUG_PREFERRED) {
11415                            Slog.i(TAG, "Replacing with same preferred activity "
11416                                    + cur.mPref.mShortComponent + " for user "
11417                                    + userId + ":");
11418                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11419                        } else {
11420                            Slog.i(TAG, "Replacing with same preferred activity "
11421                                    + cur.mPref.mShortComponent + " for user "
11422                                    + userId);
11423                        }
11424                        return;
11425                    }
11426                }
11427
11428                if (existing != null) {
11429                    if (DEBUG_PREFERRED) {
11430                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11431                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11432                    }
11433                    for (int i = 0; i < existing.size(); i++) {
11434                        PreferredActivity pa = existing.get(i);
11435                        if (DEBUG_PREFERRED) {
11436                            Slog.i(TAG, "Removing existing preferred activity "
11437                                    + pa.mPref.mComponent + ":");
11438                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11439                        }
11440                        pir.removeFilter(pa);
11441                    }
11442                }
11443            }
11444            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11445                    "Replacing preferred");
11446        }
11447    }
11448
11449    @Override
11450    public void clearPackagePreferredActivities(String packageName) {
11451        final int uid = Binder.getCallingUid();
11452        // writer
11453        synchronized (mPackages) {
11454            PackageParser.Package pkg = mPackages.get(packageName);
11455            if (pkg == null || pkg.applicationInfo.uid != uid) {
11456                if (mContext.checkCallingOrSelfPermission(
11457                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11458                        != PackageManager.PERMISSION_GRANTED) {
11459                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11460                            < Build.VERSION_CODES.FROYO) {
11461                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11462                                + Binder.getCallingUid());
11463                        return;
11464                    }
11465                    mContext.enforceCallingOrSelfPermission(
11466                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11467                }
11468            }
11469
11470            int user = UserHandle.getCallingUserId();
11471            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11472                mSettings.writePackageRestrictionsLPr(user);
11473                scheduleWriteSettingsLocked();
11474            }
11475        }
11476    }
11477
11478    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11479    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11480        ArrayList<PreferredActivity> removed = null;
11481        boolean changed = false;
11482        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11483            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11484            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11485            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11486                continue;
11487            }
11488            Iterator<PreferredActivity> it = pir.filterIterator();
11489            while (it.hasNext()) {
11490                PreferredActivity pa = it.next();
11491                // Mark entry for removal only if it matches the package name
11492                // and the entry is of type "always".
11493                if (packageName == null ||
11494                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11495                                && pa.mPref.mAlways)) {
11496                    if (removed == null) {
11497                        removed = new ArrayList<PreferredActivity>();
11498                    }
11499                    removed.add(pa);
11500                }
11501            }
11502            if (removed != null) {
11503                for (int j=0; j<removed.size(); j++) {
11504                    PreferredActivity pa = removed.get(j);
11505                    pir.removeFilter(pa);
11506                }
11507                changed = true;
11508            }
11509        }
11510        return changed;
11511    }
11512
11513    @Override
11514    public void resetPreferredActivities(int userId) {
11515        mContext.enforceCallingOrSelfPermission(
11516                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11517        // writer
11518        synchronized (mPackages) {
11519            int user = UserHandle.getCallingUserId();
11520            clearPackagePreferredActivitiesLPw(null, user);
11521            mSettings.readDefaultPreferredAppsLPw(this, user);
11522            mSettings.writePackageRestrictionsLPr(user);
11523            scheduleWriteSettingsLocked();
11524        }
11525    }
11526
11527    @Override
11528    public int getPreferredActivities(List<IntentFilter> outFilters,
11529            List<ComponentName> outActivities, String packageName) {
11530
11531        int num = 0;
11532        final int userId = UserHandle.getCallingUserId();
11533        // reader
11534        synchronized (mPackages) {
11535            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11536            if (pir != null) {
11537                final Iterator<PreferredActivity> it = pir.filterIterator();
11538                while (it.hasNext()) {
11539                    final PreferredActivity pa = it.next();
11540                    if (packageName == null
11541                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11542                                    && pa.mPref.mAlways)) {
11543                        if (outFilters != null) {
11544                            outFilters.add(new IntentFilter(pa));
11545                        }
11546                        if (outActivities != null) {
11547                            outActivities.add(pa.mPref.mComponent);
11548                        }
11549                    }
11550                }
11551            }
11552        }
11553
11554        return num;
11555    }
11556
11557    @Override
11558    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11559            int userId) {
11560        int callingUid = Binder.getCallingUid();
11561        if (callingUid != Process.SYSTEM_UID) {
11562            throw new SecurityException(
11563                    "addPersistentPreferredActivity can only be run by the system");
11564        }
11565        if (filter.countActions() == 0) {
11566            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11567            return;
11568        }
11569        synchronized (mPackages) {
11570            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11571                    " :");
11572            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11573            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11574                    new PersistentPreferredActivity(filter, activity));
11575            mSettings.writePackageRestrictionsLPr(userId);
11576        }
11577    }
11578
11579    @Override
11580    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11581        int callingUid = Binder.getCallingUid();
11582        if (callingUid != Process.SYSTEM_UID) {
11583            throw new SecurityException(
11584                    "clearPackagePersistentPreferredActivities can only be run by the system");
11585        }
11586        ArrayList<PersistentPreferredActivity> removed = null;
11587        boolean changed = false;
11588        synchronized (mPackages) {
11589            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11590                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11591                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11592                        .valueAt(i);
11593                if (userId != thisUserId) {
11594                    continue;
11595                }
11596                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11597                while (it.hasNext()) {
11598                    PersistentPreferredActivity ppa = it.next();
11599                    // Mark entry for removal only if it matches the package name.
11600                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11601                        if (removed == null) {
11602                            removed = new ArrayList<PersistentPreferredActivity>();
11603                        }
11604                        removed.add(ppa);
11605                    }
11606                }
11607                if (removed != null) {
11608                    for (int j=0; j<removed.size(); j++) {
11609                        PersistentPreferredActivity ppa = removed.get(j);
11610                        ppir.removeFilter(ppa);
11611                    }
11612                    changed = true;
11613                }
11614            }
11615
11616            if (changed) {
11617                mSettings.writePackageRestrictionsLPr(userId);
11618            }
11619        }
11620    }
11621
11622    @Override
11623    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11624            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11625        mContext.enforceCallingOrSelfPermission(
11626                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11627        int callingUid = Binder.getCallingUid();
11628        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11629        if (intentFilter.countActions() == 0) {
11630            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11631            return;
11632        }
11633        synchronized (mPackages) {
11634            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11635                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11636            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11637            mSettings.writePackageRestrictionsLPr(sourceUserId);
11638        }
11639    }
11640
11641    @Override
11642    public void addCrossProfileIntentsForPackage(String packageName,
11643            int sourceUserId, int targetUserId) {
11644        mContext.enforceCallingOrSelfPermission(
11645                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11646        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11647        mSettings.writePackageRestrictionsLPr(sourceUserId);
11648    }
11649
11650    @Override
11651    public void removeCrossProfileIntentsForPackage(String packageName,
11652            int sourceUserId, int targetUserId) {
11653        mContext.enforceCallingOrSelfPermission(
11654                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11655        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11656        mSettings.writePackageRestrictionsLPr(sourceUserId);
11657    }
11658
11659    @Override
11660    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11661            int ownerUserId) {
11662        mContext.enforceCallingOrSelfPermission(
11663                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11664        int callingUid = Binder.getCallingUid();
11665        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11666        int callingUserId = UserHandle.getUserId(callingUid);
11667        synchronized (mPackages) {
11668            CrossProfileIntentResolver resolver =
11669                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11670            HashSet<CrossProfileIntentFilter> set =
11671                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11672            for (CrossProfileIntentFilter filter : set) {
11673                if (filter.getOwnerPackage().equals(ownerPackage)
11674                        && filter.getOwnerUserId() == callingUserId) {
11675                    resolver.removeFilter(filter);
11676                }
11677            }
11678            mSettings.writePackageRestrictionsLPr(sourceUserId);
11679        }
11680    }
11681
11682    // Enforcing that callingUid is owning pkg on userId
11683    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11684        // The system owns everything.
11685        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11686            return;
11687        }
11688        int callingUserId = UserHandle.getUserId(callingUid);
11689        if (callingUserId != userId) {
11690            throw new SecurityException("calling uid " + callingUid
11691                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11692                    + callingUserId);
11693        }
11694        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11695        if (pi == null) {
11696            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11697                    + callingUserId);
11698        }
11699        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11700            throw new SecurityException("Calling uid " + callingUid
11701                    + " does not own package " + pkg);
11702        }
11703    }
11704
11705    @Override
11706    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11707        Intent intent = new Intent(Intent.ACTION_MAIN);
11708        intent.addCategory(Intent.CATEGORY_HOME);
11709
11710        final int callingUserId = UserHandle.getCallingUserId();
11711        List<ResolveInfo> list = queryIntentActivities(intent, null,
11712                PackageManager.GET_META_DATA, callingUserId);
11713        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11714                true, false, false, callingUserId);
11715
11716        allHomeCandidates.clear();
11717        if (list != null) {
11718            for (ResolveInfo ri : list) {
11719                allHomeCandidates.add(ri);
11720            }
11721        }
11722        return (preferred == null || preferred.activityInfo == null)
11723                ? null
11724                : new ComponentName(preferred.activityInfo.packageName,
11725                        preferred.activityInfo.name);
11726    }
11727
11728    @Override
11729    public void setApplicationEnabledSetting(String appPackageName,
11730            int newState, int flags, int userId, String callingPackage) {
11731        if (!sUserManager.exists(userId)) return;
11732        if (callingPackage == null) {
11733            callingPackage = Integer.toString(Binder.getCallingUid());
11734        }
11735        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11736    }
11737
11738    @Override
11739    public void setComponentEnabledSetting(ComponentName componentName,
11740            int newState, int flags, int userId) {
11741        if (!sUserManager.exists(userId)) return;
11742        setEnabledSetting(componentName.getPackageName(),
11743                componentName.getClassName(), newState, flags, userId, null);
11744    }
11745
11746    private void setEnabledSetting(final String packageName, String className, int newState,
11747            final int flags, int userId, String callingPackage) {
11748        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11749              || newState == COMPONENT_ENABLED_STATE_ENABLED
11750              || newState == COMPONENT_ENABLED_STATE_DISABLED
11751              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11752              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11753            throw new IllegalArgumentException("Invalid new component state: "
11754                    + newState);
11755        }
11756        PackageSetting pkgSetting;
11757        final int uid = Binder.getCallingUid();
11758        final int permission = mContext.checkCallingOrSelfPermission(
11759                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11760        enforceCrossUserPermission(uid, userId, false, "set enabled");
11761        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11762        boolean sendNow = false;
11763        boolean isApp = (className == null);
11764        String componentName = isApp ? packageName : className;
11765        int packageUid = -1;
11766        ArrayList<String> components;
11767
11768        // writer
11769        synchronized (mPackages) {
11770            pkgSetting = mSettings.mPackages.get(packageName);
11771            if (pkgSetting == null) {
11772                if (className == null) {
11773                    throw new IllegalArgumentException(
11774                            "Unknown package: " + packageName);
11775                }
11776                throw new IllegalArgumentException(
11777                        "Unknown component: " + packageName
11778                        + "/" + className);
11779            }
11780            // Allow root and verify that userId is not being specified by a different user
11781            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11782                throw new SecurityException(
11783                        "Permission Denial: attempt to change component state from pid="
11784                        + Binder.getCallingPid()
11785                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11786            }
11787            if (className == null) {
11788                // We're dealing with an application/package level state change
11789                if (pkgSetting.getEnabled(userId) == newState) {
11790                    // Nothing to do
11791                    return;
11792                }
11793                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11794                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11795                    // Don't care about who enables an app.
11796                    callingPackage = null;
11797                }
11798                pkgSetting.setEnabled(newState, userId, callingPackage);
11799                // pkgSetting.pkg.mSetEnabled = newState;
11800            } else {
11801                // We're dealing with a component level state change
11802                // First, verify that this is a valid class name.
11803                PackageParser.Package pkg = pkgSetting.pkg;
11804                if (pkg == null || !pkg.hasComponentClassName(className)) {
11805                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11806                        throw new IllegalArgumentException("Component class " + className
11807                                + " does not exist in " + packageName);
11808                    } else {
11809                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11810                                + className + " does not exist in " + packageName);
11811                    }
11812                }
11813                switch (newState) {
11814                case COMPONENT_ENABLED_STATE_ENABLED:
11815                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11816                        return;
11817                    }
11818                    break;
11819                case COMPONENT_ENABLED_STATE_DISABLED:
11820                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11821                        return;
11822                    }
11823                    break;
11824                case COMPONENT_ENABLED_STATE_DEFAULT:
11825                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11826                        return;
11827                    }
11828                    break;
11829                default:
11830                    Slog.e(TAG, "Invalid new component state: " + newState);
11831                    return;
11832                }
11833            }
11834            mSettings.writePackageRestrictionsLPr(userId);
11835            components = mPendingBroadcasts.get(userId, packageName);
11836            final boolean newPackage = components == null;
11837            if (newPackage) {
11838                components = new ArrayList<String>();
11839            }
11840            if (!components.contains(componentName)) {
11841                components.add(componentName);
11842            }
11843            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11844                sendNow = true;
11845                // Purge entry from pending broadcast list if another one exists already
11846                // since we are sending one right away.
11847                mPendingBroadcasts.remove(userId, packageName);
11848            } else {
11849                if (newPackage) {
11850                    mPendingBroadcasts.put(userId, packageName, components);
11851                }
11852                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11853                    // Schedule a message
11854                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11855                }
11856            }
11857        }
11858
11859        long callingId = Binder.clearCallingIdentity();
11860        try {
11861            if (sendNow) {
11862                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11863                sendPackageChangedBroadcast(packageName,
11864                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11865            }
11866        } finally {
11867            Binder.restoreCallingIdentity(callingId);
11868        }
11869    }
11870
11871    private void sendPackageChangedBroadcast(String packageName,
11872            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11873        if (DEBUG_INSTALL)
11874            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11875                    + componentNames);
11876        Bundle extras = new Bundle(4);
11877        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11878        String nameList[] = new String[componentNames.size()];
11879        componentNames.toArray(nameList);
11880        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11881        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11882        extras.putInt(Intent.EXTRA_UID, packageUid);
11883        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11884                new int[] {UserHandle.getUserId(packageUid)});
11885    }
11886
11887    @Override
11888    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11889        if (!sUserManager.exists(userId)) return;
11890        final int uid = Binder.getCallingUid();
11891        final int permission = mContext.checkCallingOrSelfPermission(
11892                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11893        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11894        enforceCrossUserPermission(uid, userId, true, "stop package");
11895        // writer
11896        synchronized (mPackages) {
11897            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11898                    uid, userId)) {
11899                scheduleWritePackageRestrictionsLocked(userId);
11900            }
11901        }
11902    }
11903
11904    @Override
11905    public String getInstallerPackageName(String packageName) {
11906        // reader
11907        synchronized (mPackages) {
11908            return mSettings.getInstallerPackageNameLPr(packageName);
11909        }
11910    }
11911
11912    @Override
11913    public int getApplicationEnabledSetting(String packageName, int userId) {
11914        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11915        int uid = Binder.getCallingUid();
11916        enforceCrossUserPermission(uid, userId, false, "get enabled");
11917        // reader
11918        synchronized (mPackages) {
11919            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11920        }
11921    }
11922
11923    @Override
11924    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11925        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11926        int uid = Binder.getCallingUid();
11927        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11928        // reader
11929        synchronized (mPackages) {
11930            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11931        }
11932    }
11933
11934    @Override
11935    public void enterSafeMode() {
11936        enforceSystemOrRoot("Only the system can request entering safe mode");
11937
11938        if (!mSystemReady) {
11939            mSafeMode = true;
11940        }
11941    }
11942
11943    @Override
11944    public void systemReady() {
11945        mSystemReady = true;
11946
11947        // Read the compatibilty setting when the system is ready.
11948        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11949                mContext.getContentResolver(),
11950                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11951        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11952        if (DEBUG_SETTINGS) {
11953            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11954        }
11955
11956        synchronized (mPackages) {
11957            // Verify that all of the preferred activity components actually
11958            // exist.  It is possible for applications to be updated and at
11959            // that point remove a previously declared activity component that
11960            // had been set as a preferred activity.  We try to clean this up
11961            // the next time we encounter that preferred activity, but it is
11962            // possible for the user flow to never be able to return to that
11963            // situation so here we do a sanity check to make sure we haven't
11964            // left any junk around.
11965            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11966            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11967                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11968                removed.clear();
11969                for (PreferredActivity pa : pir.filterSet()) {
11970                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11971                        removed.add(pa);
11972                    }
11973                }
11974                if (removed.size() > 0) {
11975                    for (int r=0; r<removed.size(); r++) {
11976                        PreferredActivity pa = removed.get(r);
11977                        Slog.w(TAG, "Removing dangling preferred activity: "
11978                                + pa.mPref.mComponent);
11979                        pir.removeFilter(pa);
11980                    }
11981                    mSettings.writePackageRestrictionsLPr(
11982                            mSettings.mPreferredActivities.keyAt(i));
11983                }
11984            }
11985        }
11986        sUserManager.systemReady();
11987
11988        // Kick off any messages waiting for system ready
11989        if (mPostSystemReadyMessages != null) {
11990            for (Message msg : mPostSystemReadyMessages) {
11991                msg.sendToTarget();
11992            }
11993            mPostSystemReadyMessages = null;
11994        }
11995    }
11996
11997    @Override
11998    public boolean isSafeMode() {
11999        return mSafeMode;
12000    }
12001
12002    @Override
12003    public boolean hasSystemUidErrors() {
12004        return mHasSystemUidErrors;
12005    }
12006
12007    static String arrayToString(int[] array) {
12008        StringBuffer buf = new StringBuffer(128);
12009        buf.append('[');
12010        if (array != null) {
12011            for (int i=0; i<array.length; i++) {
12012                if (i > 0) buf.append(", ");
12013                buf.append(array[i]);
12014            }
12015        }
12016        buf.append(']');
12017        return buf.toString();
12018    }
12019
12020    static class DumpState {
12021        public static final int DUMP_LIBS = 1 << 0;
12022        public static final int DUMP_FEATURES = 1 << 1;
12023        public static final int DUMP_RESOLVERS = 1 << 2;
12024        public static final int DUMP_PERMISSIONS = 1 << 3;
12025        public static final int DUMP_PACKAGES = 1 << 4;
12026        public static final int DUMP_SHARED_USERS = 1 << 5;
12027        public static final int DUMP_MESSAGES = 1 << 6;
12028        public static final int DUMP_PROVIDERS = 1 << 7;
12029        public static final int DUMP_VERIFIERS = 1 << 8;
12030        public static final int DUMP_PREFERRED = 1 << 9;
12031        public static final int DUMP_PREFERRED_XML = 1 << 10;
12032        public static final int DUMP_KEYSETS = 1 << 11;
12033        public static final int DUMP_VERSION = 1 << 12;
12034        public static final int DUMP_INSTALLS = 1 << 13;
12035
12036        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12037
12038        private int mTypes;
12039
12040        private int mOptions;
12041
12042        private boolean mTitlePrinted;
12043
12044        private SharedUserSetting mSharedUser;
12045
12046        public boolean isDumping(int type) {
12047            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12048                return true;
12049            }
12050
12051            return (mTypes & type) != 0;
12052        }
12053
12054        public void setDump(int type) {
12055            mTypes |= type;
12056        }
12057
12058        public boolean isOptionEnabled(int option) {
12059            return (mOptions & option) != 0;
12060        }
12061
12062        public void setOptionEnabled(int option) {
12063            mOptions |= option;
12064        }
12065
12066        public boolean onTitlePrinted() {
12067            final boolean printed = mTitlePrinted;
12068            mTitlePrinted = true;
12069            return printed;
12070        }
12071
12072        public boolean getTitlePrinted() {
12073            return mTitlePrinted;
12074        }
12075
12076        public void setTitlePrinted(boolean enabled) {
12077            mTitlePrinted = enabled;
12078        }
12079
12080        public SharedUserSetting getSharedUser() {
12081            return mSharedUser;
12082        }
12083
12084        public void setSharedUser(SharedUserSetting user) {
12085            mSharedUser = user;
12086        }
12087    }
12088
12089    @Override
12090    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12091        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12092                != PackageManager.PERMISSION_GRANTED) {
12093            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12094                    + Binder.getCallingPid()
12095                    + ", uid=" + Binder.getCallingUid()
12096                    + " without permission "
12097                    + android.Manifest.permission.DUMP);
12098            return;
12099        }
12100
12101        DumpState dumpState = new DumpState();
12102        boolean fullPreferred = false;
12103        boolean checkin = false;
12104
12105        String packageName = null;
12106
12107        int opti = 0;
12108        while (opti < args.length) {
12109            String opt = args[opti];
12110            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12111                break;
12112            }
12113            opti++;
12114            if ("-a".equals(opt)) {
12115                // Right now we only know how to print all.
12116            } else if ("-h".equals(opt)) {
12117                pw.println("Package manager dump options:");
12118                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12119                pw.println("    --checkin: dump for a checkin");
12120                pw.println("    -f: print details of intent filters");
12121                pw.println("    -h: print this help");
12122                pw.println("  cmd may be one of:");
12123                pw.println("    l[ibraries]: list known shared libraries");
12124                pw.println("    f[ibraries]: list device features");
12125                pw.println("    k[eysets]: print known keysets");
12126                pw.println("    r[esolvers]: dump intent resolvers");
12127                pw.println("    perm[issions]: dump permissions");
12128                pw.println("    pref[erred]: print preferred package settings");
12129                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12130                pw.println("    prov[iders]: dump content providers");
12131                pw.println("    p[ackages]: dump installed packages");
12132                pw.println("    s[hared-users]: dump shared user IDs");
12133                pw.println("    m[essages]: print collected runtime messages");
12134                pw.println("    v[erifiers]: print package verifier info");
12135                pw.println("    version: print database version info");
12136                pw.println("    write: write current settings now");
12137                pw.println("    <package.name>: info about given package");
12138                pw.println("    installs: details about install sessions");
12139                return;
12140            } else if ("--checkin".equals(opt)) {
12141                checkin = true;
12142            } else if ("-f".equals(opt)) {
12143                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12144            } else {
12145                pw.println("Unknown argument: " + opt + "; use -h for help");
12146            }
12147        }
12148
12149        // Is the caller requesting to dump a particular piece of data?
12150        if (opti < args.length) {
12151            String cmd = args[opti];
12152            opti++;
12153            // Is this a package name?
12154            if ("android".equals(cmd) || cmd.contains(".")) {
12155                packageName = cmd;
12156                // When dumping a single package, we always dump all of its
12157                // filter information since the amount of data will be reasonable.
12158                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12159            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12160                dumpState.setDump(DumpState.DUMP_LIBS);
12161            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12162                dumpState.setDump(DumpState.DUMP_FEATURES);
12163            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12164                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12165            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12166                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12167            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12168                dumpState.setDump(DumpState.DUMP_PREFERRED);
12169            } else if ("preferred-xml".equals(cmd)) {
12170                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12171                if (opti < args.length && "--full".equals(args[opti])) {
12172                    fullPreferred = true;
12173                    opti++;
12174                }
12175            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12176                dumpState.setDump(DumpState.DUMP_PACKAGES);
12177            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12178                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12179            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12181            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_MESSAGES);
12183            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12185            } else if ("version".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_VERSION);
12187            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12188                dumpState.setDump(DumpState.DUMP_KEYSETS);
12189            } else if ("write".equals(cmd)) {
12190                synchronized (mPackages) {
12191                    mSettings.writeLPr();
12192                    pw.println("Settings written.");
12193                    return;
12194                }
12195            } else if ("installs".equals(cmd)) {
12196                dumpState.setDump(DumpState.DUMP_INSTALLS);
12197            }
12198        }
12199
12200        if (checkin) {
12201            pw.println("vers,1");
12202        }
12203
12204        // reader
12205        synchronized (mPackages) {
12206            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12207                if (!checkin) {
12208                    if (dumpState.onTitlePrinted())
12209                        pw.println();
12210                    pw.println("Database versions:");
12211                    pw.print("  SDK Version:");
12212                    pw.print(" internal=");
12213                    pw.print(mSettings.mInternalSdkPlatform);
12214                    pw.print(" external=");
12215                    pw.println(mSettings.mExternalSdkPlatform);
12216                    pw.print("  DB Version:");
12217                    pw.print(" internal=");
12218                    pw.print(mSettings.mInternalDatabaseVersion);
12219                    pw.print(" external=");
12220                    pw.println(mSettings.mExternalDatabaseVersion);
12221                }
12222            }
12223
12224            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12225                if (!checkin) {
12226                    if (dumpState.onTitlePrinted())
12227                        pw.println();
12228                    pw.println("Verifiers:");
12229                    pw.print("  Required: ");
12230                    pw.print(mRequiredVerifierPackage);
12231                    pw.print(" (uid=");
12232                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12233                    pw.println(")");
12234                } else if (mRequiredVerifierPackage != null) {
12235                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12236                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12237                }
12238            }
12239
12240            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12241                boolean printedHeader = false;
12242                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12243                while (it.hasNext()) {
12244                    String name = it.next();
12245                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12246                    if (!checkin) {
12247                        if (!printedHeader) {
12248                            if (dumpState.onTitlePrinted())
12249                                pw.println();
12250                            pw.println("Libraries:");
12251                            printedHeader = true;
12252                        }
12253                        pw.print("  ");
12254                    } else {
12255                        pw.print("lib,");
12256                    }
12257                    pw.print(name);
12258                    if (!checkin) {
12259                        pw.print(" -> ");
12260                    }
12261                    if (ent.path != null) {
12262                        if (!checkin) {
12263                            pw.print("(jar) ");
12264                            pw.print(ent.path);
12265                        } else {
12266                            pw.print(",jar,");
12267                            pw.print(ent.path);
12268                        }
12269                    } else {
12270                        if (!checkin) {
12271                            pw.print("(apk) ");
12272                            pw.print(ent.apk);
12273                        } else {
12274                            pw.print(",apk,");
12275                            pw.print(ent.apk);
12276                        }
12277                    }
12278                    pw.println();
12279                }
12280            }
12281
12282            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12283                if (dumpState.onTitlePrinted())
12284                    pw.println();
12285                if (!checkin) {
12286                    pw.println("Features:");
12287                }
12288                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12289                while (it.hasNext()) {
12290                    String name = it.next();
12291                    if (!checkin) {
12292                        pw.print("  ");
12293                    } else {
12294                        pw.print("feat,");
12295                    }
12296                    pw.println(name);
12297                }
12298            }
12299
12300            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12301                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12302                        : "Activity Resolver Table:", "  ", packageName,
12303                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12304                    dumpState.setTitlePrinted(true);
12305                }
12306                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12307                        : "Receiver Resolver Table:", "  ", packageName,
12308                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12309                    dumpState.setTitlePrinted(true);
12310                }
12311                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12312                        : "Service Resolver Table:", "  ", packageName,
12313                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12314                    dumpState.setTitlePrinted(true);
12315                }
12316                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12317                        : "Provider Resolver Table:", "  ", packageName,
12318                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12319                    dumpState.setTitlePrinted(true);
12320                }
12321            }
12322
12323            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12324                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12325                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12326                    int user = mSettings.mPreferredActivities.keyAt(i);
12327                    if (pir.dump(pw,
12328                            dumpState.getTitlePrinted()
12329                                ? "\nPreferred Activities User " + user + ":"
12330                                : "Preferred Activities User " + user + ":", "  ",
12331                            packageName, true)) {
12332                        dumpState.setTitlePrinted(true);
12333                    }
12334                }
12335            }
12336
12337            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12338                pw.flush();
12339                FileOutputStream fout = new FileOutputStream(fd);
12340                BufferedOutputStream str = new BufferedOutputStream(fout);
12341                XmlSerializer serializer = new FastXmlSerializer();
12342                try {
12343                    serializer.setOutput(str, "utf-8");
12344                    serializer.startDocument(null, true);
12345                    serializer.setFeature(
12346                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12347                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12348                    serializer.endDocument();
12349                    serializer.flush();
12350                } catch (IllegalArgumentException e) {
12351                    pw.println("Failed writing: " + e);
12352                } catch (IllegalStateException e) {
12353                    pw.println("Failed writing: " + e);
12354                } catch (IOException e) {
12355                    pw.println("Failed writing: " + e);
12356                }
12357            }
12358
12359            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12360                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12361                if (packageName == null) {
12362                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12363                        if (iperm == 0) {
12364                            if (dumpState.onTitlePrinted())
12365                                pw.println();
12366                            pw.println("AppOp Permissions:");
12367                        }
12368                        pw.print("  AppOp Permission ");
12369                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12370                        pw.println(":");
12371                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12372                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12373                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12374                        }
12375                    }
12376                }
12377            }
12378
12379            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12380                boolean printedSomething = false;
12381                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12382                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12383                        continue;
12384                    }
12385                    if (!printedSomething) {
12386                        if (dumpState.onTitlePrinted())
12387                            pw.println();
12388                        pw.println("Registered ContentProviders:");
12389                        printedSomething = true;
12390                    }
12391                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12392                    pw.print("    "); pw.println(p.toString());
12393                }
12394                printedSomething = false;
12395                for (Map.Entry<String, PackageParser.Provider> entry :
12396                        mProvidersByAuthority.entrySet()) {
12397                    PackageParser.Provider p = entry.getValue();
12398                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12399                        continue;
12400                    }
12401                    if (!printedSomething) {
12402                        if (dumpState.onTitlePrinted())
12403                            pw.println();
12404                        pw.println("ContentProvider Authorities:");
12405                        printedSomething = true;
12406                    }
12407                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12408                    pw.print("    "); pw.println(p.toString());
12409                    if (p.info != null && p.info.applicationInfo != null) {
12410                        final String appInfo = p.info.applicationInfo.toString();
12411                        pw.print("      applicationInfo="); pw.println(appInfo);
12412                    }
12413                }
12414            }
12415
12416            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12417                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12418            }
12419
12420            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12421                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12422            }
12423
12424            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12425                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12426            }
12427
12428            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12429                if (dumpState.onTitlePrinted()) pw.println();
12430                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12431            }
12432
12433            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12434                if (dumpState.onTitlePrinted()) pw.println();
12435                mSettings.dumpReadMessagesLPr(pw, dumpState);
12436
12437                pw.println();
12438                pw.println("Package warning messages:");
12439                final File fname = getSettingsProblemFile();
12440                FileInputStream in = null;
12441                try {
12442                    in = new FileInputStream(fname);
12443                    final int avail = in.available();
12444                    final byte[] data = new byte[avail];
12445                    in.read(data);
12446                    pw.print(new String(data));
12447                } catch (FileNotFoundException e) {
12448                } catch (IOException e) {
12449                } finally {
12450                    if (in != null) {
12451                        try {
12452                            in.close();
12453                        } catch (IOException e) {
12454                        }
12455                    }
12456                }
12457            }
12458        }
12459    }
12460
12461    // ------- apps on sdcard specific code -------
12462    static final boolean DEBUG_SD_INSTALL = false;
12463
12464    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12465
12466    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12467
12468    private boolean mMediaMounted = false;
12469
12470    static String getEncryptKey() {
12471        try {
12472            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12473                    SD_ENCRYPTION_KEYSTORE_NAME);
12474            if (sdEncKey == null) {
12475                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12476                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12477                if (sdEncKey == null) {
12478                    Slog.e(TAG, "Failed to create encryption keys");
12479                    return null;
12480                }
12481            }
12482            return sdEncKey;
12483        } catch (NoSuchAlgorithmException nsae) {
12484            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12485            return null;
12486        } catch (IOException ioe) {
12487            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12488            return null;
12489        }
12490    }
12491
12492    /*
12493     * Update media status on PackageManager.
12494     */
12495    @Override
12496    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12497        int callingUid = Binder.getCallingUid();
12498        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12499            throw new SecurityException("Media status can only be updated by the system");
12500        }
12501        // reader; this apparently protects mMediaMounted, but should probably
12502        // be a different lock in that case.
12503        synchronized (mPackages) {
12504            Log.i(TAG, "Updating external media status from "
12505                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12506                    + (mediaStatus ? "mounted" : "unmounted"));
12507            if (DEBUG_SD_INSTALL)
12508                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12509                        + ", mMediaMounted=" + mMediaMounted);
12510            if (mediaStatus == mMediaMounted) {
12511                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12512                        : 0, -1);
12513                mHandler.sendMessage(msg);
12514                return;
12515            }
12516            mMediaMounted = mediaStatus;
12517        }
12518        // Queue up an async operation since the package installation may take a
12519        // little while.
12520        mHandler.post(new Runnable() {
12521            public void run() {
12522                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12523            }
12524        });
12525    }
12526
12527    /**
12528     * Called by MountService when the initial ASECs to scan are available.
12529     * Should block until all the ASEC containers are finished being scanned.
12530     */
12531    public void scanAvailableAsecs() {
12532        updateExternalMediaStatusInner(true, false, false);
12533        if (mShouldRestoreconData) {
12534            SELinuxMMAC.setRestoreconDone();
12535            mShouldRestoreconData = false;
12536        }
12537    }
12538
12539    /*
12540     * Collect information of applications on external media, map them against
12541     * existing containers and update information based on current mount status.
12542     * Please note that we always have to report status if reportStatus has been
12543     * set to true especially when unloading packages.
12544     */
12545    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12546            boolean externalStorage) {
12547        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12548        int[] uidArr = EmptyArray.INT;
12549
12550        final String[] list = PackageHelper.getSecureContainerList();
12551        if (ArrayUtils.isEmpty(list)) {
12552            Log.i(TAG, "No secure containers found");
12553        } else {
12554            // Process list of secure containers and categorize them
12555            // as active or stale based on their package internal state.
12556
12557            // reader
12558            synchronized (mPackages) {
12559                for (String cid : list) {
12560                    // Leave stages untouched for now; installer service owns them
12561                    if (PackageInstallerService.isStageName(cid)) continue;
12562
12563                    if (DEBUG_SD_INSTALL)
12564                        Log.i(TAG, "Processing container " + cid);
12565                    String pkgName = getAsecPackageName(cid);
12566                    if (pkgName == null) {
12567                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12568                        continue;
12569                    }
12570                    if (DEBUG_SD_INSTALL)
12571                        Log.i(TAG, "Looking for pkg : " + pkgName);
12572
12573                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12574                    if (ps == null) {
12575                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12576                        continue;
12577                    }
12578
12579                    /*
12580                     * Skip packages that are not external if we're unmounting
12581                     * external storage.
12582                     */
12583                    if (externalStorage && !isMounted && !isExternal(ps)) {
12584                        continue;
12585                    }
12586
12587                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12588                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12589                    // The package status is changed only if the code path
12590                    // matches between settings and the container id.
12591                    if (ps.codePathString != null
12592                            && ps.codePathString.startsWith(args.getCodePath())) {
12593                        if (DEBUG_SD_INSTALL) {
12594                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12595                                    + " at code path: " + ps.codePathString);
12596                        }
12597
12598                        // We do have a valid package installed on sdcard
12599                        processCids.put(args, ps.codePathString);
12600                        final int uid = ps.appId;
12601                        if (uid != -1) {
12602                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12603                        }
12604                    } else {
12605                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12606                                + ps.codePathString);
12607                    }
12608                }
12609            }
12610
12611            Arrays.sort(uidArr);
12612        }
12613
12614        // Process packages with valid entries.
12615        if (isMounted) {
12616            if (DEBUG_SD_INSTALL)
12617                Log.i(TAG, "Loading packages");
12618            loadMediaPackages(processCids, uidArr);
12619            startCleaningPackages();
12620            mInstallerService.onSecureContainersAvailable();
12621        } else {
12622            if (DEBUG_SD_INSTALL)
12623                Log.i(TAG, "Unloading packages");
12624            unloadMediaPackages(processCids, uidArr, reportStatus);
12625        }
12626    }
12627
12628    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12629            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12630        int size = pkgList.size();
12631        if (size > 0) {
12632            // Send broadcasts here
12633            Bundle extras = new Bundle();
12634            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12635                    .toArray(new String[size]));
12636            if (uidArr != null) {
12637                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12638            }
12639            if (replacing) {
12640                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12641            }
12642            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12643                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12644            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12645        }
12646    }
12647
12648   /*
12649     * Look at potentially valid container ids from processCids If package
12650     * information doesn't match the one on record or package scanning fails,
12651     * the cid is added to list of removeCids. We currently don't delete stale
12652     * containers.
12653     */
12654    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12655        ArrayList<String> pkgList = new ArrayList<String>();
12656        Set<AsecInstallArgs> keys = processCids.keySet();
12657
12658        for (AsecInstallArgs args : keys) {
12659            String codePath = processCids.get(args);
12660            if (DEBUG_SD_INSTALL)
12661                Log.i(TAG, "Loading container : " + args.cid);
12662            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12663            try {
12664                // Make sure there are no container errors first.
12665                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12666                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12667                            + " when installing from sdcard");
12668                    continue;
12669                }
12670                // Check code path here.
12671                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12672                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12673                            + " does not match one in settings " + codePath);
12674                    continue;
12675                }
12676                // Parse package
12677                int parseFlags = mDefParseFlags;
12678                if (args.isExternal()) {
12679                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12680                }
12681                if (args.isFwdLocked()) {
12682                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12683                }
12684
12685                synchronized (mInstallLock) {
12686                    PackageParser.Package pkg = null;
12687                    try {
12688                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12689                    } catch (PackageManagerException e) {
12690                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12691                    }
12692                    // Scan the package
12693                    if (pkg != null) {
12694                        /*
12695                         * TODO why is the lock being held? doPostInstall is
12696                         * called in other places without the lock. This needs
12697                         * to be straightened out.
12698                         */
12699                        // writer
12700                        synchronized (mPackages) {
12701                            retCode = PackageManager.INSTALL_SUCCEEDED;
12702                            pkgList.add(pkg.packageName);
12703                            // Post process args
12704                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12705                                    pkg.applicationInfo.uid);
12706                        }
12707                    } else {
12708                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12709                    }
12710                }
12711
12712            } finally {
12713                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12714                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12715                }
12716            }
12717        }
12718        // writer
12719        synchronized (mPackages) {
12720            // If the platform SDK has changed since the last time we booted,
12721            // we need to re-grant app permission to catch any new ones that
12722            // appear. This is really a hack, and means that apps can in some
12723            // cases get permissions that the user didn't initially explicitly
12724            // allow... it would be nice to have some better way to handle
12725            // this situation.
12726            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12727            if (regrantPermissions)
12728                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12729                        + mSdkVersion + "; regranting permissions for external storage");
12730            mSettings.mExternalSdkPlatform = mSdkVersion;
12731
12732            // Make sure group IDs have been assigned, and any permission
12733            // changes in other apps are accounted for
12734            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12735                    | (regrantPermissions
12736                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12737                            : 0));
12738
12739            mSettings.updateExternalDatabaseVersion();
12740
12741            // can downgrade to reader
12742            // Persist settings
12743            mSettings.writeLPr();
12744        }
12745        // Send a broadcast to let everyone know we are done processing
12746        if (pkgList.size() > 0) {
12747            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12748        }
12749    }
12750
12751   /*
12752     * Utility method to unload a list of specified containers
12753     */
12754    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12755        // Just unmount all valid containers.
12756        for (AsecInstallArgs arg : cidArgs) {
12757            synchronized (mInstallLock) {
12758                arg.doPostDeleteLI(false);
12759           }
12760       }
12761   }
12762
12763    /*
12764     * Unload packages mounted on external media. This involves deleting package
12765     * data from internal structures, sending broadcasts about diabled packages,
12766     * gc'ing to free up references, unmounting all secure containers
12767     * corresponding to packages on external media, and posting a
12768     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12769     * that we always have to post this message if status has been requested no
12770     * matter what.
12771     */
12772    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12773            final boolean reportStatus) {
12774        if (DEBUG_SD_INSTALL)
12775            Log.i(TAG, "unloading media packages");
12776        ArrayList<String> pkgList = new ArrayList<String>();
12777        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12778        final Set<AsecInstallArgs> keys = processCids.keySet();
12779        for (AsecInstallArgs args : keys) {
12780            String pkgName = args.getPackageName();
12781            if (DEBUG_SD_INSTALL)
12782                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12783            // Delete package internally
12784            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12785            synchronized (mInstallLock) {
12786                boolean res = deletePackageLI(pkgName, null, false, null, null,
12787                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12788                if (res) {
12789                    pkgList.add(pkgName);
12790                } else {
12791                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12792                    failedList.add(args);
12793                }
12794            }
12795        }
12796
12797        // reader
12798        synchronized (mPackages) {
12799            // We didn't update the settings after removing each package;
12800            // write them now for all packages.
12801            mSettings.writeLPr();
12802        }
12803
12804        // We have to absolutely send UPDATED_MEDIA_STATUS only
12805        // after confirming that all the receivers processed the ordered
12806        // broadcast when packages get disabled, force a gc to clean things up.
12807        // and unload all the containers.
12808        if (pkgList.size() > 0) {
12809            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12810                    new IIntentReceiver.Stub() {
12811                public void performReceive(Intent intent, int resultCode, String data,
12812                        Bundle extras, boolean ordered, boolean sticky,
12813                        int sendingUser) throws RemoteException {
12814                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12815                            reportStatus ? 1 : 0, 1, keys);
12816                    mHandler.sendMessage(msg);
12817                }
12818            });
12819        } else {
12820            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12821                    keys);
12822            mHandler.sendMessage(msg);
12823        }
12824    }
12825
12826    /** Binder call */
12827    @Override
12828    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12829            final int flags) {
12830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12831        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12832        int returnCode = PackageManager.MOVE_SUCCEEDED;
12833        int currInstallFlags = 0;
12834        int newInstallFlags = 0;
12835
12836        File codeFile = null;
12837        String installerPackageName = null;
12838        String packageAbiOverride = null;
12839
12840        // reader
12841        synchronized (mPackages) {
12842            final PackageParser.Package pkg = mPackages.get(packageName);
12843            final PackageSetting ps = mSettings.mPackages.get(packageName);
12844            if (pkg == null || ps == null) {
12845                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12846            } else {
12847                // Disable moving fwd locked apps and system packages
12848                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12849                    Slog.w(TAG, "Cannot move system application");
12850                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12851                } else if (pkg.mOperationPending) {
12852                    Slog.w(TAG, "Attempt to move package which has pending operations");
12853                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12854                } else {
12855                    // Find install location first
12856                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12857                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12858                        Slog.w(TAG, "Ambigous flags specified for move location.");
12859                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12860                    } else {
12861                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12862                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12863                        currInstallFlags = isExternal(pkg)
12864                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12865
12866                        if (newInstallFlags == currInstallFlags) {
12867                            Slog.w(TAG, "No move required. Trying to move to same location");
12868                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12869                        } else {
12870                            if (isForwardLocked(pkg)) {
12871                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12872                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12873                            }
12874                        }
12875                    }
12876                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12877                        pkg.mOperationPending = true;
12878                    }
12879                }
12880
12881                codeFile = new File(pkg.codePath);
12882                installerPackageName = ps.installerPackageName;
12883                packageAbiOverride = ps.cpuAbiOverrideString;
12884            }
12885        }
12886
12887        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12888            try {
12889                observer.packageMoved(packageName, returnCode);
12890            } catch (RemoteException ignored) {
12891            }
12892            return;
12893        }
12894
12895        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12896            @Override
12897            public void onUserActionRequired(Intent intent) throws RemoteException {
12898                throw new IllegalStateException();
12899            }
12900
12901            @Override
12902            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12903                    Bundle extras) throws RemoteException {
12904                Slog.d(TAG, "Install result for move: "
12905                        + PackageManager.installStatusToString(returnCode, msg));
12906
12907                // We usually have a new package now after the install, but if
12908                // we failed we need to clear the pending flag on the original
12909                // package object.
12910                synchronized (mPackages) {
12911                    final PackageParser.Package pkg = mPackages.get(packageName);
12912                    if (pkg != null) {
12913                        pkg.mOperationPending = false;
12914                    }
12915                }
12916
12917                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12918                switch (status) {
12919                    case PackageInstaller.STATUS_SUCCESS:
12920                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12921                        break;
12922                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12923                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12924                        break;
12925                    default:
12926                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12927                        break;
12928                }
12929            }
12930        };
12931
12932        // Treat a move like reinstalling an existing app, which ensures that we
12933        // process everythign uniformly, like unpacking native libraries.
12934        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12935
12936        final Message msg = mHandler.obtainMessage(INIT_COPY);
12937        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12938        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12939                installerPackageName, null, user, packageAbiOverride);
12940        mHandler.sendMessage(msg);
12941    }
12942
12943    @Override
12944    public boolean setInstallLocation(int loc) {
12945        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12946                null);
12947        if (getInstallLocation() == loc) {
12948            return true;
12949        }
12950        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12951                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12952            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12953                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12954            return true;
12955        }
12956        return false;
12957   }
12958
12959    @Override
12960    public int getInstallLocation() {
12961        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12962                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12963                PackageHelper.APP_INSTALL_AUTO);
12964    }
12965
12966    /** Called by UserManagerService */
12967    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12968        mDirtyUsers.remove(userHandle);
12969        mSettings.removeUserLPw(userHandle);
12970        mPendingBroadcasts.remove(userHandle);
12971        if (mInstaller != null) {
12972            // Technically, we shouldn't be doing this with the package lock
12973            // held.  However, this is very rare, and there is already so much
12974            // other disk I/O going on, that we'll let it slide for now.
12975            mInstaller.removeUserDataDirs(userHandle);
12976        }
12977        mUserNeedsBadging.delete(userHandle);
12978        removeUnusedPackagesLILPw(userManager, userHandle);
12979    }
12980
12981    /**
12982     * We're removing userHandle and would like to remove any downloaded packages
12983     * that are no longer in use by any other user.
12984     * @param userHandle the user being removed
12985     */
12986    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12987        final boolean DEBUG_CLEAN_APKS = false;
12988        int [] users = userManager.getUserIdsLPr();
12989        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12990        while (psit.hasNext()) {
12991            PackageSetting ps = psit.next();
12992            final String packageName = ps.pkg.packageName;
12993            // Skip over if system app
12994            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12995                continue;
12996            }
12997            if (DEBUG_CLEAN_APKS) {
12998                Slog.i(TAG, "Checking package " + packageName);
12999            }
13000            boolean keep = false;
13001            for (int i = 0; i < users.length; i++) {
13002                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13003                    keep = true;
13004                    if (DEBUG_CLEAN_APKS) {
13005                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13006                                + users[i]);
13007                    }
13008                    break;
13009                }
13010            }
13011            if (!keep) {
13012                if (DEBUG_CLEAN_APKS) {
13013                    Slog.i(TAG, "  Removing package " + packageName);
13014                }
13015                mHandler.post(new Runnable() {
13016                    public void run() {
13017                        deletePackageX(packageName, userHandle, 0);
13018                    } //end run
13019                });
13020            }
13021        }
13022    }
13023
13024    /** Called by UserManagerService */
13025    void createNewUserLILPw(int userHandle, File path) {
13026        if (mInstaller != null) {
13027            mInstaller.createUserConfig(userHandle);
13028            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13029        }
13030    }
13031
13032    @Override
13033    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13034        mContext.enforceCallingOrSelfPermission(
13035                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13036                "Only package verification agents can read the verifier device identity");
13037
13038        synchronized (mPackages) {
13039            return mSettings.getVerifierDeviceIdentityLPw();
13040        }
13041    }
13042
13043    @Override
13044    public void setPermissionEnforced(String permission, boolean enforced) {
13045        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13046        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13047            synchronized (mPackages) {
13048                if (mSettings.mReadExternalStorageEnforced == null
13049                        || mSettings.mReadExternalStorageEnforced != enforced) {
13050                    mSettings.mReadExternalStorageEnforced = enforced;
13051                    mSettings.writeLPr();
13052                }
13053            }
13054            // kill any non-foreground processes so we restart them and
13055            // grant/revoke the GID.
13056            final IActivityManager am = ActivityManagerNative.getDefault();
13057            if (am != null) {
13058                final long token = Binder.clearCallingIdentity();
13059                try {
13060                    am.killProcessesBelowForeground("setPermissionEnforcement");
13061                } catch (RemoteException e) {
13062                } finally {
13063                    Binder.restoreCallingIdentity(token);
13064                }
13065            }
13066        } else {
13067            throw new IllegalArgumentException("No selective enforcement for " + permission);
13068        }
13069    }
13070
13071    @Override
13072    @Deprecated
13073    public boolean isPermissionEnforced(String permission) {
13074        return true;
13075    }
13076
13077    @Override
13078    public boolean isStorageLow() {
13079        final long token = Binder.clearCallingIdentity();
13080        try {
13081            final DeviceStorageMonitorInternal
13082                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13083            if (dsm != null) {
13084                return dsm.isMemoryLow();
13085            } else {
13086                return false;
13087            }
13088        } finally {
13089            Binder.restoreCallingIdentity(token);
13090        }
13091    }
13092
13093    @Override
13094    public IPackageInstaller getPackageInstaller() {
13095        return mInstallerService;
13096    }
13097
13098    private boolean userNeedsBadging(int userId) {
13099        int index = mUserNeedsBadging.indexOfKey(userId);
13100        if (index < 0) {
13101            final UserInfo userInfo;
13102            final long token = Binder.clearCallingIdentity();
13103            try {
13104                userInfo = sUserManager.getUserInfo(userId);
13105            } finally {
13106                Binder.restoreCallingIdentity(token);
13107            }
13108            final boolean b;
13109            if (userInfo != null && userInfo.isManagedProfile()) {
13110                b = true;
13111            } else {
13112                b = false;
13113            }
13114            mUserNeedsBadging.put(userId, b);
13115            return b;
13116        }
13117        return mUserNeedsBadging.valueAt(index);
13118    }
13119
13120    @Override
13121    public KeySet getKeySetByAlias(String packageName, String alias) {
13122        if (packageName == null || alias == null) {
13123            return null;
13124        }
13125        synchronized(mPackages) {
13126            final PackageParser.Package pkg = mPackages.get(packageName);
13127            if (pkg == null) {
13128                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13129                throw new IllegalArgumentException("Unknown package: " + packageName);
13130            }
13131            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13132            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13133        }
13134    }
13135
13136    @Override
13137    public KeySet getSigningKeySet(String packageName) {
13138        if (packageName == null) {
13139            return null;
13140        }
13141        synchronized(mPackages) {
13142            final PackageParser.Package pkg = mPackages.get(packageName);
13143            if (pkg == null) {
13144                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13145                throw new IllegalArgumentException("Unknown package: " + packageName);
13146            }
13147            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13148                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13149                throw new SecurityException("May not access signing KeySet of other apps.");
13150            }
13151            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13152            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13153        }
13154    }
13155
13156    @Override
13157    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13158        if (packageName == null || ks == null) {
13159            return false;
13160        }
13161        synchronized(mPackages) {
13162            final PackageParser.Package pkg = mPackages.get(packageName);
13163            if (pkg == null) {
13164                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13165                throw new IllegalArgumentException("Unknown package: " + packageName);
13166            }
13167            IBinder ksh = ks.getToken();
13168            if (ksh instanceof KeySetHandle) {
13169                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13170                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13171            }
13172            return false;
13173        }
13174    }
13175
13176    @Override
13177    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13178        if (packageName == null || ks == null) {
13179            return false;
13180        }
13181        synchronized(mPackages) {
13182            final PackageParser.Package pkg = mPackages.get(packageName);
13183            if (pkg == null) {
13184                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13185                throw new IllegalArgumentException("Unknown package: " + packageName);
13186            }
13187            IBinder ksh = ks.getToken();
13188            if (ksh instanceof KeySetHandle) {
13189                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13190                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13191            }
13192            return false;
13193        }
13194    }
13195}
13196