PackageManagerService.java revision aebb65cb687216b9912cf98d24858ffcb3e6f50b
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_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
56import static com.android.internal.util.ArrayUtils.appendInt;
57import static com.android.internal.util.ArrayUtils.removeInt;
58
59import android.util.ArrayMap;
60
61import com.android.internal.R;
62import com.android.internal.app.IMediaContainerService;
63import com.android.internal.app.ResolverActivity;
64import com.android.internal.content.NativeLibraryHelper;
65import com.android.internal.content.PackageHelper;
66import com.android.internal.os.IParcelFileDescriptorFactory;
67import com.android.internal.util.ArrayUtils;
68import com.android.internal.util.FastPrintWriter;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.IndentingPrintWriter;
71import com.android.server.EventLogTags;
72import com.android.server.IntentResolver;
73import com.android.server.LocalServices;
74import com.android.server.ServiceThread;
75import com.android.server.SystemConfig;
76import com.android.server.Watchdog;
77import com.android.server.pm.Settings.DatabaseVersion;
78import com.android.server.storage.DeviceStorageMonitorInternal;
79
80import org.xmlpull.v1.XmlSerializer;
81
82import android.app.ActivityManager;
83import android.app.ActivityManagerNative;
84import android.app.AppGlobals;
85import android.app.IActivityManager;
86import android.app.admin.IDevicePolicyManager;
87import android.app.backup.IBackupManager;
88import android.app.usage.UsageStats;
89import android.app.usage.UsageStatsManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.KeySet;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageInstaller;
117import android.content.pm.PackageManager;
118import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
119import android.content.pm.PackageParser.ActivityIntentInfo;
120import android.content.pm.PackageParser.PackageLite;
121import android.content.pm.PackageParser.PackageParserException;
122import android.content.pm.PackageParser;
123import android.content.pm.PackageStats;
124import android.content.pm.PackageUserState;
125import android.content.pm.ParceledListSlice;
126import android.content.pm.PermissionGroupInfo;
127import android.content.pm.PermissionInfo;
128import android.content.pm.ProviderInfo;
129import android.content.pm.ResolveInfo;
130import android.content.pm.ServiceInfo;
131import android.content.pm.Signature;
132import android.content.pm.UserInfo;
133import android.content.pm.VerificationParams;
134import android.content.pm.VerifierDeviceIdentity;
135import android.content.pm.VerifierInfo;
136import android.content.res.Resources;
137import android.hardware.display.DisplayManager;
138import android.net.Uri;
139import android.os.Binder;
140import android.os.Build;
141import android.os.Bundle;
142import android.os.Environment;
143import android.os.Environment.UserEnvironment;
144import android.os.storage.StorageManager;
145import android.os.Debug;
146import android.os.FileUtils;
147import android.os.Handler;
148import android.os.IBinder;
149import android.os.Looper;
150import android.os.Message;
151import android.os.Parcel;
152import android.os.ParcelFileDescriptor;
153import android.os.Process;
154import android.os.RemoteException;
155import android.os.SELinux;
156import android.os.ServiceManager;
157import android.os.SystemClock;
158import android.os.SystemProperties;
159import android.os.UserHandle;
160import android.os.UserManager;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.util.ArraySet;
168import android.util.AtomicFile;
169import android.util.DisplayMetrics;
170import android.util.EventLog;
171import android.util.ExceptionUtils;
172import android.util.Log;
173import android.util.LogPrinter;
174import android.util.PrintStreamPrinter;
175import android.util.Slog;
176import android.util.SparseArray;
177import android.util.SparseBooleanArray;
178import android.view.Display;
179
180import java.io.BufferedInputStream;
181import java.io.BufferedOutputStream;
182import java.io.BufferedReader;
183import java.io.File;
184import java.io.FileDescriptor;
185import java.io.FileInputStream;
186import java.io.FileNotFoundException;
187import java.io.FileOutputStream;
188import java.io.FileReader;
189import java.io.FilenameFilter;
190import java.io.IOException;
191import java.io.InputStream;
192import java.io.PrintWriter;
193import java.nio.charset.StandardCharsets;
194import java.security.NoSuchAlgorithmException;
195import java.security.PublicKey;
196import java.security.cert.CertificateEncodingException;
197import java.security.cert.CertificateException;
198import java.text.SimpleDateFormat;
199import java.util.ArrayList;
200import java.util.Arrays;
201import java.util.Collection;
202import java.util.Collections;
203import java.util.Comparator;
204import java.util.Date;
205import java.util.Iterator;
206import java.util.List;
207import java.util.Map;
208import java.util.Objects;
209import java.util.Set;
210import java.util.concurrent.atomic.AtomicBoolean;
211import java.util.concurrent.atomic.AtomicLong;
212
213import dalvik.system.DexFile;
214import dalvik.system.StaleDexCacheError;
215import dalvik.system.VMRuntime;
216
217import libcore.io.IoUtils;
218import libcore.util.EmptyArray;
219
220/**
221 * Keep track of all those .apks everywhere.
222 *
223 * This is very central to the platform's security; please run the unit
224 * tests whenever making modifications here:
225 *
226mmm frameworks/base/tests/AndroidTests
227adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
228adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
229 *
230 * {@hide}
231 */
232public class PackageManagerService extends IPackageManager.Stub {
233    static final String TAG = "PackageManager";
234    static final boolean DEBUG_SETTINGS = false;
235    static final boolean DEBUG_PREFERRED = false;
236    static final boolean DEBUG_UPGRADE = false;
237    private static final boolean DEBUG_INSTALL = false;
238    private static final boolean DEBUG_REMOVE = false;
239    private static final boolean DEBUG_BROADCASTS = false;
240    private static final boolean DEBUG_SHOW_INFO = false;
241    private static final boolean DEBUG_PACKAGE_INFO = false;
242    private static final boolean DEBUG_INTENT_MATCHING = false;
243    private static final boolean DEBUG_PACKAGE_SCANNING = false;
244    private static final boolean DEBUG_VERIFY = false;
245    private static final boolean DEBUG_DEXOPT = false;
246    private static final boolean DEBUG_ABI_SELECTION = false;
247
248    private static final int RADIO_UID = Process.PHONE_UID;
249    private static final int LOG_UID = Process.LOG_UID;
250    private static final int NFC_UID = Process.NFC_UID;
251    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
252    private static final int SHELL_UID = Process.SHELL_UID;
253
254    // Cap the size of permission trees that 3rd party apps can define
255    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
256
257    // Suffix used during package installation when copying/moving
258    // package apks to install directory.
259    private static final String INSTALL_PACKAGE_SUFFIX = "-";
260
261    static final int SCAN_NO_DEX = 1<<1;
262    static final int SCAN_FORCE_DEX = 1<<2;
263    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
264    static final int SCAN_NEW_INSTALL = 1<<4;
265    static final int SCAN_NO_PATHS = 1<<5;
266    static final int SCAN_UPDATE_TIME = 1<<6;
267    static final int SCAN_DEFER_DEX = 1<<7;
268    static final int SCAN_BOOTING = 1<<8;
269    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
270    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
271    static final int SCAN_REPLACING = 1<<11;
272
273    static final int REMOVE_CHATTY = 1<<16;
274
275    /**
276     * Timeout (in milliseconds) after which the watchdog should declare that
277     * our handler thread is wedged.  The usual default for such things is one
278     * minute but we sometimes do very lengthy I/O operations on this thread,
279     * such as installing multi-gigabyte applications, so ours needs to be longer.
280     */
281    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
282
283    /**
284     * Whether verification is enabled by default.
285     */
286    private static final boolean DEFAULT_VERIFY_ENABLE = true;
287
288    /**
289     * The default maximum time to wait for the verification agent to return in
290     * milliseconds.
291     */
292    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
293
294    /**
295     * The default response for package verification timeout.
296     *
297     * This can be either PackageManager.VERIFICATION_ALLOW or
298     * PackageManager.VERIFICATION_REJECT.
299     */
300    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
301
302    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
303
304    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
305            DEFAULT_CONTAINER_PACKAGE,
306            "com.android.defcontainer.DefaultContainerService");
307
308    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
309
310    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
311
312    private static String sPreferredInstructionSet;
313
314    final ServiceThread mHandlerThread;
315
316    private static final String IDMAP_PREFIX = "/data/resource-cache/";
317    private static final String IDMAP_SUFFIX = "@idmap";
318
319    final PackageHandler mHandler;
320
321    /**
322     * Messages for {@link #mHandler} that need to wait for system ready before
323     * being dispatched.
324     */
325    private ArrayList<Message> mPostSystemReadyMessages;
326
327    final int mSdkVersion = Build.VERSION.SDK_INT;
328
329    final Context mContext;
330    final boolean mFactoryTest;
331    final boolean mOnlyCore;
332    final boolean mLazyDexOpt;
333    final long mDexOptLRUThresholdInMills;
334    final DisplayMetrics mMetrics;
335    final int mDefParseFlags;
336    final String[] mSeparateProcesses;
337    final boolean mIsUpgrade;
338
339    // This is where all application persistent data goes.
340    final File mAppDataDir;
341
342    // This is where all application persistent data goes for secondary users.
343    final File mUserAppDataDir;
344
345    /** The location for ASEC container files on internal storage. */
346    final String mAsecInternalPath;
347
348    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
349    // LOCK HELD.  Can be called with mInstallLock held.
350    final Installer mInstaller;
351
352    /** Directory where installed third-party apps stored */
353    final File mAppInstallDir;
354
355    /**
356     * Directory to which applications installed internally have their
357     * 32 bit native libraries copied.
358     */
359    private File mAppLib32InstallDir;
360
361    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
362    // apps.
363    final File mDrmAppPrivateInstallDir;
364
365    // ----------------------------------------------------------------
366
367    // Lock for state used when installing and doing other long running
368    // operations.  Methods that must be called with this lock held have
369    // the suffix "LI".
370    final Object mInstallLock = new Object();
371
372    // ----------------------------------------------------------------
373
374    // Keys are String (package name), values are Package.  This also serves
375    // as the lock for the global state.  Methods that must be called with
376    // this lock held have the prefix "LP".
377    final ArrayMap<String, PackageParser.Package> mPackages =
378            new ArrayMap<String, PackageParser.Package>();
379
380    // Tracks available target package names -> overlay package paths.
381    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
382        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
383
384    final Settings mSettings;
385    boolean mRestoredSettings;
386
387    // System configuration read by SystemConfig.
388    final int[] mGlobalGids;
389    final SparseArray<ArraySet<String>> mSystemPermissions;
390    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
391
392    // If mac_permissions.xml was found for seinfo labeling.
393    boolean mFoundPolicyFile;
394
395    // If a recursive restorecon of /data/data/<pkg> is needed.
396    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
397
398    public static final class SharedLibraryEntry {
399        public final String path;
400        public final String apk;
401
402        SharedLibraryEntry(String _path, String _apk) {
403            path = _path;
404            apk = _apk;
405        }
406    }
407
408    // Currently known shared libraries.
409    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
410            new ArrayMap<String, SharedLibraryEntry>();
411
412    // All available activities, for your resolving pleasure.
413    final ActivityIntentResolver mActivities =
414            new ActivityIntentResolver();
415
416    // All available receivers, for your resolving pleasure.
417    final ActivityIntentResolver mReceivers =
418            new ActivityIntentResolver();
419
420    // All available services, for your resolving pleasure.
421    final ServiceIntentResolver mServices = new ServiceIntentResolver();
422
423    // All available providers, for your resolving pleasure.
424    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
425
426    // Mapping from provider base names (first directory in content URI codePath)
427    // to the provider information.
428    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
429            new ArrayMap<String, PackageParser.Provider>();
430
431    // Mapping from instrumentation class names to info about them.
432    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
433            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
434
435    // Mapping from permission names to info about them.
436    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
437            new ArrayMap<String, PackageParser.PermissionGroup>();
438
439    // Packages whose data we have transfered into another package, thus
440    // should no longer exist.
441    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
442
443    // Broadcast actions that are only available to the system.
444    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
445
446    /** List of packages waiting for verification. */
447    final SparseArray<PackageVerificationState> mPendingVerification
448            = new SparseArray<PackageVerificationState>();
449
450    /** Set of packages associated with each app op permission. */
451    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
452
453    final PackageInstallerService mInstallerService;
454
455    ArraySet<PackageParser.Package> mDeferredDexOpt = null;
456
457    // Cache of users who need badging.
458    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
459
460    /** Token for keys in mPendingVerification. */
461    private int mPendingVerificationToken = 0;
462
463    volatile boolean mSystemReady;
464    volatile boolean mSafeMode;
465    volatile boolean mHasSystemUidErrors;
466
467    ApplicationInfo mAndroidApplication;
468    final ActivityInfo mResolveActivity = new ActivityInfo();
469    final ResolveInfo mResolveInfo = new ResolveInfo();
470    ComponentName mResolveComponentName;
471    PackageParser.Package mPlatformPackage;
472    ComponentName mCustomResolverComponentName;
473
474    boolean mResolverReplaced = false;
475
476    // Set of pending broadcasts for aggregating enable/disable of components.
477    static class PendingPackageBroadcasts {
478        // for each user id, a map of <package name -> components within that package>
479        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
480
481        public PendingPackageBroadcasts() {
482            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
483        }
484
485        public ArrayList<String> get(int userId, String packageName) {
486            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
487            return packages.get(packageName);
488        }
489
490        public void put(int userId, String packageName, ArrayList<String> components) {
491            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
492            packages.put(packageName, components);
493        }
494
495        public void remove(int userId, String packageName) {
496            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
497            if (packages != null) {
498                packages.remove(packageName);
499            }
500        }
501
502        public void remove(int userId) {
503            mUidMap.remove(userId);
504        }
505
506        public int userIdCount() {
507            return mUidMap.size();
508        }
509
510        public int userIdAt(int n) {
511            return mUidMap.keyAt(n);
512        }
513
514        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
515            return mUidMap.get(userId);
516        }
517
518        public int size() {
519            // total number of pending broadcast entries across all userIds
520            int num = 0;
521            for (int i = 0; i< mUidMap.size(); i++) {
522                num += mUidMap.valueAt(i).size();
523            }
524            return num;
525        }
526
527        public void clear() {
528            mUidMap.clear();
529        }
530
531        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
532            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
533            if (map == null) {
534                map = new ArrayMap<String, ArrayList<String>>();
535                mUidMap.put(userId, map);
536            }
537            return map;
538        }
539    }
540    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
541
542    // Service Connection to remote media container service to copy
543    // package uri's from external media onto secure containers
544    // or internal storage.
545    private IMediaContainerService mContainerService = null;
546
547    static final int SEND_PENDING_BROADCAST = 1;
548    static final int MCS_BOUND = 3;
549    static final int END_COPY = 4;
550    static final int INIT_COPY = 5;
551    static final int MCS_UNBIND = 6;
552    static final int START_CLEANING_PACKAGE = 7;
553    static final int FIND_INSTALL_LOC = 8;
554    static final int POST_INSTALL = 9;
555    static final int MCS_RECONNECT = 10;
556    static final int MCS_GIVE_UP = 11;
557    static final int UPDATED_MEDIA_STATUS = 12;
558    static final int WRITE_SETTINGS = 13;
559    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
560    static final int PACKAGE_VERIFIED = 15;
561    static final int CHECK_PENDING_VERIFICATION = 16;
562
563    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
564
565    // Delay time in millisecs
566    static final int BROADCAST_DELAY = 10 * 1000;
567
568    static UserManagerService sUserManager;
569
570    // Stores a list of users whose package restrictions file needs to be updated
571    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
572
573    final private DefaultContainerConnection mDefContainerConn =
574            new DefaultContainerConnection();
575    class DefaultContainerConnection implements ServiceConnection {
576        public void onServiceConnected(ComponentName name, IBinder service) {
577            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
578            IMediaContainerService imcs =
579                IMediaContainerService.Stub.asInterface(service);
580            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
581        }
582
583        public void onServiceDisconnected(ComponentName name) {
584            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
585        }
586    };
587
588    // Recordkeeping of restore-after-install operations that are currently in flight
589    // between the Package Manager and the Backup Manager
590    class PostInstallData {
591        public InstallArgs args;
592        public PackageInstalledInfo res;
593
594        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
595            args = _a;
596            res = _r;
597        }
598    };
599    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
600    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
601
602    private final String mRequiredVerifierPackage;
603
604    private final PackageUsage mPackageUsage = new PackageUsage();
605
606    private class PackageUsage {
607        private static final int WRITE_INTERVAL
608            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
609
610        private final Object mFileLock = new Object();
611        private final AtomicLong mLastWritten = new AtomicLong(0);
612        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
613
614        private boolean mIsHistoricalPackageUsageAvailable = true;
615
616        boolean isHistoricalPackageUsageAvailable() {
617            return mIsHistoricalPackageUsageAvailable;
618        }
619
620        void write(boolean force) {
621            if (force) {
622                writeInternal();
623                return;
624            }
625            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
626                && !DEBUG_DEXOPT) {
627                return;
628            }
629            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
630                new Thread("PackageUsage_DiskWriter") {
631                    @Override
632                    public void run() {
633                        try {
634                            writeInternal();
635                        } finally {
636                            mBackgroundWriteRunning.set(false);
637                        }
638                    }
639                }.start();
640            }
641        }
642
643        private void writeInternal() {
644            synchronized (mPackages) {
645                synchronized (mFileLock) {
646                    AtomicFile file = getFile();
647                    FileOutputStream f = null;
648                    try {
649                        f = file.startWrite();
650                        BufferedOutputStream out = new BufferedOutputStream(f);
651                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
652                        StringBuilder sb = new StringBuilder();
653                        for (PackageParser.Package pkg : mPackages.values()) {
654                            if (pkg.mLastPackageUsageTimeInMills == 0) {
655                                continue;
656                            }
657                            sb.setLength(0);
658                            sb.append(pkg.packageName);
659                            sb.append(' ');
660                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
661                            sb.append('\n');
662                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
663                        }
664                        out.flush();
665                        file.finishWrite(f);
666                    } catch (IOException e) {
667                        if (f != null) {
668                            file.failWrite(f);
669                        }
670                        Log.e(TAG, "Failed to write package usage times", e);
671                    }
672                }
673            }
674            mLastWritten.set(SystemClock.elapsedRealtime());
675        }
676
677        void readLP() {
678            synchronized (mFileLock) {
679                AtomicFile file = getFile();
680                BufferedInputStream in = null;
681                try {
682                    in = new BufferedInputStream(file.openRead());
683                    StringBuffer sb = new StringBuffer();
684                    while (true) {
685                        String packageName = readToken(in, sb, ' ');
686                        if (packageName == null) {
687                            break;
688                        }
689                        String timeInMillisString = readToken(in, sb, '\n');
690                        if (timeInMillisString == null) {
691                            throw new IOException("Failed to find last usage time for package "
692                                                  + packageName);
693                        }
694                        PackageParser.Package pkg = mPackages.get(packageName);
695                        if (pkg == null) {
696                            continue;
697                        }
698                        long timeInMillis;
699                        try {
700                            timeInMillis = Long.parseLong(timeInMillisString.toString());
701                        } catch (NumberFormatException e) {
702                            throw new IOException("Failed to parse " + timeInMillisString
703                                                  + " as a long.", e);
704                        }
705                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
706                    }
707                } catch (FileNotFoundException expected) {
708                    mIsHistoricalPackageUsageAvailable = false;
709                } catch (IOException e) {
710                    Log.w(TAG, "Failed to read package usage times", e);
711                } finally {
712                    IoUtils.closeQuietly(in);
713                }
714            }
715            mLastWritten.set(SystemClock.elapsedRealtime());
716        }
717
718        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
719                throws IOException {
720            sb.setLength(0);
721            while (true) {
722                int ch = in.read();
723                if (ch == -1) {
724                    if (sb.length() == 0) {
725                        return null;
726                    }
727                    throw new IOException("Unexpected EOF");
728                }
729                if (ch == endOfToken) {
730                    return sb.toString();
731                }
732                sb.append((char)ch);
733            }
734        }
735
736        private AtomicFile getFile() {
737            File dataDir = Environment.getDataDirectory();
738            File systemDir = new File(dataDir, "system");
739            File fname = new File(systemDir, "package-usage.list");
740            return new AtomicFile(fname);
741        }
742    }
743
744    class PackageHandler extends Handler {
745        private boolean mBound = false;
746        final ArrayList<HandlerParams> mPendingInstalls =
747            new ArrayList<HandlerParams>();
748
749        private boolean connectToService() {
750            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
751                    " DefaultContainerService");
752            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
753            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
754            if (mContext.bindServiceAsUser(service, mDefContainerConn,
755                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
756                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
757                mBound = true;
758                return true;
759            }
760            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
761            return false;
762        }
763
764        private void disconnectService() {
765            mContainerService = null;
766            mBound = false;
767            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
768            mContext.unbindService(mDefContainerConn);
769            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
770        }
771
772        PackageHandler(Looper looper) {
773            super(looper);
774        }
775
776        public void handleMessage(Message msg) {
777            try {
778                doHandleMessage(msg);
779            } finally {
780                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781            }
782        }
783
784        void doHandleMessage(Message msg) {
785            switch (msg.what) {
786                case INIT_COPY: {
787                    HandlerParams params = (HandlerParams) msg.obj;
788                    int idx = mPendingInstalls.size();
789                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
790                    // If a bind was already initiated we dont really
791                    // need to do anything. The pending install
792                    // will be processed later on.
793                    if (!mBound) {
794                        // If this is the only one pending we might
795                        // have to bind to the service again.
796                        if (!connectToService()) {
797                            Slog.e(TAG, "Failed to bind to media container service");
798                            params.serviceError();
799                            return;
800                        } else {
801                            // Once we bind to the service, the first
802                            // pending request will be processed.
803                            mPendingInstalls.add(idx, params);
804                        }
805                    } else {
806                        mPendingInstalls.add(idx, params);
807                        // Already bound to the service. Just make
808                        // sure we trigger off processing the first request.
809                        if (idx == 0) {
810                            mHandler.sendEmptyMessage(MCS_BOUND);
811                        }
812                    }
813                    break;
814                }
815                case MCS_BOUND: {
816                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
817                    if (msg.obj != null) {
818                        mContainerService = (IMediaContainerService) msg.obj;
819                    }
820                    if (mContainerService == null) {
821                        // Something seriously wrong. Bail out
822                        Slog.e(TAG, "Cannot bind to media container service");
823                        for (HandlerParams params : mPendingInstalls) {
824                            // Indicate service bind error
825                            params.serviceError();
826                        }
827                        mPendingInstalls.clear();
828                    } else if (mPendingInstalls.size() > 0) {
829                        HandlerParams params = mPendingInstalls.get(0);
830                        if (params != null) {
831                            if (params.startCopy()) {
832                                // We are done...  look for more work or to
833                                // go idle.
834                                if (DEBUG_SD_INSTALL) Log.i(TAG,
835                                        "Checking for more work or unbind...");
836                                // Delete pending install
837                                if (mPendingInstalls.size() > 0) {
838                                    mPendingInstalls.remove(0);
839                                }
840                                if (mPendingInstalls.size() == 0) {
841                                    if (mBound) {
842                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
843                                                "Posting delayed MCS_UNBIND");
844                                        removeMessages(MCS_UNBIND);
845                                        Message ubmsg = obtainMessage(MCS_UNBIND);
846                                        // Unbind after a little delay, to avoid
847                                        // continual thrashing.
848                                        sendMessageDelayed(ubmsg, 10000);
849                                    }
850                                } else {
851                                    // There are more pending requests in queue.
852                                    // Just post MCS_BOUND message to trigger processing
853                                    // of next pending install.
854                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
855                                            "Posting MCS_BOUND for next work");
856                                    mHandler.sendEmptyMessage(MCS_BOUND);
857                                }
858                            }
859                        }
860                    } else {
861                        // Should never happen ideally.
862                        Slog.w(TAG, "Empty queue");
863                    }
864                    break;
865                }
866                case MCS_RECONNECT: {
867                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
868                    if (mPendingInstalls.size() > 0) {
869                        if (mBound) {
870                            disconnectService();
871                        }
872                        if (!connectToService()) {
873                            Slog.e(TAG, "Failed to bind to media container service");
874                            for (HandlerParams params : mPendingInstalls) {
875                                // Indicate service bind error
876                                params.serviceError();
877                            }
878                            mPendingInstalls.clear();
879                        }
880                    }
881                    break;
882                }
883                case MCS_UNBIND: {
884                    // If there is no actual work left, then time to unbind.
885                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
886
887                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
888                        if (mBound) {
889                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
890
891                            disconnectService();
892                        }
893                    } else if (mPendingInstalls.size() > 0) {
894                        // There are more pending requests in queue.
895                        // Just post MCS_BOUND message to trigger processing
896                        // of next pending install.
897                        mHandler.sendEmptyMessage(MCS_BOUND);
898                    }
899
900                    break;
901                }
902                case MCS_GIVE_UP: {
903                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
904                    mPendingInstalls.remove(0);
905                    break;
906                }
907                case SEND_PENDING_BROADCAST: {
908                    String packages[];
909                    ArrayList<String> components[];
910                    int size = 0;
911                    int uids[];
912                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
913                    synchronized (mPackages) {
914                        if (mPendingBroadcasts == null) {
915                            return;
916                        }
917                        size = mPendingBroadcasts.size();
918                        if (size <= 0) {
919                            // Nothing to be done. Just return
920                            return;
921                        }
922                        packages = new String[size];
923                        components = new ArrayList[size];
924                        uids = new int[size];
925                        int i = 0;  // filling out the above arrays
926
927                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
928                            int packageUserId = mPendingBroadcasts.userIdAt(n);
929                            Iterator<Map.Entry<String, ArrayList<String>>> it
930                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
931                                            .entrySet().iterator();
932                            while (it.hasNext() && i < size) {
933                                Map.Entry<String, ArrayList<String>> ent = it.next();
934                                packages[i] = ent.getKey();
935                                components[i] = ent.getValue();
936                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
937                                uids[i] = (ps != null)
938                                        ? UserHandle.getUid(packageUserId, ps.appId)
939                                        : -1;
940                                i++;
941                            }
942                        }
943                        size = i;
944                        mPendingBroadcasts.clear();
945                    }
946                    // Send broadcasts
947                    for (int i = 0; i < size; i++) {
948                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
949                    }
950                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
951                    break;
952                }
953                case START_CLEANING_PACKAGE: {
954                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
955                    final String packageName = (String)msg.obj;
956                    final int userId = msg.arg1;
957                    final boolean andCode = msg.arg2 != 0;
958                    synchronized (mPackages) {
959                        if (userId == UserHandle.USER_ALL) {
960                            int[] users = sUserManager.getUserIds();
961                            for (int user : users) {
962                                mSettings.addPackageToCleanLPw(
963                                        new PackageCleanItem(user, packageName, andCode));
964                            }
965                        } else {
966                            mSettings.addPackageToCleanLPw(
967                                    new PackageCleanItem(userId, packageName, andCode));
968                        }
969                    }
970                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
971                    startCleaningPackages();
972                } break;
973                case POST_INSTALL: {
974                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
975                    PostInstallData data = mRunningInstalls.get(msg.arg1);
976                    mRunningInstalls.delete(msg.arg1);
977                    boolean deleteOld = false;
978
979                    if (data != null) {
980                        InstallArgs args = data.args;
981                        PackageInstalledInfo res = data.res;
982
983                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
984                            res.removedInfo.sendBroadcast(false, true, false);
985                            Bundle extras = new Bundle(1);
986                            extras.putInt(Intent.EXTRA_UID, res.uid);
987                            // Determine the set of users who are adding this
988                            // package for the first time vs. those who are seeing
989                            // an update.
990                            int[] firstUsers;
991                            int[] updateUsers = new int[0];
992                            if (res.origUsers == null || res.origUsers.length == 0) {
993                                firstUsers = res.newUsers;
994                            } else {
995                                firstUsers = new int[0];
996                                for (int i=0; i<res.newUsers.length; i++) {
997                                    int user = res.newUsers[i];
998                                    boolean isNew = true;
999                                    for (int j=0; j<res.origUsers.length; j++) {
1000                                        if (res.origUsers[j] == user) {
1001                                            isNew = false;
1002                                            break;
1003                                        }
1004                                    }
1005                                    if (isNew) {
1006                                        int[] newFirst = new int[firstUsers.length+1];
1007                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1008                                                firstUsers.length);
1009                                        newFirst[firstUsers.length] = user;
1010                                        firstUsers = newFirst;
1011                                    } else {
1012                                        int[] newUpdate = new int[updateUsers.length+1];
1013                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1014                                                updateUsers.length);
1015                                        newUpdate[updateUsers.length] = user;
1016                                        updateUsers = newUpdate;
1017                                    }
1018                                }
1019                            }
1020                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1021                                    res.pkg.applicationInfo.packageName,
1022                                    extras, null, null, firstUsers);
1023                            final boolean update = res.removedInfo.removedPackage != null;
1024                            if (update) {
1025                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1026                            }
1027                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1028                                    res.pkg.applicationInfo.packageName,
1029                                    extras, null, null, updateUsers);
1030                            if (update) {
1031                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1032                                        res.pkg.applicationInfo.packageName,
1033                                        extras, null, null, updateUsers);
1034                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1035                                        null, null,
1036                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1037
1038                                // treat asec-hosted packages like removable media on upgrade
1039                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1040                                    if (DEBUG_INSTALL) {
1041                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1042                                                + " is ASEC-hosted -> AVAILABLE");
1043                                    }
1044                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1045                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1046                                    pkgList.add(res.pkg.applicationInfo.packageName);
1047                                    sendResourcesChangedBroadcast(true, true,
1048                                            pkgList,uidArray, null);
1049                                }
1050                            }
1051                            if (res.removedInfo.args != null) {
1052                                // Remove the replaced package's older resources safely now
1053                                deleteOld = true;
1054                            }
1055
1056                            // Log current value of "unknown sources" setting
1057                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1058                                getUnknownSourcesSettings());
1059                        }
1060                        // Force a gc to clear up things
1061                        Runtime.getRuntime().gc();
1062                        // We delete after a gc for applications  on sdcard.
1063                        if (deleteOld) {
1064                            synchronized (mInstallLock) {
1065                                res.removedInfo.args.doPostDeleteLI(true);
1066                            }
1067                        }
1068                        if (args.observer != null) {
1069                            try {
1070                                Bundle extras = extrasForInstallResult(res);
1071                                args.observer.onPackageInstalled(res.name, res.returnCode,
1072                                        res.returnMsg, extras);
1073                            } catch (RemoteException e) {
1074                                Slog.i(TAG, "Observer no longer exists.");
1075                            }
1076                        }
1077                    } else {
1078                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1079                    }
1080                } break;
1081                case UPDATED_MEDIA_STATUS: {
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1083                    boolean reportStatus = msg.arg1 == 1;
1084                    boolean doGc = msg.arg2 == 1;
1085                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1086                    if (doGc) {
1087                        // Force a gc to clear up stale containers.
1088                        Runtime.getRuntime().gc();
1089                    }
1090                    if (msg.obj != null) {
1091                        @SuppressWarnings("unchecked")
1092                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1093                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1094                        // Unload containers
1095                        unloadAllContainers(args);
1096                    }
1097                    if (reportStatus) {
1098                        try {
1099                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1100                            PackageHelper.getMountService().finishMediaUpdate();
1101                        } catch (RemoteException e) {
1102                            Log.e(TAG, "MountService not running?");
1103                        }
1104                    }
1105                } break;
1106                case WRITE_SETTINGS: {
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1108                    synchronized (mPackages) {
1109                        removeMessages(WRITE_SETTINGS);
1110                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1111                        mSettings.writeLPr();
1112                        mDirtyUsers.clear();
1113                    }
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115                } break;
1116                case WRITE_PACKAGE_RESTRICTIONS: {
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1118                    synchronized (mPackages) {
1119                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1120                        for (int userId : mDirtyUsers) {
1121                            mSettings.writePackageRestrictionsLPr(userId);
1122                        }
1123                        mDirtyUsers.clear();
1124                    }
1125                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                } break;
1127                case CHECK_PENDING_VERIFICATION: {
1128                    final int verificationId = msg.arg1;
1129                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1130
1131                    if ((state != null) && !state.timeoutExtended()) {
1132                        final InstallArgs args = state.getInstallArgs();
1133                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1134
1135                        Slog.i(TAG, "Verification timed out for " + originUri);
1136                        mPendingVerification.remove(verificationId);
1137
1138                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1139
1140                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1141                            Slog.i(TAG, "Continuing with installation of " + originUri);
1142                            state.setVerifierResponse(Binder.getCallingUid(),
1143                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1144                            broadcastPackageVerified(verificationId, originUri,
1145                                    PackageManager.VERIFICATION_ALLOW,
1146                                    state.getInstallArgs().getUser());
1147                            try {
1148                                ret = args.copyApk(mContainerService, true);
1149                            } catch (RemoteException e) {
1150                                Slog.e(TAG, "Could not contact the ContainerService");
1151                            }
1152                        } else {
1153                            broadcastPackageVerified(verificationId, originUri,
1154                                    PackageManager.VERIFICATION_REJECT,
1155                                    state.getInstallArgs().getUser());
1156                        }
1157
1158                        processPendingInstall(args, ret);
1159                        mHandler.sendEmptyMessage(MCS_UNBIND);
1160                    }
1161                    break;
1162                }
1163                case PACKAGE_VERIFIED: {
1164                    final int verificationId = msg.arg1;
1165
1166                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1167                    if (state == null) {
1168                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1169                        break;
1170                    }
1171
1172                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1173
1174                    state.setVerifierResponse(response.callerUid, response.code);
1175
1176                    if (state.isVerificationComplete()) {
1177                        mPendingVerification.remove(verificationId);
1178
1179                        final InstallArgs args = state.getInstallArgs();
1180                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1181
1182                        int ret;
1183                        if (state.isInstallAllowed()) {
1184                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1185                            broadcastPackageVerified(verificationId, originUri,
1186                                    response.code, state.getInstallArgs().getUser());
1187                            try {
1188                                ret = args.copyApk(mContainerService, true);
1189                            } catch (RemoteException e) {
1190                                Slog.e(TAG, "Could not contact the ContainerService");
1191                            }
1192                        } else {
1193                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1194                        }
1195
1196                        processPendingInstall(args, ret);
1197
1198                        mHandler.sendEmptyMessage(MCS_UNBIND);
1199                    }
1200
1201                    break;
1202                }
1203            }
1204        }
1205    }
1206
1207    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1208        Bundle extras = null;
1209        switch (res.returnCode) {
1210            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1211                extras = new Bundle();
1212                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1213                        res.origPermission);
1214                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1215                        res.origPackage);
1216                break;
1217            }
1218        }
1219        return extras;
1220    }
1221
1222    void scheduleWriteSettingsLocked() {
1223        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1224            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1225        }
1226    }
1227
1228    void scheduleWritePackageRestrictionsLocked(int userId) {
1229        if (!sUserManager.exists(userId)) return;
1230        mDirtyUsers.add(userId);
1231        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1232            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1233        }
1234    }
1235
1236    public static final PackageManagerService main(Context context, Installer installer,
1237            boolean factoryTest, boolean onlyCore) {
1238        PackageManagerService m = new PackageManagerService(context, installer,
1239                factoryTest, onlyCore);
1240        ServiceManager.addService("package", m);
1241        return m;
1242    }
1243
1244    static String[] splitString(String str, char sep) {
1245        int count = 1;
1246        int i = 0;
1247        while ((i=str.indexOf(sep, i)) >= 0) {
1248            count++;
1249            i++;
1250        }
1251
1252        String[] res = new String[count];
1253        i=0;
1254        count = 0;
1255        int lastI=0;
1256        while ((i=str.indexOf(sep, i)) >= 0) {
1257            res[count] = str.substring(lastI, i);
1258            count++;
1259            i++;
1260            lastI = i;
1261        }
1262        res[count] = str.substring(lastI, str.length());
1263        return res;
1264    }
1265
1266    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1267        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1268                Context.DISPLAY_SERVICE);
1269        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1270    }
1271
1272    public PackageManagerService(Context context, Installer installer,
1273            boolean factoryTest, boolean onlyCore) {
1274        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1275                SystemClock.uptimeMillis());
1276
1277        if (mSdkVersion <= 0) {
1278            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1279        }
1280
1281        mContext = context;
1282        mFactoryTest = factoryTest;
1283        mOnlyCore = onlyCore;
1284        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1285        mMetrics = new DisplayMetrics();
1286        mSettings = new Settings(context);
1287        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299
1300        // TODO: add a property to control this?
1301        long dexOptLRUThresholdInMinutes;
1302        if (mLazyDexOpt) {
1303            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1304        } else {
1305            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1306        }
1307        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1308
1309        String separateProcesses = SystemProperties.get("debug.separate_processes");
1310        if (separateProcesses != null && separateProcesses.length() > 0) {
1311            if ("*".equals(separateProcesses)) {
1312                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1313                mSeparateProcesses = null;
1314                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1315            } else {
1316                mDefParseFlags = 0;
1317                mSeparateProcesses = separateProcesses.split(",");
1318                Slog.w(TAG, "Running with debug.separate_processes: "
1319                        + separateProcesses);
1320            }
1321        } else {
1322            mDefParseFlags = 0;
1323            mSeparateProcesses = null;
1324        }
1325
1326        mInstaller = installer;
1327
1328        getDefaultDisplayMetrics(context, mMetrics);
1329
1330        SystemConfig systemConfig = SystemConfig.getInstance();
1331        mGlobalGids = systemConfig.getGlobalGids();
1332        mSystemPermissions = systemConfig.getSystemPermissions();
1333        mAvailableFeatures = systemConfig.getAvailableFeatures();
1334
1335        synchronized (mInstallLock) {
1336        // writer
1337        synchronized (mPackages) {
1338            mHandlerThread = new ServiceThread(TAG,
1339                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1340            mHandlerThread.start();
1341            mHandler = new PackageHandler(mHandlerThread.getLooper());
1342            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1343
1344            File dataDir = Environment.getDataDirectory();
1345            mAppDataDir = new File(dataDir, "data");
1346            mAppInstallDir = new File(dataDir, "app");
1347            mAppLib32InstallDir = new File(dataDir, "app-lib");
1348            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1349            mUserAppDataDir = new File(dataDir, "user");
1350            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Propagate permission configuration in to package manager.
1356            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1357                    = systemConfig.getPermissions();
1358            for (int i=0; i<permConfig.size(); i++) {
1359                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1360                BasePermission bp = mSettings.mPermissions.get(perm.name);
1361                if (bp == null) {
1362                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1363                    mSettings.mPermissions.put(perm.name, bp);
1364                }
1365                if (perm.gids != null) {
1366                    bp.gids = appendInts(bp.gids, perm.gids);
1367                }
1368            }
1369
1370            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1371            for (int i=0; i<libConfig.size(); i++) {
1372                mSharedLibraries.put(libConfig.keyAt(i),
1373                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1374            }
1375
1376            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1377
1378            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1379                    mSdkVersion, mOnlyCore);
1380
1381            String customResolverActivity = Resources.getSystem().getString(
1382                    R.string.config_customResolverActivity);
1383            if (TextUtils.isEmpty(customResolverActivity)) {
1384                customResolverActivity = null;
1385            } else {
1386                mCustomResolverComponentName = ComponentName.unflattenFromString(
1387                        customResolverActivity);
1388            }
1389
1390            long startTime = SystemClock.uptimeMillis();
1391
1392            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1393                    startTime);
1394
1395            // Set flag to monitor and not change apk file paths when
1396            // scanning install directories.
1397            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1398
1399            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1400
1401            /**
1402             * Add everything in the in the boot class path to the
1403             * list of process files because dexopt will have been run
1404             * if necessary during zygote startup.
1405             */
1406            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1407            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1408
1409            if (bootClassPath != null) {
1410                String[] bootClassPathElements = splitString(bootClassPath, ':');
1411                for (String element : bootClassPathElements) {
1412                    alreadyDexOpted.add(element);
1413                }
1414            } else {
1415                Slog.w(TAG, "No BOOTCLASSPATH found!");
1416            }
1417
1418            if (systemServerClassPath != null) {
1419                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1420                for (String element : systemServerClassPathElements) {
1421                    alreadyDexOpted.add(element);
1422                }
1423            } else {
1424                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1425            }
1426
1427            final List<String> allInstructionSets = getAllInstructionSets();
1428            final String[] dexCodeInstructionSets =
1429                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1430
1431            /**
1432             * Ensure all external libraries have had dexopt run on them.
1433             */
1434            if (mSharedLibraries.size() > 0) {
1435                // NOTE: For now, we're compiling these system "shared libraries"
1436                // (and framework jars) into all available architectures. It's possible
1437                // to compile them only when we come across an app that uses them (there's
1438                // already logic for that in scanPackageLI) but that adds some complexity.
1439                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1440                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1441                        final String lib = libEntry.path;
1442                        if (lib == null) {
1443                            continue;
1444                        }
1445
1446                        try {
1447                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1448                                                                                 dexCodeInstructionSet,
1449                                                                                 false);
1450                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1451                                alreadyDexOpted.add(lib);
1452
1453                                // The list of "shared libraries" we have at this point is
1454                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1455                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1456                                } else {
1457                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1458                                }
1459                            }
1460                        } catch (FileNotFoundException e) {
1461                            Slog.w(TAG, "Library not found: " + lib);
1462                        } catch (IOException e) {
1463                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1464                                    + e.getMessage());
1465                        }
1466                    }
1467                }
1468            }
1469
1470            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1471
1472            // Gross hack for now: we know this file doesn't contain any
1473            // code, so don't dexopt it to avoid the resulting log spew.
1474            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1475
1476            // Gross hack for now: we know this file is only part of
1477            // the boot class path for art, so don't dexopt it to
1478            // avoid the resulting log spew.
1479            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1480
1481            /**
1482             * And there are a number of commands implemented in Java, which
1483             * we currently need to do the dexopt on so that they can be
1484             * run from a non-root shell.
1485             */
1486            String[] frameworkFiles = frameworkDir.list();
1487            if (frameworkFiles != null) {
1488                // TODO: We could compile these only for the most preferred ABI. We should
1489                // first double check that the dex files for these commands are not referenced
1490                // by other system apps.
1491                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1492                    for (int i=0; i<frameworkFiles.length; i++) {
1493                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1494                        String path = libPath.getPath();
1495                        // Skip the file if we already did it.
1496                        if (alreadyDexOpted.contains(path)) {
1497                            continue;
1498                        }
1499                        // Skip the file if it is not a type we want to dexopt.
1500                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1501                            continue;
1502                        }
1503                        try {
1504                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1505                                                                                 dexCodeInstructionSet,
1506                                                                                 false);
1507                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1508                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1509                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1510                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1511                            }
1512                        } catch (FileNotFoundException e) {
1513                            Slog.w(TAG, "Jar not found: " + path);
1514                        } catch (IOException e) {
1515                            Slog.w(TAG, "Exception reading jar: " + path, e);
1516                        }
1517                    }
1518                }
1519            }
1520
1521            // Collect vendor overlay packages.
1522            // (Do this before scanning any apps.)
1523            // For security and version matching reason, only consider
1524            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1525            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1526            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1527                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1528
1529            // Find base frameworks (resource packages without code).
1530            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1531                    | PackageParser.PARSE_IS_SYSTEM_DIR
1532                    | PackageParser.PARSE_IS_PRIVILEGED,
1533                    scanFlags | SCAN_NO_DEX, 0);
1534
1535            // Collected privileged system packages.
1536            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1537            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1538                    | PackageParser.PARSE_IS_SYSTEM_DIR
1539                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1540
1541            // Collect ordinary system packages.
1542            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1543            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1544                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1545
1546            // Collect all vendor packages.
1547            File vendorAppDir = new File("/vendor/app");
1548            try {
1549                vendorAppDir = vendorAppDir.getCanonicalFile();
1550            } catch (IOException e) {
1551                // failed to look up canonical path, continue with original one
1552            }
1553            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1554                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1555
1556            // Collect all OEM packages.
1557            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1558            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1559                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1560
1561            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1562            mInstaller.moveFiles();
1563
1564            // Prune any system packages that no longer exist.
1565            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1566            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1567            if (!mOnlyCore) {
1568                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1569                while (psit.hasNext()) {
1570                    PackageSetting ps = psit.next();
1571
1572                    /*
1573                     * If this is not a system app, it can't be a
1574                     * disable system app.
1575                     */
1576                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1577                        continue;
1578                    }
1579
1580                    /*
1581                     * If the package is scanned, it's not erased.
1582                     */
1583                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1584                    if (scannedPkg != null) {
1585                        /*
1586                         * If the system app is both scanned and in the
1587                         * disabled packages list, then it must have been
1588                         * added via OTA. Remove it from the currently
1589                         * scanned package so the previously user-installed
1590                         * application can be scanned.
1591                         */
1592                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1593                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1594                                    + ps.name + "; removing system app.  Last known codePath="
1595                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1596                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1597                                    + scannedPkg.mVersionCode);
1598                            removePackageLI(ps, true);
1599                            expectingBetter.put(ps.name, ps.codePath);
1600                        }
1601
1602                        continue;
1603                    }
1604
1605                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1606                        psit.remove();
1607                        logCriticalInfo(Log.WARN, "System package " + ps.name
1608                                + " no longer exists; wiping its data");
1609                        removeDataDirsLI(ps.name);
1610                    } else {
1611                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1612                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1613                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1614                        }
1615                    }
1616                }
1617            }
1618
1619            //look for any incomplete package installations
1620            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1621            //clean up list
1622            for(int i = 0; i < deletePkgsList.size(); i++) {
1623                //clean up here
1624                cleanupInstallFailedPackage(deletePkgsList.get(i));
1625            }
1626            //delete tmp files
1627            deleteTempPackageFiles();
1628
1629            // Remove any shared userIDs that have no associated packages
1630            mSettings.pruneSharedUsersLPw();
1631
1632            if (!mOnlyCore) {
1633                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1634                        SystemClock.uptimeMillis());
1635                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1636
1637                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1638                        scanFlags, 0);
1639
1640                /**
1641                 * Remove disable package settings for any updated system
1642                 * apps that were removed via an OTA. If they're not a
1643                 * previously-updated app, remove them completely.
1644                 * Otherwise, just revoke their system-level permissions.
1645                 */
1646                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1647                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1648                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1649
1650                    String msg;
1651                    if (deletedPkg == null) {
1652                        msg = "Updated system package " + deletedAppName
1653                                + " no longer exists; wiping its data";
1654                        removeDataDirsLI(deletedAppName);
1655                    } else {
1656                        msg = "Updated system app + " + deletedAppName
1657                                + " no longer present; removing system privileges for "
1658                                + deletedAppName;
1659
1660                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1661
1662                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1663                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1664                    }
1665                    logCriticalInfo(Log.WARN, msg);
1666                }
1667
1668                /**
1669                 * Make sure all system apps that we expected to appear on
1670                 * the userdata partition actually showed up. If they never
1671                 * appeared, crawl back and revive the system version.
1672                 */
1673                for (int i = 0; i < expectingBetter.size(); i++) {
1674                    final String packageName = expectingBetter.keyAt(i);
1675                    if (!mPackages.containsKey(packageName)) {
1676                        final File scanFile = expectingBetter.valueAt(i);
1677
1678                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1679                                + " but never showed up; reverting to system");
1680
1681                        final int reparseFlags;
1682                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1683                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1684                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1685                                    | PackageParser.PARSE_IS_PRIVILEGED;
1686                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1687                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1688                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1689                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1690                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1691                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1692                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1693                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1694                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1695                        } else {
1696                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1697                            continue;
1698                        }
1699
1700                        mSettings.enableSystemPackageLPw(packageName);
1701
1702                        try {
1703                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1704                        } catch (PackageManagerException e) {
1705                            Slog.e(TAG, "Failed to parse original system package: "
1706                                    + e.getMessage());
1707                        }
1708                    }
1709                }
1710            }
1711
1712            // Now that we know all of the shared libraries, update all clients to have
1713            // the correct library paths.
1714            updateAllSharedLibrariesLPw();
1715
1716            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1717                // NOTE: We ignore potential failures here during a system scan (like
1718                // the rest of the commands above) because there's precious little we
1719                // can do about it. A settings error is reported, though.
1720                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1721                        false /* force dexopt */, false /* defer dexopt */);
1722            }
1723
1724            // Now that we know all the packages we are keeping,
1725            // read and update their last usage times.
1726            mPackageUsage.readLP();
1727
1728            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1729                    SystemClock.uptimeMillis());
1730            Slog.i(TAG, "Time to scan packages: "
1731                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1732                    + " seconds");
1733
1734            // If the platform SDK has changed since the last time we booted,
1735            // we need to re-grant app permission to catch any new ones that
1736            // appear.  This is really a hack, and means that apps can in some
1737            // cases get permissions that the user didn't initially explicitly
1738            // allow...  it would be nice to have some better way to handle
1739            // this situation.
1740            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1741                    != mSdkVersion;
1742            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1743                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1744                    + "; regranting permissions for internal storage");
1745            mSettings.mInternalSdkPlatform = mSdkVersion;
1746
1747            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1748                    | (regrantPermissions
1749                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1750                            : 0));
1751
1752            // If this is the first boot, and it is a normal boot, then
1753            // we need to initialize the default preferred apps.
1754            if (!mRestoredSettings && !onlyCore) {
1755                mSettings.readDefaultPreferredAppsLPw(this, 0);
1756            }
1757
1758            // If this is first boot after an OTA, and a normal boot, then
1759            // we need to clear code cache directories.
1760            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1761            if (mIsUpgrade && !onlyCore) {
1762                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1763                for (String pkgName : mSettings.mPackages.keySet()) {
1764                    deleteCodeCacheDirsLI(pkgName);
1765                }
1766                mSettings.mFingerprint = Build.FINGERPRINT;
1767            }
1768
1769            // All the changes are done during package scanning.
1770            mSettings.updateInternalDatabaseVersion();
1771
1772            // can downgrade to reader
1773            mSettings.writeLPr();
1774
1775            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1776                    SystemClock.uptimeMillis());
1777
1778
1779            mRequiredVerifierPackage = getRequiredVerifierLPr();
1780        } // synchronized (mPackages)
1781        } // synchronized (mInstallLock)
1782
1783        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1784
1785        // Now after opening every single application zip, make sure they
1786        // are all flushed.  Not really needed, but keeps things nice and
1787        // tidy.
1788        Runtime.getRuntime().gc();
1789    }
1790
1791    @Override
1792    public boolean isFirstBoot() {
1793        return !mRestoredSettings;
1794    }
1795
1796    @Override
1797    public boolean isOnlyCoreApps() {
1798        return mOnlyCore;
1799    }
1800
1801    @Override
1802    public boolean isUpgrade() {
1803        return mIsUpgrade;
1804    }
1805
1806    private String getRequiredVerifierLPr() {
1807        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1808        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1809                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1810
1811        String requiredVerifier = null;
1812
1813        final int N = receivers.size();
1814        for (int i = 0; i < N; i++) {
1815            final ResolveInfo info = receivers.get(i);
1816
1817            if (info.activityInfo == null) {
1818                continue;
1819            }
1820
1821            final String packageName = info.activityInfo.packageName;
1822
1823            final PackageSetting ps = mSettings.mPackages.get(packageName);
1824            if (ps == null) {
1825                continue;
1826            }
1827
1828            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1829            if (!gp.grantedPermissions
1830                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1831                continue;
1832            }
1833
1834            if (requiredVerifier != null) {
1835                throw new RuntimeException("There can be only one required verifier");
1836            }
1837
1838            requiredVerifier = packageName;
1839        }
1840
1841        return requiredVerifier;
1842    }
1843
1844    @Override
1845    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1846            throws RemoteException {
1847        try {
1848            return super.onTransact(code, data, reply, flags);
1849        } catch (RuntimeException e) {
1850            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1851                Slog.wtf(TAG, "Package Manager Crash", e);
1852            }
1853            throw e;
1854        }
1855    }
1856
1857    void cleanupInstallFailedPackage(PackageSetting ps) {
1858        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1859
1860        removeDataDirsLI(ps.name);
1861        if (ps.codePath != null) {
1862            if (ps.codePath.isDirectory()) {
1863                FileUtils.deleteContents(ps.codePath);
1864            }
1865            ps.codePath.delete();
1866        }
1867        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1868            if (ps.resourcePath.isDirectory()) {
1869                FileUtils.deleteContents(ps.resourcePath);
1870            }
1871            ps.resourcePath.delete();
1872        }
1873        mSettings.removePackageLPw(ps.name);
1874    }
1875
1876    static int[] appendInts(int[] cur, int[] add) {
1877        if (add == null) return cur;
1878        if (cur == null) return add;
1879        final int N = add.length;
1880        for (int i=0; i<N; i++) {
1881            cur = appendInt(cur, add[i]);
1882        }
1883        return cur;
1884    }
1885
1886    static int[] removeInts(int[] cur, int[] rem) {
1887        if (rem == null) return cur;
1888        if (cur == null) return cur;
1889        final int N = rem.length;
1890        for (int i=0; i<N; i++) {
1891            cur = removeInt(cur, rem[i]);
1892        }
1893        return cur;
1894    }
1895
1896    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1897        if (!sUserManager.exists(userId)) return null;
1898        final PackageSetting ps = (PackageSetting) p.mExtras;
1899        if (ps == null) {
1900            return null;
1901        }
1902        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1903        final PackageUserState state = ps.readUserState(userId);
1904        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1905                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1906                state, userId);
1907    }
1908
1909    @Override
1910    public boolean isPackageAvailable(String packageName, int userId) {
1911        if (!sUserManager.exists(userId)) return false;
1912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1913        synchronized (mPackages) {
1914            PackageParser.Package p = mPackages.get(packageName);
1915            if (p != null) {
1916                final PackageSetting ps = (PackageSetting) p.mExtras;
1917                if (ps != null) {
1918                    final PackageUserState state = ps.readUserState(userId);
1919                    if (state != null) {
1920                        return PackageParser.isAvailable(state);
1921                    }
1922                }
1923            }
1924        }
1925        return false;
1926    }
1927
1928    @Override
1929    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1930        if (!sUserManager.exists(userId)) return null;
1931        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1932        // reader
1933        synchronized (mPackages) {
1934            PackageParser.Package p = mPackages.get(packageName);
1935            if (DEBUG_PACKAGE_INFO)
1936                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1937            if (p != null) {
1938                return generatePackageInfo(p, flags, userId);
1939            }
1940            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1941                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1942            }
1943        }
1944        return null;
1945    }
1946
1947    @Override
1948    public String[] currentToCanonicalPackageNames(String[] names) {
1949        String[] out = new String[names.length];
1950        // reader
1951        synchronized (mPackages) {
1952            for (int i=names.length-1; i>=0; i--) {
1953                PackageSetting ps = mSettings.mPackages.get(names[i]);
1954                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1955            }
1956        }
1957        return out;
1958    }
1959
1960    @Override
1961    public String[] canonicalToCurrentPackageNames(String[] names) {
1962        String[] out = new String[names.length];
1963        // reader
1964        synchronized (mPackages) {
1965            for (int i=names.length-1; i>=0; i--) {
1966                String cur = mSettings.mRenamedPackages.get(names[i]);
1967                out[i] = cur != null ? cur : names[i];
1968            }
1969        }
1970        return out;
1971    }
1972
1973    @Override
1974    public int getPackageUid(String packageName, int userId) {
1975        if (!sUserManager.exists(userId)) return -1;
1976        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1977        // reader
1978        synchronized (mPackages) {
1979            PackageParser.Package p = mPackages.get(packageName);
1980            if(p != null) {
1981                return UserHandle.getUid(userId, p.applicationInfo.uid);
1982            }
1983            PackageSetting ps = mSettings.mPackages.get(packageName);
1984            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1985                return -1;
1986            }
1987            p = ps.pkg;
1988            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1989        }
1990    }
1991
1992    @Override
1993    public int[] getPackageGids(String packageName) {
1994        // reader
1995        synchronized (mPackages) {
1996            PackageParser.Package p = mPackages.get(packageName);
1997            if (DEBUG_PACKAGE_INFO)
1998                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1999            if (p != null) {
2000                final PackageSetting ps = (PackageSetting)p.mExtras;
2001                return ps.getGids();
2002            }
2003        }
2004        // stupid thing to indicate an error.
2005        return new int[0];
2006    }
2007
2008    static final PermissionInfo generatePermissionInfo(
2009            BasePermission bp, int flags) {
2010        if (bp.perm != null) {
2011            return PackageParser.generatePermissionInfo(bp.perm, flags);
2012        }
2013        PermissionInfo pi = new PermissionInfo();
2014        pi.name = bp.name;
2015        pi.packageName = bp.sourcePackage;
2016        pi.nonLocalizedLabel = bp.name;
2017        pi.protectionLevel = bp.protectionLevel;
2018        return pi;
2019    }
2020
2021    @Override
2022    public PermissionInfo getPermissionInfo(String name, int flags) {
2023        // reader
2024        synchronized (mPackages) {
2025            final BasePermission p = mSettings.mPermissions.get(name);
2026            if (p != null) {
2027                return generatePermissionInfo(p, flags);
2028            }
2029            return null;
2030        }
2031    }
2032
2033    @Override
2034    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2035        // reader
2036        synchronized (mPackages) {
2037            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2038            for (BasePermission p : mSettings.mPermissions.values()) {
2039                if (group == null) {
2040                    if (p.perm == null || p.perm.info.group == null) {
2041                        out.add(generatePermissionInfo(p, flags));
2042                    }
2043                } else {
2044                    if (p.perm != null && group.equals(p.perm.info.group)) {
2045                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2046                    }
2047                }
2048            }
2049
2050            if (out.size() > 0) {
2051                return out;
2052            }
2053            return mPermissionGroups.containsKey(group) ? out : null;
2054        }
2055    }
2056
2057    @Override
2058    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2059        // reader
2060        synchronized (mPackages) {
2061            return PackageParser.generatePermissionGroupInfo(
2062                    mPermissionGroups.get(name), flags);
2063        }
2064    }
2065
2066    @Override
2067    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2068        // reader
2069        synchronized (mPackages) {
2070            final int N = mPermissionGroups.size();
2071            ArrayList<PermissionGroupInfo> out
2072                    = new ArrayList<PermissionGroupInfo>(N);
2073            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2074                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2075            }
2076            return out;
2077        }
2078    }
2079
2080    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2081            int userId) {
2082        if (!sUserManager.exists(userId)) return null;
2083        PackageSetting ps = mSettings.mPackages.get(packageName);
2084        if (ps != null) {
2085            if (ps.pkg == null) {
2086                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2087                        flags, userId);
2088                if (pInfo != null) {
2089                    return pInfo.applicationInfo;
2090                }
2091                return null;
2092            }
2093            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2094                    ps.readUserState(userId), userId);
2095        }
2096        return null;
2097    }
2098
2099    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2100            int userId) {
2101        if (!sUserManager.exists(userId)) return null;
2102        PackageSetting ps = mSettings.mPackages.get(packageName);
2103        if (ps != null) {
2104            PackageParser.Package pkg = ps.pkg;
2105            if (pkg == null) {
2106                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2107                    return null;
2108                }
2109                // Only data remains, so we aren't worried about code paths
2110                pkg = new PackageParser.Package(packageName);
2111                pkg.applicationInfo.packageName = packageName;
2112                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2113                pkg.applicationInfo.dataDir =
2114                        getDataPathForPackage(packageName, 0).getPath();
2115                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2116                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2117            }
2118            return generatePackageInfo(pkg, flags, userId);
2119        }
2120        return null;
2121    }
2122
2123    @Override
2124    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2125        if (!sUserManager.exists(userId)) return null;
2126        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2127        // writer
2128        synchronized (mPackages) {
2129            PackageParser.Package p = mPackages.get(packageName);
2130            if (DEBUG_PACKAGE_INFO) Log.v(
2131                    TAG, "getApplicationInfo " + packageName
2132                    + ": " + p);
2133            if (p != null) {
2134                PackageSetting ps = mSettings.mPackages.get(packageName);
2135                if (ps == null) return null;
2136                // Note: isEnabledLP() does not apply here - always return info
2137                return PackageParser.generateApplicationInfo(
2138                        p, flags, ps.readUserState(userId), userId);
2139            }
2140            if ("android".equals(packageName)||"system".equals(packageName)) {
2141                return mAndroidApplication;
2142            }
2143            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2144                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2145            }
2146        }
2147        return null;
2148    }
2149
2150
2151    @Override
2152    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2153        mContext.enforceCallingOrSelfPermission(
2154                android.Manifest.permission.CLEAR_APP_CACHE, null);
2155        // Queue up an async operation since clearing cache may take a little while.
2156        mHandler.post(new Runnable() {
2157            public void run() {
2158                mHandler.removeCallbacks(this);
2159                int retCode = -1;
2160                synchronized (mInstallLock) {
2161                    retCode = mInstaller.freeCache(freeStorageSize);
2162                    if (retCode < 0) {
2163                        Slog.w(TAG, "Couldn't clear application caches");
2164                    }
2165                }
2166                if (observer != null) {
2167                    try {
2168                        observer.onRemoveCompleted(null, (retCode >= 0));
2169                    } catch (RemoteException e) {
2170                        Slog.w(TAG, "RemoveException when invoking call back");
2171                    }
2172                }
2173            }
2174        });
2175    }
2176
2177    @Override
2178    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2179        mContext.enforceCallingOrSelfPermission(
2180                android.Manifest.permission.CLEAR_APP_CACHE, null);
2181        // Queue up an async operation since clearing cache may take a little while.
2182        mHandler.post(new Runnable() {
2183            public void run() {
2184                mHandler.removeCallbacks(this);
2185                int retCode = -1;
2186                synchronized (mInstallLock) {
2187                    retCode = mInstaller.freeCache(freeStorageSize);
2188                    if (retCode < 0) {
2189                        Slog.w(TAG, "Couldn't clear application caches");
2190                    }
2191                }
2192                if(pi != null) {
2193                    try {
2194                        // Callback via pending intent
2195                        int code = (retCode >= 0) ? 1 : 0;
2196                        pi.sendIntent(null, code, null,
2197                                null, null);
2198                    } catch (SendIntentException e1) {
2199                        Slog.i(TAG, "Failed to send pending intent");
2200                    }
2201                }
2202            }
2203        });
2204    }
2205
2206    void freeStorage(long freeStorageSize) throws IOException {
2207        synchronized (mInstallLock) {
2208            if (mInstaller.freeCache(freeStorageSize) < 0) {
2209                throw new IOException("Failed to free enough space");
2210            }
2211        }
2212    }
2213
2214    @Override
2215    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2216        if (!sUserManager.exists(userId)) return null;
2217        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2218        synchronized (mPackages) {
2219            PackageParser.Activity a = mActivities.mActivities.get(component);
2220
2221            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2222            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2223                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2224                if (ps == null) return null;
2225                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2226                        userId);
2227            }
2228            if (mResolveComponentName.equals(component)) {
2229                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2230                        new PackageUserState(), userId);
2231            }
2232        }
2233        return null;
2234    }
2235
2236    @Override
2237    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2238            String resolvedType) {
2239        synchronized (mPackages) {
2240            PackageParser.Activity a = mActivities.mActivities.get(component);
2241            if (a == null) {
2242                return false;
2243            }
2244            for (int i=0; i<a.intents.size(); i++) {
2245                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2246                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2247                    return true;
2248                }
2249            }
2250            return false;
2251        }
2252    }
2253
2254    @Override
2255    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2256        if (!sUserManager.exists(userId)) return null;
2257        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2258        synchronized (mPackages) {
2259            PackageParser.Activity a = mReceivers.mActivities.get(component);
2260            if (DEBUG_PACKAGE_INFO) Log.v(
2261                TAG, "getReceiverInfo " + component + ": " + a);
2262            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2264                if (ps == null) return null;
2265                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2266                        userId);
2267            }
2268        }
2269        return null;
2270    }
2271
2272    @Override
2273    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2274        if (!sUserManager.exists(userId)) return null;
2275        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2276        synchronized (mPackages) {
2277            PackageParser.Service s = mServices.mServices.get(component);
2278            if (DEBUG_PACKAGE_INFO) Log.v(
2279                TAG, "getServiceInfo " + component + ": " + s);
2280            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2281                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2282                if (ps == null) return null;
2283                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2284                        userId);
2285            }
2286        }
2287        return null;
2288    }
2289
2290    @Override
2291    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2292        if (!sUserManager.exists(userId)) return null;
2293        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2294        synchronized (mPackages) {
2295            PackageParser.Provider p = mProviders.mProviders.get(component);
2296            if (DEBUG_PACKAGE_INFO) Log.v(
2297                TAG, "getProviderInfo " + component + ": " + p);
2298            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2299                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2300                if (ps == null) return null;
2301                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2302                        userId);
2303            }
2304        }
2305        return null;
2306    }
2307
2308    @Override
2309    public String[] getSystemSharedLibraryNames() {
2310        Set<String> libSet;
2311        synchronized (mPackages) {
2312            libSet = mSharedLibraries.keySet();
2313            int size = libSet.size();
2314            if (size > 0) {
2315                String[] libs = new String[size];
2316                libSet.toArray(libs);
2317                return libs;
2318            }
2319        }
2320        return null;
2321    }
2322
2323    @Override
2324    public FeatureInfo[] getSystemAvailableFeatures() {
2325        Collection<FeatureInfo> featSet;
2326        synchronized (mPackages) {
2327            featSet = mAvailableFeatures.values();
2328            int size = featSet.size();
2329            if (size > 0) {
2330                FeatureInfo[] features = new FeatureInfo[size+1];
2331                featSet.toArray(features);
2332                FeatureInfo fi = new FeatureInfo();
2333                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2334                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2335                features[size] = fi;
2336                return features;
2337            }
2338        }
2339        return null;
2340    }
2341
2342    @Override
2343    public boolean hasSystemFeature(String name) {
2344        synchronized (mPackages) {
2345            return mAvailableFeatures.containsKey(name);
2346        }
2347    }
2348
2349    private void checkValidCaller(int uid, int userId) {
2350        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2351            return;
2352
2353        throw new SecurityException("Caller uid=" + uid
2354                + " is not privileged to communicate with user=" + userId);
2355    }
2356
2357    @Override
2358    public int checkPermission(String permName, String pkgName) {
2359        synchronized (mPackages) {
2360            PackageParser.Package p = mPackages.get(pkgName);
2361            if (p != null && p.mExtras != null) {
2362                PackageSetting ps = (PackageSetting)p.mExtras;
2363                if (ps.sharedUser != null) {
2364                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2365                        return PackageManager.PERMISSION_GRANTED;
2366                    }
2367                } else if (ps.grantedPermissions.contains(permName)) {
2368                    return PackageManager.PERMISSION_GRANTED;
2369                }
2370            }
2371        }
2372        return PackageManager.PERMISSION_DENIED;
2373    }
2374
2375    @Override
2376    public int checkUidPermission(String permName, int uid) {
2377        synchronized (mPackages) {
2378            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2379            if (obj != null) {
2380                GrantedPermissions gp = (GrantedPermissions)obj;
2381                if (gp.grantedPermissions.contains(permName)) {
2382                    return PackageManager.PERMISSION_GRANTED;
2383                }
2384            } else {
2385                ArraySet<String> perms = mSystemPermissions.get(uid);
2386                if (perms != null && perms.contains(permName)) {
2387                    return PackageManager.PERMISSION_GRANTED;
2388                }
2389            }
2390        }
2391        return PackageManager.PERMISSION_DENIED;
2392    }
2393
2394    /**
2395     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2396     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2397     * @param checkShell TODO(yamasani):
2398     * @param message the message to log on security exception
2399     */
2400    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2401            boolean checkShell, String message) {
2402        if (userId < 0) {
2403            throw new IllegalArgumentException("Invalid userId " + userId);
2404        }
2405        if (checkShell) {
2406            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2407        }
2408        if (userId == UserHandle.getUserId(callingUid)) return;
2409        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2410            if (requireFullPermission) {
2411                mContext.enforceCallingOrSelfPermission(
2412                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2413            } else {
2414                try {
2415                    mContext.enforceCallingOrSelfPermission(
2416                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2417                } catch (SecurityException se) {
2418                    mContext.enforceCallingOrSelfPermission(
2419                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2420                }
2421            }
2422        }
2423    }
2424
2425    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2426        if (callingUid == Process.SHELL_UID) {
2427            if (userHandle >= 0
2428                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2429                throw new SecurityException("Shell does not have permission to access user "
2430                        + userHandle);
2431            } else if (userHandle < 0) {
2432                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2433                        + Debug.getCallers(3));
2434            }
2435        }
2436    }
2437
2438    private BasePermission findPermissionTreeLP(String permName) {
2439        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2440            if (permName.startsWith(bp.name) &&
2441                    permName.length() > bp.name.length() &&
2442                    permName.charAt(bp.name.length()) == '.') {
2443                return bp;
2444            }
2445        }
2446        return null;
2447    }
2448
2449    private BasePermission checkPermissionTreeLP(String permName) {
2450        if (permName != null) {
2451            BasePermission bp = findPermissionTreeLP(permName);
2452            if (bp != null) {
2453                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2454                    return bp;
2455                }
2456                throw new SecurityException("Calling uid "
2457                        + Binder.getCallingUid()
2458                        + " is not allowed to add to permission tree "
2459                        + bp.name + " owned by uid " + bp.uid);
2460            }
2461        }
2462        throw new SecurityException("No permission tree found for " + permName);
2463    }
2464
2465    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2466        if (s1 == null) {
2467            return s2 == null;
2468        }
2469        if (s2 == null) {
2470            return false;
2471        }
2472        if (s1.getClass() != s2.getClass()) {
2473            return false;
2474        }
2475        return s1.equals(s2);
2476    }
2477
2478    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2479        if (pi1.icon != pi2.icon) return false;
2480        if (pi1.logo != pi2.logo) return false;
2481        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2482        if (!compareStrings(pi1.name, pi2.name)) return false;
2483        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2484        // We'll take care of setting this one.
2485        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2486        // These are not currently stored in settings.
2487        //if (!compareStrings(pi1.group, pi2.group)) return false;
2488        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2489        //if (pi1.labelRes != pi2.labelRes) return false;
2490        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2491        return true;
2492    }
2493
2494    int permissionInfoFootprint(PermissionInfo info) {
2495        int size = info.name.length();
2496        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2497        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2498        return size;
2499    }
2500
2501    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2502        int size = 0;
2503        for (BasePermission perm : mSettings.mPermissions.values()) {
2504            if (perm.uid == tree.uid) {
2505                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2506            }
2507        }
2508        return size;
2509    }
2510
2511    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2512        // We calculate the max size of permissions defined by this uid and throw
2513        // if that plus the size of 'info' would exceed our stated maximum.
2514        if (tree.uid != Process.SYSTEM_UID) {
2515            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2516            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2517                throw new SecurityException("Permission tree size cap exceeded");
2518            }
2519        }
2520    }
2521
2522    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2523        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2524            throw new SecurityException("Label must be specified in permission");
2525        }
2526        BasePermission tree = checkPermissionTreeLP(info.name);
2527        BasePermission bp = mSettings.mPermissions.get(info.name);
2528        boolean added = bp == null;
2529        boolean changed = true;
2530        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2531        if (added) {
2532            enforcePermissionCapLocked(info, tree);
2533            bp = new BasePermission(info.name, tree.sourcePackage,
2534                    BasePermission.TYPE_DYNAMIC);
2535        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2536            throw new SecurityException(
2537                    "Not allowed to modify non-dynamic permission "
2538                    + info.name);
2539        } else {
2540            if (bp.protectionLevel == fixedLevel
2541                    && bp.perm.owner.equals(tree.perm.owner)
2542                    && bp.uid == tree.uid
2543                    && comparePermissionInfos(bp.perm.info, info)) {
2544                changed = false;
2545            }
2546        }
2547        bp.protectionLevel = fixedLevel;
2548        info = new PermissionInfo(info);
2549        info.protectionLevel = fixedLevel;
2550        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2551        bp.perm.info.packageName = tree.perm.info.packageName;
2552        bp.uid = tree.uid;
2553        if (added) {
2554            mSettings.mPermissions.put(info.name, bp);
2555        }
2556        if (changed) {
2557            if (!async) {
2558                mSettings.writeLPr();
2559            } else {
2560                scheduleWriteSettingsLocked();
2561            }
2562        }
2563        return added;
2564    }
2565
2566    @Override
2567    public boolean addPermission(PermissionInfo info) {
2568        synchronized (mPackages) {
2569            return addPermissionLocked(info, false);
2570        }
2571    }
2572
2573    @Override
2574    public boolean addPermissionAsync(PermissionInfo info) {
2575        synchronized (mPackages) {
2576            return addPermissionLocked(info, true);
2577        }
2578    }
2579
2580    @Override
2581    public void removePermission(String name) {
2582        synchronized (mPackages) {
2583            checkPermissionTreeLP(name);
2584            BasePermission bp = mSettings.mPermissions.get(name);
2585            if (bp != null) {
2586                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2587                    throw new SecurityException(
2588                            "Not allowed to modify non-dynamic permission "
2589                            + name);
2590                }
2591                mSettings.mPermissions.remove(name);
2592                mSettings.writeLPr();
2593            }
2594        }
2595    }
2596
2597    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2598        int index = pkg.requestedPermissions.indexOf(bp.name);
2599        if (index == -1) {
2600            throw new SecurityException("Package " + pkg.packageName
2601                    + " has not requested permission " + bp.name);
2602        }
2603        boolean isNormal =
2604                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2605                        == PermissionInfo.PROTECTION_NORMAL);
2606        boolean isDangerous =
2607                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2608                        == PermissionInfo.PROTECTION_DANGEROUS);
2609        boolean isDevelopment =
2610                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2611
2612        if (!isNormal && !isDangerous && !isDevelopment) {
2613            throw new SecurityException("Permission " + bp.name
2614                    + " is not a changeable permission type");
2615        }
2616
2617        if (isNormal || isDangerous) {
2618            if (pkg.requestedPermissionsRequired.get(index)) {
2619                throw new SecurityException("Can't change " + bp.name
2620                        + ". It is required by the application");
2621            }
2622        }
2623    }
2624
2625    @Override
2626    public void grantPermission(String packageName, String permissionName) {
2627        mContext.enforceCallingOrSelfPermission(
2628                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2629        synchronized (mPackages) {
2630            final PackageParser.Package pkg = mPackages.get(packageName);
2631            if (pkg == null) {
2632                throw new IllegalArgumentException("Unknown package: " + packageName);
2633            }
2634            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2635            if (bp == null) {
2636                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2637            }
2638
2639            checkGrantRevokePermissions(pkg, bp);
2640
2641            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2642            if (ps == null) {
2643                return;
2644            }
2645            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2646            if (gp.grantedPermissions.add(permissionName)) {
2647                if (ps.haveGids) {
2648                    gp.gids = appendInts(gp.gids, bp.gids);
2649                }
2650                mSettings.writeLPr();
2651            }
2652        }
2653    }
2654
2655    @Override
2656    public void revokePermission(String packageName, String permissionName) {
2657        int changedAppId = -1;
2658
2659        synchronized (mPackages) {
2660            final PackageParser.Package pkg = mPackages.get(packageName);
2661            if (pkg == null) {
2662                throw new IllegalArgumentException("Unknown package: " + packageName);
2663            }
2664            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2665                mContext.enforceCallingOrSelfPermission(
2666                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2667            }
2668            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2669            if (bp == null) {
2670                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2671            }
2672
2673            checkGrantRevokePermissions(pkg, bp);
2674
2675            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2676            if (ps == null) {
2677                return;
2678            }
2679            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2680            if (gp.grantedPermissions.remove(permissionName)) {
2681                gp.grantedPermissions.remove(permissionName);
2682                if (ps.haveGids) {
2683                    gp.gids = removeInts(gp.gids, bp.gids);
2684                }
2685                mSettings.writeLPr();
2686                changedAppId = ps.appId;
2687            }
2688        }
2689
2690        if (changedAppId >= 0) {
2691            // We changed the perm on someone, kill its processes.
2692            IActivityManager am = ActivityManagerNative.getDefault();
2693            if (am != null) {
2694                final int callingUserId = UserHandle.getCallingUserId();
2695                final long ident = Binder.clearCallingIdentity();
2696                try {
2697                    //XXX we should only revoke for the calling user's app permissions,
2698                    // but for now we impact all users.
2699                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2700                    //        "revoke " + permissionName);
2701                    int[] users = sUserManager.getUserIds();
2702                    for (int user : users) {
2703                        am.killUid(UserHandle.getUid(user, changedAppId),
2704                                "revoke " + permissionName);
2705                    }
2706                } catch (RemoteException e) {
2707                } finally {
2708                    Binder.restoreCallingIdentity(ident);
2709                }
2710            }
2711        }
2712    }
2713
2714    @Override
2715    public boolean isProtectedBroadcast(String actionName) {
2716        synchronized (mPackages) {
2717            return mProtectedBroadcasts.contains(actionName);
2718        }
2719    }
2720
2721    @Override
2722    public int checkSignatures(String pkg1, String pkg2) {
2723        synchronized (mPackages) {
2724            final PackageParser.Package p1 = mPackages.get(pkg1);
2725            final PackageParser.Package p2 = mPackages.get(pkg2);
2726            if (p1 == null || p1.mExtras == null
2727                    || p2 == null || p2.mExtras == null) {
2728                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2729            }
2730            return compareSignatures(p1.mSignatures, p2.mSignatures);
2731        }
2732    }
2733
2734    @Override
2735    public int checkUidSignatures(int uid1, int uid2) {
2736        // Map to base uids.
2737        uid1 = UserHandle.getAppId(uid1);
2738        uid2 = UserHandle.getAppId(uid2);
2739        // reader
2740        synchronized (mPackages) {
2741            Signature[] s1;
2742            Signature[] s2;
2743            Object obj = mSettings.getUserIdLPr(uid1);
2744            if (obj != null) {
2745                if (obj instanceof SharedUserSetting) {
2746                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2747                } else if (obj instanceof PackageSetting) {
2748                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2749                } else {
2750                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2751                }
2752            } else {
2753                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2754            }
2755            obj = mSettings.getUserIdLPr(uid2);
2756            if (obj != null) {
2757                if (obj instanceof SharedUserSetting) {
2758                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2759                } else if (obj instanceof PackageSetting) {
2760                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2761                } else {
2762                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2763                }
2764            } else {
2765                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2766            }
2767            return compareSignatures(s1, s2);
2768        }
2769    }
2770
2771    /**
2772     * Compares two sets of signatures. Returns:
2773     * <br />
2774     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2775     * <br />
2776     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2777     * <br />
2778     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2779     * <br />
2780     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2781     * <br />
2782     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2783     */
2784    static int compareSignatures(Signature[] s1, Signature[] s2) {
2785        if (s1 == null) {
2786            return s2 == null
2787                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2788                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2789        }
2790
2791        if (s2 == null) {
2792            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2793        }
2794
2795        if (s1.length != s2.length) {
2796            return PackageManager.SIGNATURE_NO_MATCH;
2797        }
2798
2799        // Since both signature sets are of size 1, we can compare without HashSets.
2800        if (s1.length == 1) {
2801            return s1[0].equals(s2[0]) ?
2802                    PackageManager.SIGNATURE_MATCH :
2803                    PackageManager.SIGNATURE_NO_MATCH;
2804        }
2805
2806        ArraySet<Signature> set1 = new ArraySet<Signature>();
2807        for (Signature sig : s1) {
2808            set1.add(sig);
2809        }
2810        ArraySet<Signature> set2 = new ArraySet<Signature>();
2811        for (Signature sig : s2) {
2812            set2.add(sig);
2813        }
2814        // Make sure s2 contains all signatures in s1.
2815        if (set1.equals(set2)) {
2816            return PackageManager.SIGNATURE_MATCH;
2817        }
2818        return PackageManager.SIGNATURE_NO_MATCH;
2819    }
2820
2821    /**
2822     * If the database version for this type of package (internal storage or
2823     * external storage) is less than the version where package signatures
2824     * were updated, return true.
2825     */
2826    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2827        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2828                DatabaseVersion.SIGNATURE_END_ENTITY))
2829                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2830                        DatabaseVersion.SIGNATURE_END_ENTITY));
2831    }
2832
2833    /**
2834     * Used for backward compatibility to make sure any packages with
2835     * certificate chains get upgraded to the new style. {@code existingSigs}
2836     * will be in the old format (since they were stored on disk from before the
2837     * system upgrade) and {@code scannedSigs} will be in the newer format.
2838     */
2839    private int compareSignaturesCompat(PackageSignatures existingSigs,
2840            PackageParser.Package scannedPkg) {
2841        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2842            return PackageManager.SIGNATURE_NO_MATCH;
2843        }
2844
2845        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2846        for (Signature sig : existingSigs.mSignatures) {
2847            existingSet.add(sig);
2848        }
2849        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2850        for (Signature sig : scannedPkg.mSignatures) {
2851            try {
2852                Signature[] chainSignatures = sig.getChainSignatures();
2853                for (Signature chainSig : chainSignatures) {
2854                    scannedCompatSet.add(chainSig);
2855                }
2856            } catch (CertificateEncodingException e) {
2857                scannedCompatSet.add(sig);
2858            }
2859        }
2860        /*
2861         * Make sure the expanded scanned set contains all signatures in the
2862         * existing one.
2863         */
2864        if (scannedCompatSet.equals(existingSet)) {
2865            // Migrate the old signatures to the new scheme.
2866            existingSigs.assignSignatures(scannedPkg.mSignatures);
2867            // The new KeySets will be re-added later in the scanning process.
2868            synchronized (mPackages) {
2869                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2870            }
2871            return PackageManager.SIGNATURE_MATCH;
2872        }
2873        return PackageManager.SIGNATURE_NO_MATCH;
2874    }
2875
2876    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2877        if (isExternal(scannedPkg)) {
2878            return mSettings.isExternalDatabaseVersionOlderThan(
2879                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2880        } else {
2881            return mSettings.isInternalDatabaseVersionOlderThan(
2882                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2883        }
2884    }
2885
2886    private int compareSignaturesRecover(PackageSignatures existingSigs,
2887            PackageParser.Package scannedPkg) {
2888        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2889            return PackageManager.SIGNATURE_NO_MATCH;
2890        }
2891
2892        String msg = null;
2893        try {
2894            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2895                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2896                        + scannedPkg.packageName);
2897                return PackageManager.SIGNATURE_MATCH;
2898            }
2899        } catch (CertificateException e) {
2900            msg = e.getMessage();
2901        }
2902
2903        logCriticalInfo(Log.INFO,
2904                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2905        return PackageManager.SIGNATURE_NO_MATCH;
2906    }
2907
2908    @Override
2909    public String[] getPackagesForUid(int uid) {
2910        uid = UserHandle.getAppId(uid);
2911        // reader
2912        synchronized (mPackages) {
2913            Object obj = mSettings.getUserIdLPr(uid);
2914            if (obj instanceof SharedUserSetting) {
2915                final SharedUserSetting sus = (SharedUserSetting) obj;
2916                final int N = sus.packages.size();
2917                final String[] res = new String[N];
2918                final Iterator<PackageSetting> it = sus.packages.iterator();
2919                int i = 0;
2920                while (it.hasNext()) {
2921                    res[i++] = it.next().name;
2922                }
2923                return res;
2924            } else if (obj instanceof PackageSetting) {
2925                final PackageSetting ps = (PackageSetting) obj;
2926                return new String[] { ps.name };
2927            }
2928        }
2929        return null;
2930    }
2931
2932    @Override
2933    public String getNameForUid(int uid) {
2934        // reader
2935        synchronized (mPackages) {
2936            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2937            if (obj instanceof SharedUserSetting) {
2938                final SharedUserSetting sus = (SharedUserSetting) obj;
2939                return sus.name + ":" + sus.userId;
2940            } else if (obj instanceof PackageSetting) {
2941                final PackageSetting ps = (PackageSetting) obj;
2942                return ps.name;
2943            }
2944        }
2945        return null;
2946    }
2947
2948    @Override
2949    public int getUidForSharedUser(String sharedUserName) {
2950        if(sharedUserName == null) {
2951            return -1;
2952        }
2953        // reader
2954        synchronized (mPackages) {
2955            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2956            if (suid == null) {
2957                return -1;
2958            }
2959            return suid.userId;
2960        }
2961    }
2962
2963    @Override
2964    public int getFlagsForUid(int uid) {
2965        synchronized (mPackages) {
2966            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2967            if (obj instanceof SharedUserSetting) {
2968                final SharedUserSetting sus = (SharedUserSetting) obj;
2969                return sus.pkgFlags;
2970            } else if (obj instanceof PackageSetting) {
2971                final PackageSetting ps = (PackageSetting) obj;
2972                return ps.pkgFlags;
2973            }
2974        }
2975        return 0;
2976    }
2977
2978    @Override
2979    public boolean isUidPrivileged(int uid) {
2980        uid = UserHandle.getAppId(uid);
2981        // reader
2982        synchronized (mPackages) {
2983            Object obj = mSettings.getUserIdLPr(uid);
2984            if (obj instanceof SharedUserSetting) {
2985                final SharedUserSetting sus = (SharedUserSetting) obj;
2986                final Iterator<PackageSetting> it = sus.packages.iterator();
2987                while (it.hasNext()) {
2988                    if (it.next().isPrivileged()) {
2989                        return true;
2990                    }
2991                }
2992            } else if (obj instanceof PackageSetting) {
2993                final PackageSetting ps = (PackageSetting) obj;
2994                return ps.isPrivileged();
2995            }
2996        }
2997        return false;
2998    }
2999
3000    @Override
3001    public String[] getAppOpPermissionPackages(String permissionName) {
3002        synchronized (mPackages) {
3003            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3004            if (pkgs == null) {
3005                return null;
3006            }
3007            return pkgs.toArray(new String[pkgs.size()]);
3008        }
3009    }
3010
3011    @Override
3012    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3013            int flags, int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3016        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3017        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3018    }
3019
3020    @Override
3021    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3022            IntentFilter filter, int match, ComponentName activity) {
3023        final int userId = UserHandle.getCallingUserId();
3024        if (DEBUG_PREFERRED) {
3025            Log.v(TAG, "setLastChosenActivity intent=" + intent
3026                + " resolvedType=" + resolvedType
3027                + " flags=" + flags
3028                + " filter=" + filter
3029                + " match=" + match
3030                + " activity=" + activity);
3031            filter.dump(new PrintStreamPrinter(System.out), "    ");
3032        }
3033        intent.setComponent(null);
3034        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3035        // Find any earlier preferred or last chosen entries and nuke them
3036        findPreferredActivity(intent, resolvedType,
3037                flags, query, 0, false, true, false, userId);
3038        // Add the new activity as the last chosen for this filter
3039        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3040                "Setting last chosen");
3041    }
3042
3043    @Override
3044    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3045        final int userId = UserHandle.getCallingUserId();
3046        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3047        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3048        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3049                false, false, false, userId);
3050    }
3051
3052    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3053            int flags, List<ResolveInfo> query, int userId) {
3054        if (query != null) {
3055            final int N = query.size();
3056            if (N == 1) {
3057                return query.get(0);
3058            } else if (N > 1) {
3059                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3060                // If there is more than one activity with the same priority,
3061                // then let the user decide between them.
3062                ResolveInfo r0 = query.get(0);
3063                ResolveInfo r1 = query.get(1);
3064                if (DEBUG_INTENT_MATCHING || debug) {
3065                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3066                            + r1.activityInfo.name + "=" + r1.priority);
3067                }
3068                // If the first activity has a higher priority, or a different
3069                // default, then it is always desireable to pick it.
3070                if (r0.priority != r1.priority
3071                        || r0.preferredOrder != r1.preferredOrder
3072                        || r0.isDefault != r1.isDefault) {
3073                    return query.get(0);
3074                }
3075                // If we have saved a preference for a preferred activity for
3076                // this Intent, use that.
3077                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3078                        flags, query, r0.priority, true, false, debug, userId);
3079                if (ri != null) {
3080                    return ri;
3081                }
3082                if (userId != 0) {
3083                    ri = new ResolveInfo(mResolveInfo);
3084                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3085                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3086                            ri.activityInfo.applicationInfo);
3087                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3088                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3089                    return ri;
3090                }
3091                return mResolveInfo;
3092            }
3093        }
3094        return null;
3095    }
3096
3097    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3098            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3099        final int N = query.size();
3100        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3101                .get(userId);
3102        // Get the list of persistent preferred activities that handle the intent
3103        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3104        List<PersistentPreferredActivity> pprefs = ppir != null
3105                ? ppir.queryIntent(intent, resolvedType,
3106                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3107                : null;
3108        if (pprefs != null && pprefs.size() > 0) {
3109            final int M = pprefs.size();
3110            for (int i=0; i<M; i++) {
3111                final PersistentPreferredActivity ppa = pprefs.get(i);
3112                if (DEBUG_PREFERRED || debug) {
3113                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3114                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3115                            + "\n  component=" + ppa.mComponent);
3116                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3117                }
3118                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3119                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3120                if (DEBUG_PREFERRED || debug) {
3121                    Slog.v(TAG, "Found persistent preferred activity:");
3122                    if (ai != null) {
3123                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3124                    } else {
3125                        Slog.v(TAG, "  null");
3126                    }
3127                }
3128                if (ai == null) {
3129                    // This previously registered persistent preferred activity
3130                    // component is no longer known. Ignore it and do NOT remove it.
3131                    continue;
3132                }
3133                for (int j=0; j<N; j++) {
3134                    final ResolveInfo ri = query.get(j);
3135                    if (!ri.activityInfo.applicationInfo.packageName
3136                            .equals(ai.applicationInfo.packageName)) {
3137                        continue;
3138                    }
3139                    if (!ri.activityInfo.name.equals(ai.name)) {
3140                        continue;
3141                    }
3142                    //  Found a persistent preference that can handle the intent.
3143                    if (DEBUG_PREFERRED || debug) {
3144                        Slog.v(TAG, "Returning persistent preferred activity: " +
3145                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3146                    }
3147                    return ri;
3148                }
3149            }
3150        }
3151        return null;
3152    }
3153
3154    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3155            List<ResolveInfo> query, int priority, boolean always,
3156            boolean removeMatches, boolean debug, int userId) {
3157        if (!sUserManager.exists(userId)) return null;
3158        // writer
3159        synchronized (mPackages) {
3160            if (intent.getSelector() != null) {
3161                intent = intent.getSelector();
3162            }
3163            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3164
3165            // Try to find a matching persistent preferred activity.
3166            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3167                    debug, userId);
3168
3169            // If a persistent preferred activity matched, use it.
3170            if (pri != null) {
3171                return pri;
3172            }
3173
3174            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3175            // Get the list of preferred activities that handle the intent
3176            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3177            List<PreferredActivity> prefs = pir != null
3178                    ? pir.queryIntent(intent, resolvedType,
3179                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3180                    : null;
3181            if (prefs != null && prefs.size() > 0) {
3182                boolean changed = false;
3183                try {
3184                    // First figure out how good the original match set is.
3185                    // We will only allow preferred activities that came
3186                    // from the same match quality.
3187                    int match = 0;
3188
3189                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3190
3191                    final int N = query.size();
3192                    for (int j=0; j<N; j++) {
3193                        final ResolveInfo ri = query.get(j);
3194                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3195                                + ": 0x" + Integer.toHexString(match));
3196                        if (ri.match > match) {
3197                            match = ri.match;
3198                        }
3199                    }
3200
3201                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3202                            + Integer.toHexString(match));
3203
3204                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3205                    final int M = prefs.size();
3206                    for (int i=0; i<M; i++) {
3207                        final PreferredActivity pa = prefs.get(i);
3208                        if (DEBUG_PREFERRED || debug) {
3209                            Slog.v(TAG, "Checking PreferredActivity ds="
3210                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3211                                    + "\n  component=" + pa.mPref.mComponent);
3212                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3213                        }
3214                        if (pa.mPref.mMatch != match) {
3215                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3216                                    + Integer.toHexString(pa.mPref.mMatch));
3217                            continue;
3218                        }
3219                        // If it's not an "always" type preferred activity and that's what we're
3220                        // looking for, skip it.
3221                        if (always && !pa.mPref.mAlways) {
3222                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3223                            continue;
3224                        }
3225                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3226                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3227                        if (DEBUG_PREFERRED || debug) {
3228                            Slog.v(TAG, "Found preferred activity:");
3229                            if (ai != null) {
3230                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3231                            } else {
3232                                Slog.v(TAG, "  null");
3233                            }
3234                        }
3235                        if (ai == null) {
3236                            // This previously registered preferred activity
3237                            // component is no longer known.  Most likely an update
3238                            // to the app was installed and in the new version this
3239                            // component no longer exists.  Clean it up by removing
3240                            // it from the preferred activities list, and skip it.
3241                            Slog.w(TAG, "Removing dangling preferred activity: "
3242                                    + pa.mPref.mComponent);
3243                            pir.removeFilter(pa);
3244                            changed = true;
3245                            continue;
3246                        }
3247                        for (int j=0; j<N; j++) {
3248                            final ResolveInfo ri = query.get(j);
3249                            if (!ri.activityInfo.applicationInfo.packageName
3250                                    .equals(ai.applicationInfo.packageName)) {
3251                                continue;
3252                            }
3253                            if (!ri.activityInfo.name.equals(ai.name)) {
3254                                continue;
3255                            }
3256
3257                            if (removeMatches) {
3258                                pir.removeFilter(pa);
3259                                changed = true;
3260                                if (DEBUG_PREFERRED) {
3261                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3262                                }
3263                                break;
3264                            }
3265
3266                            // Okay we found a previously set preferred or last chosen app.
3267                            // If the result set is different from when this
3268                            // was created, we need to clear it and re-ask the
3269                            // user their preference, if we're looking for an "always" type entry.
3270                            if (always && !pa.mPref.sameSet(query, priority)) {
3271                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3272                                        + intent + " type " + resolvedType);
3273                                if (DEBUG_PREFERRED) {
3274                                    Slog.v(TAG, "Removing preferred activity since set changed "
3275                                            + pa.mPref.mComponent);
3276                                }
3277                                pir.removeFilter(pa);
3278                                // Re-add the filter as a "last chosen" entry (!always)
3279                                PreferredActivity lastChosen = new PreferredActivity(
3280                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3281                                pir.addFilter(lastChosen);
3282                                changed = true;
3283                                return null;
3284                            }
3285
3286                            // Yay! Either the set matched or we're looking for the last chosen
3287                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3288                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3289                            return ri;
3290                        }
3291                    }
3292                } finally {
3293                    if (changed) {
3294                        if (DEBUG_PREFERRED) {
3295                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3296                        }
3297                        scheduleWritePackageRestrictionsLocked(userId);
3298                    }
3299                }
3300            }
3301        }
3302        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3303        return null;
3304    }
3305
3306    /*
3307     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3308     */
3309    @Override
3310    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3311            int targetUserId) {
3312        mContext.enforceCallingOrSelfPermission(
3313                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3314        List<CrossProfileIntentFilter> matches =
3315                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3316        if (matches != null) {
3317            int size = matches.size();
3318            for (int i = 0; i < size; i++) {
3319                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3320            }
3321        }
3322        return false;
3323    }
3324
3325    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3326            String resolvedType, int userId) {
3327        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3328        if (resolver != null) {
3329            return resolver.queryIntent(intent, resolvedType, false, userId);
3330        }
3331        return null;
3332    }
3333
3334    @Override
3335    public List<ResolveInfo> queryIntentActivities(Intent intent,
3336            String resolvedType, int flags, int userId) {
3337        if (!sUserManager.exists(userId)) return Collections.emptyList();
3338        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3339        ComponentName comp = intent.getComponent();
3340        if (comp == null) {
3341            if (intent.getSelector() != null) {
3342                intent = intent.getSelector();
3343                comp = intent.getComponent();
3344            }
3345        }
3346
3347        if (comp != null) {
3348            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3349            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3350            if (ai != null) {
3351                final ResolveInfo ri = new ResolveInfo();
3352                ri.activityInfo = ai;
3353                list.add(ri);
3354            }
3355            return list;
3356        }
3357
3358        // reader
3359        synchronized (mPackages) {
3360            final String pkgName = intent.getPackage();
3361            if (pkgName == null) {
3362                List<CrossProfileIntentFilter> matchingFilters =
3363                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3364                // Check for results that need to skip the current profile.
3365                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3366                        resolvedType, flags, userId);
3367                if (resolveInfo != null) {
3368                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3369                    result.add(resolveInfo);
3370                    return result;
3371                }
3372                // Check for cross profile results.
3373                resolveInfo = queryCrossProfileIntents(
3374                        matchingFilters, intent, resolvedType, flags, userId);
3375
3376                // Check for results in the current profile.
3377                List<ResolveInfo> result = mActivities.queryIntent(
3378                        intent, resolvedType, flags, userId);
3379                if (resolveInfo != null) {
3380                    result.add(resolveInfo);
3381                    Collections.sort(result, mResolvePrioritySorter);
3382                }
3383                return result;
3384            }
3385            final PackageParser.Package pkg = mPackages.get(pkgName);
3386            if (pkg != null) {
3387                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3388                        pkg.activities, userId);
3389            }
3390            return new ArrayList<ResolveInfo>();
3391        }
3392    }
3393
3394    private ResolveInfo querySkipCurrentProfileIntents(
3395            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3396            int flags, int sourceUserId) {
3397        if (matchingFilters != null) {
3398            int size = matchingFilters.size();
3399            for (int i = 0; i < size; i ++) {
3400                CrossProfileIntentFilter filter = matchingFilters.get(i);
3401                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3402                    // Checking if there are activities in the target user that can handle the
3403                    // intent.
3404                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3405                            flags, sourceUserId);
3406                    if (resolveInfo != null) {
3407                        return resolveInfo;
3408                    }
3409                }
3410            }
3411        }
3412        return null;
3413    }
3414
3415    // Return matching ResolveInfo if any for skip current profile intent filters.
3416    private ResolveInfo queryCrossProfileIntents(
3417            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3418            int flags, int sourceUserId) {
3419        if (matchingFilters != null) {
3420            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3421            // match the same intent. For performance reasons, it is better not to
3422            // run queryIntent twice for the same userId
3423            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3424            int size = matchingFilters.size();
3425            for (int i = 0; i < size; i++) {
3426                CrossProfileIntentFilter filter = matchingFilters.get(i);
3427                int targetUserId = filter.getTargetUserId();
3428                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3429                        && !alreadyTriedUserIds.get(targetUserId)) {
3430                    // Checking if there are activities in the target user that can handle the
3431                    // intent.
3432                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3433                            flags, sourceUserId);
3434                    if (resolveInfo != null) return resolveInfo;
3435                    alreadyTriedUserIds.put(targetUserId, true);
3436                }
3437            }
3438        }
3439        return null;
3440    }
3441
3442    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3443            String resolvedType, int flags, int sourceUserId) {
3444        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3445                resolvedType, flags, filter.getTargetUserId());
3446        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3447            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3448        }
3449        return null;
3450    }
3451
3452    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3453            int sourceUserId, int targetUserId) {
3454        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3455        String className;
3456        if (targetUserId == UserHandle.USER_OWNER) {
3457            className = FORWARD_INTENT_TO_USER_OWNER;
3458        } else {
3459            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3460        }
3461        ComponentName forwardingActivityComponentName = new ComponentName(
3462                mAndroidApplication.packageName, className);
3463        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3464                sourceUserId);
3465        if (targetUserId == UserHandle.USER_OWNER) {
3466            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3467            forwardingResolveInfo.noResourceId = true;
3468        }
3469        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3470        forwardingResolveInfo.priority = 0;
3471        forwardingResolveInfo.preferredOrder = 0;
3472        forwardingResolveInfo.match = 0;
3473        forwardingResolveInfo.isDefault = true;
3474        forwardingResolveInfo.filter = filter;
3475        forwardingResolveInfo.targetUserId = targetUserId;
3476        return forwardingResolveInfo;
3477    }
3478
3479    @Override
3480    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3481            Intent[] specifics, String[] specificTypes, Intent intent,
3482            String resolvedType, int flags, int userId) {
3483        if (!sUserManager.exists(userId)) return Collections.emptyList();
3484        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3485                false, "query intent activity options");
3486        final String resultsAction = intent.getAction();
3487
3488        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3489                | PackageManager.GET_RESOLVED_FILTER, userId);
3490
3491        if (DEBUG_INTENT_MATCHING) {
3492            Log.v(TAG, "Query " + intent + ": " + results);
3493        }
3494
3495        int specificsPos = 0;
3496        int N;
3497
3498        // todo: note that the algorithm used here is O(N^2).  This
3499        // isn't a problem in our current environment, but if we start running
3500        // into situations where we have more than 5 or 10 matches then this
3501        // should probably be changed to something smarter...
3502
3503        // First we go through and resolve each of the specific items
3504        // that were supplied, taking care of removing any corresponding
3505        // duplicate items in the generic resolve list.
3506        if (specifics != null) {
3507            for (int i=0; i<specifics.length; i++) {
3508                final Intent sintent = specifics[i];
3509                if (sintent == null) {
3510                    continue;
3511                }
3512
3513                if (DEBUG_INTENT_MATCHING) {
3514                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3515                }
3516
3517                String action = sintent.getAction();
3518                if (resultsAction != null && resultsAction.equals(action)) {
3519                    // If this action was explicitly requested, then don't
3520                    // remove things that have it.
3521                    action = null;
3522                }
3523
3524                ResolveInfo ri = null;
3525                ActivityInfo ai = null;
3526
3527                ComponentName comp = sintent.getComponent();
3528                if (comp == null) {
3529                    ri = resolveIntent(
3530                        sintent,
3531                        specificTypes != null ? specificTypes[i] : null,
3532                            flags, userId);
3533                    if (ri == null) {
3534                        continue;
3535                    }
3536                    if (ri == mResolveInfo) {
3537                        // ACK!  Must do something better with this.
3538                    }
3539                    ai = ri.activityInfo;
3540                    comp = new ComponentName(ai.applicationInfo.packageName,
3541                            ai.name);
3542                } else {
3543                    ai = getActivityInfo(comp, flags, userId);
3544                    if (ai == null) {
3545                        continue;
3546                    }
3547                }
3548
3549                // Look for any generic query activities that are duplicates
3550                // of this specific one, and remove them from the results.
3551                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3552                N = results.size();
3553                int j;
3554                for (j=specificsPos; j<N; j++) {
3555                    ResolveInfo sri = results.get(j);
3556                    if ((sri.activityInfo.name.equals(comp.getClassName())
3557                            && sri.activityInfo.applicationInfo.packageName.equals(
3558                                    comp.getPackageName()))
3559                        || (action != null && sri.filter.matchAction(action))) {
3560                        results.remove(j);
3561                        if (DEBUG_INTENT_MATCHING) Log.v(
3562                            TAG, "Removing duplicate item from " + j
3563                            + " due to specific " + specificsPos);
3564                        if (ri == null) {
3565                            ri = sri;
3566                        }
3567                        j--;
3568                        N--;
3569                    }
3570                }
3571
3572                // Add this specific item to its proper place.
3573                if (ri == null) {
3574                    ri = new ResolveInfo();
3575                    ri.activityInfo = ai;
3576                }
3577                results.add(specificsPos, ri);
3578                ri.specificIndex = i;
3579                specificsPos++;
3580            }
3581        }
3582
3583        // Now we go through the remaining generic results and remove any
3584        // duplicate actions that are found here.
3585        N = results.size();
3586        for (int i=specificsPos; i<N-1; i++) {
3587            final ResolveInfo rii = results.get(i);
3588            if (rii.filter == null) {
3589                continue;
3590            }
3591
3592            // Iterate over all of the actions of this result's intent
3593            // filter...  typically this should be just one.
3594            final Iterator<String> it = rii.filter.actionsIterator();
3595            if (it == null) {
3596                continue;
3597            }
3598            while (it.hasNext()) {
3599                final String action = it.next();
3600                if (resultsAction != null && resultsAction.equals(action)) {
3601                    // If this action was explicitly requested, then don't
3602                    // remove things that have it.
3603                    continue;
3604                }
3605                for (int j=i+1; j<N; j++) {
3606                    final ResolveInfo rij = results.get(j);
3607                    if (rij.filter != null && rij.filter.hasAction(action)) {
3608                        results.remove(j);
3609                        if (DEBUG_INTENT_MATCHING) Log.v(
3610                            TAG, "Removing duplicate item from " + j
3611                            + " due to action " + action + " at " + i);
3612                        j--;
3613                        N--;
3614                    }
3615                }
3616            }
3617
3618            // If the caller didn't request filter information, drop it now
3619            // so we don't have to marshall/unmarshall it.
3620            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3621                rii.filter = null;
3622            }
3623        }
3624
3625        // Filter out the caller activity if so requested.
3626        if (caller != null) {
3627            N = results.size();
3628            for (int i=0; i<N; i++) {
3629                ActivityInfo ainfo = results.get(i).activityInfo;
3630                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3631                        && caller.getClassName().equals(ainfo.name)) {
3632                    results.remove(i);
3633                    break;
3634                }
3635            }
3636        }
3637
3638        // If the caller didn't request filter information,
3639        // drop them now so we don't have to
3640        // marshall/unmarshall it.
3641        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3642            N = results.size();
3643            for (int i=0; i<N; i++) {
3644                results.get(i).filter = null;
3645            }
3646        }
3647
3648        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3649        return results;
3650    }
3651
3652    @Override
3653    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3654            int userId) {
3655        if (!sUserManager.exists(userId)) return Collections.emptyList();
3656        ComponentName comp = intent.getComponent();
3657        if (comp == null) {
3658            if (intent.getSelector() != null) {
3659                intent = intent.getSelector();
3660                comp = intent.getComponent();
3661            }
3662        }
3663        if (comp != null) {
3664            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3665            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3666            if (ai != null) {
3667                ResolveInfo ri = new ResolveInfo();
3668                ri.activityInfo = ai;
3669                list.add(ri);
3670            }
3671            return list;
3672        }
3673
3674        // reader
3675        synchronized (mPackages) {
3676            String pkgName = intent.getPackage();
3677            if (pkgName == null) {
3678                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3679            }
3680            final PackageParser.Package pkg = mPackages.get(pkgName);
3681            if (pkg != null) {
3682                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3683                        userId);
3684            }
3685            return null;
3686        }
3687    }
3688
3689    @Override
3690    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3691        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3692        if (!sUserManager.exists(userId)) return null;
3693        if (query != null) {
3694            if (query.size() >= 1) {
3695                // If there is more than one service with the same priority,
3696                // just arbitrarily pick the first one.
3697                return query.get(0);
3698            }
3699        }
3700        return null;
3701    }
3702
3703    @Override
3704    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3705            int userId) {
3706        if (!sUserManager.exists(userId)) return Collections.emptyList();
3707        ComponentName comp = intent.getComponent();
3708        if (comp == null) {
3709            if (intent.getSelector() != null) {
3710                intent = intent.getSelector();
3711                comp = intent.getComponent();
3712            }
3713        }
3714        if (comp != null) {
3715            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3716            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3717            if (si != null) {
3718                final ResolveInfo ri = new ResolveInfo();
3719                ri.serviceInfo = si;
3720                list.add(ri);
3721            }
3722            return list;
3723        }
3724
3725        // reader
3726        synchronized (mPackages) {
3727            String pkgName = intent.getPackage();
3728            if (pkgName == null) {
3729                return mServices.queryIntent(intent, resolvedType, flags, userId);
3730            }
3731            final PackageParser.Package pkg = mPackages.get(pkgName);
3732            if (pkg != null) {
3733                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3734                        userId);
3735            }
3736            return null;
3737        }
3738    }
3739
3740    @Override
3741    public List<ResolveInfo> queryIntentContentProviders(
3742            Intent intent, String resolvedType, int flags, int userId) {
3743        if (!sUserManager.exists(userId)) return Collections.emptyList();
3744        ComponentName comp = intent.getComponent();
3745        if (comp == null) {
3746            if (intent.getSelector() != null) {
3747                intent = intent.getSelector();
3748                comp = intent.getComponent();
3749            }
3750        }
3751        if (comp != null) {
3752            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3753            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3754            if (pi != null) {
3755                final ResolveInfo ri = new ResolveInfo();
3756                ri.providerInfo = pi;
3757                list.add(ri);
3758            }
3759            return list;
3760        }
3761
3762        // reader
3763        synchronized (mPackages) {
3764            String pkgName = intent.getPackage();
3765            if (pkgName == null) {
3766                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3767            }
3768            final PackageParser.Package pkg = mPackages.get(pkgName);
3769            if (pkg != null) {
3770                return mProviders.queryIntentForPackage(
3771                        intent, resolvedType, flags, pkg.providers, userId);
3772            }
3773            return null;
3774        }
3775    }
3776
3777    @Override
3778    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3779        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3780
3781        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3782
3783        // writer
3784        synchronized (mPackages) {
3785            ArrayList<PackageInfo> list;
3786            if (listUninstalled) {
3787                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3788                for (PackageSetting ps : mSettings.mPackages.values()) {
3789                    PackageInfo pi;
3790                    if (ps.pkg != null) {
3791                        pi = generatePackageInfo(ps.pkg, flags, userId);
3792                    } else {
3793                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3794                    }
3795                    if (pi != null) {
3796                        list.add(pi);
3797                    }
3798                }
3799            } else {
3800                list = new ArrayList<PackageInfo>(mPackages.size());
3801                for (PackageParser.Package p : mPackages.values()) {
3802                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3803                    if (pi != null) {
3804                        list.add(pi);
3805                    }
3806                }
3807            }
3808
3809            return new ParceledListSlice<PackageInfo>(list);
3810        }
3811    }
3812
3813    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3814            String[] permissions, boolean[] tmp, int flags, int userId) {
3815        int numMatch = 0;
3816        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3817        for (int i=0; i<permissions.length; i++) {
3818            if (gp.grantedPermissions.contains(permissions[i])) {
3819                tmp[i] = true;
3820                numMatch++;
3821            } else {
3822                tmp[i] = false;
3823            }
3824        }
3825        if (numMatch == 0) {
3826            return;
3827        }
3828        PackageInfo pi;
3829        if (ps.pkg != null) {
3830            pi = generatePackageInfo(ps.pkg, flags, userId);
3831        } else {
3832            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3833        }
3834        // The above might return null in cases of uninstalled apps or install-state
3835        // skew across users/profiles.
3836        if (pi != null) {
3837            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3838                if (numMatch == permissions.length) {
3839                    pi.requestedPermissions = permissions;
3840                } else {
3841                    pi.requestedPermissions = new String[numMatch];
3842                    numMatch = 0;
3843                    for (int i=0; i<permissions.length; i++) {
3844                        if (tmp[i]) {
3845                            pi.requestedPermissions[numMatch] = permissions[i];
3846                            numMatch++;
3847                        }
3848                    }
3849                }
3850            }
3851            list.add(pi);
3852        }
3853    }
3854
3855    @Override
3856    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3857            String[] permissions, int flags, int userId) {
3858        if (!sUserManager.exists(userId)) return null;
3859        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3860
3861        // writer
3862        synchronized (mPackages) {
3863            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3864            boolean[] tmpBools = new boolean[permissions.length];
3865            if (listUninstalled) {
3866                for (PackageSetting ps : mSettings.mPackages.values()) {
3867                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3868                }
3869            } else {
3870                for (PackageParser.Package pkg : mPackages.values()) {
3871                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3872                    if (ps != null) {
3873                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3874                                userId);
3875                    }
3876                }
3877            }
3878
3879            return new ParceledListSlice<PackageInfo>(list);
3880        }
3881    }
3882
3883    @Override
3884    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3885        if (!sUserManager.exists(userId)) return null;
3886        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3887
3888        // writer
3889        synchronized (mPackages) {
3890            ArrayList<ApplicationInfo> list;
3891            if (listUninstalled) {
3892                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3893                for (PackageSetting ps : mSettings.mPackages.values()) {
3894                    ApplicationInfo ai;
3895                    if (ps.pkg != null) {
3896                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3897                                ps.readUserState(userId), userId);
3898                    } else {
3899                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3900                    }
3901                    if (ai != null) {
3902                        list.add(ai);
3903                    }
3904                }
3905            } else {
3906                list = new ArrayList<ApplicationInfo>(mPackages.size());
3907                for (PackageParser.Package p : mPackages.values()) {
3908                    if (p.mExtras != null) {
3909                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3910                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3911                        if (ai != null) {
3912                            list.add(ai);
3913                        }
3914                    }
3915                }
3916            }
3917
3918            return new ParceledListSlice<ApplicationInfo>(list);
3919        }
3920    }
3921
3922    public List<ApplicationInfo> getPersistentApplications(int flags) {
3923        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3924
3925        // reader
3926        synchronized (mPackages) {
3927            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3928            final int userId = UserHandle.getCallingUserId();
3929            while (i.hasNext()) {
3930                final PackageParser.Package p = i.next();
3931                if (p.applicationInfo != null
3932                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3933                        && (!mSafeMode || isSystemApp(p))) {
3934                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3935                    if (ps != null) {
3936                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3937                                ps.readUserState(userId), userId);
3938                        if (ai != null) {
3939                            finalList.add(ai);
3940                        }
3941                    }
3942                }
3943            }
3944        }
3945
3946        return finalList;
3947    }
3948
3949    @Override
3950    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3951        if (!sUserManager.exists(userId)) return null;
3952        // reader
3953        synchronized (mPackages) {
3954            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3955            PackageSetting ps = provider != null
3956                    ? mSettings.mPackages.get(provider.owner.packageName)
3957                    : null;
3958            return ps != null
3959                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3960                    && (!mSafeMode || (provider.info.applicationInfo.flags
3961                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3962                    ? PackageParser.generateProviderInfo(provider, flags,
3963                            ps.readUserState(userId), userId)
3964                    : null;
3965        }
3966    }
3967
3968    /**
3969     * @deprecated
3970     */
3971    @Deprecated
3972    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3973        // reader
3974        synchronized (mPackages) {
3975            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3976                    .entrySet().iterator();
3977            final int userId = UserHandle.getCallingUserId();
3978            while (i.hasNext()) {
3979                Map.Entry<String, PackageParser.Provider> entry = i.next();
3980                PackageParser.Provider p = entry.getValue();
3981                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3982
3983                if (ps != null && p.syncable
3984                        && (!mSafeMode || (p.info.applicationInfo.flags
3985                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3986                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3987                            ps.readUserState(userId), userId);
3988                    if (info != null) {
3989                        outNames.add(entry.getKey());
3990                        outInfo.add(info);
3991                    }
3992                }
3993            }
3994        }
3995    }
3996
3997    @Override
3998    public List<ProviderInfo> queryContentProviders(String processName,
3999            int uid, int flags) {
4000        ArrayList<ProviderInfo> finalList = null;
4001        // reader
4002        synchronized (mPackages) {
4003            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4004            final int userId = processName != null ?
4005                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4006            while (i.hasNext()) {
4007                final PackageParser.Provider p = i.next();
4008                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4009                if (ps != null && p.info.authority != null
4010                        && (processName == null
4011                                || (p.info.processName.equals(processName)
4012                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4013                        && mSettings.isEnabledLPr(p.info, flags, userId)
4014                        && (!mSafeMode
4015                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4016                    if (finalList == null) {
4017                        finalList = new ArrayList<ProviderInfo>(3);
4018                    }
4019                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4020                            ps.readUserState(userId), userId);
4021                    if (info != null) {
4022                        finalList.add(info);
4023                    }
4024                }
4025            }
4026        }
4027
4028        if (finalList != null) {
4029            Collections.sort(finalList, mProviderInitOrderSorter);
4030        }
4031
4032        return finalList;
4033    }
4034
4035    @Override
4036    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4037            int flags) {
4038        // reader
4039        synchronized (mPackages) {
4040            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4041            return PackageParser.generateInstrumentationInfo(i, flags);
4042        }
4043    }
4044
4045    @Override
4046    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4047            int flags) {
4048        ArrayList<InstrumentationInfo> finalList =
4049            new ArrayList<InstrumentationInfo>();
4050
4051        // reader
4052        synchronized (mPackages) {
4053            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4054            while (i.hasNext()) {
4055                final PackageParser.Instrumentation p = i.next();
4056                if (targetPackage == null
4057                        || targetPackage.equals(p.info.targetPackage)) {
4058                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4059                            flags);
4060                    if (ii != null) {
4061                        finalList.add(ii);
4062                    }
4063                }
4064            }
4065        }
4066
4067        return finalList;
4068    }
4069
4070    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4071        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4072        if (overlays == null) {
4073            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4074            return;
4075        }
4076        for (PackageParser.Package opkg : overlays.values()) {
4077            // Not much to do if idmap fails: we already logged the error
4078            // and we certainly don't want to abort installation of pkg simply
4079            // because an overlay didn't fit properly. For these reasons,
4080            // ignore the return value of createIdmapForPackagePairLI.
4081            createIdmapForPackagePairLI(pkg, opkg);
4082        }
4083    }
4084
4085    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4086            PackageParser.Package opkg) {
4087        if (!opkg.mTrustedOverlay) {
4088            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4089                    opkg.baseCodePath + ": overlay not trusted");
4090            return false;
4091        }
4092        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4093        if (overlaySet == null) {
4094            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4095                    opkg.baseCodePath + " but target package has no known overlays");
4096            return false;
4097        }
4098        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4099        // TODO: generate idmap for split APKs
4100        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4101            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4102                    + opkg.baseCodePath);
4103            return false;
4104        }
4105        PackageParser.Package[] overlayArray =
4106            overlaySet.values().toArray(new PackageParser.Package[0]);
4107        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4108            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4109                return p1.mOverlayPriority - p2.mOverlayPriority;
4110            }
4111        };
4112        Arrays.sort(overlayArray, cmp);
4113
4114        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4115        int i = 0;
4116        for (PackageParser.Package p : overlayArray) {
4117            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4118        }
4119        return true;
4120    }
4121
4122    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4123        final File[] files = dir.listFiles();
4124        if (ArrayUtils.isEmpty(files)) {
4125            Log.d(TAG, "No files in app dir " + dir);
4126            return;
4127        }
4128
4129        if (DEBUG_PACKAGE_SCANNING) {
4130            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4131                    + " flags=0x" + Integer.toHexString(parseFlags));
4132        }
4133
4134        for (File file : files) {
4135            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4136                    && !PackageInstallerService.isStageName(file.getName());
4137            if (!isPackage) {
4138                // Ignore entries which are not packages
4139                continue;
4140            }
4141            try {
4142                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4143                        scanFlags, currentTime, null);
4144            } catch (PackageManagerException e) {
4145                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4146
4147                // Delete invalid userdata apps
4148                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4149                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4150                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4151                    if (file.isDirectory()) {
4152                        FileUtils.deleteContents(file);
4153                    }
4154                    file.delete();
4155                }
4156            }
4157        }
4158    }
4159
4160    private static File getSettingsProblemFile() {
4161        File dataDir = Environment.getDataDirectory();
4162        File systemDir = new File(dataDir, "system");
4163        File fname = new File(systemDir, "uiderrors.txt");
4164        return fname;
4165    }
4166
4167    static void reportSettingsProblem(int priority, String msg) {
4168        logCriticalInfo(priority, msg);
4169    }
4170
4171    static void logCriticalInfo(int priority, String msg) {
4172        Slog.println(priority, TAG, msg);
4173        EventLogTags.writePmCriticalInfo(msg);
4174        try {
4175            File fname = getSettingsProblemFile();
4176            FileOutputStream out = new FileOutputStream(fname, true);
4177            PrintWriter pw = new FastPrintWriter(out);
4178            SimpleDateFormat formatter = new SimpleDateFormat();
4179            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4180            pw.println(dateString + ": " + msg);
4181            pw.close();
4182            FileUtils.setPermissions(
4183                    fname.toString(),
4184                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4185                    -1, -1);
4186        } catch (java.io.IOException e) {
4187        }
4188    }
4189
4190    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4191            PackageParser.Package pkg, File srcFile, int parseFlags)
4192            throws PackageManagerException {
4193        if (ps != null
4194                && ps.codePath.equals(srcFile)
4195                && ps.timeStamp == srcFile.lastModified()
4196                && !isCompatSignatureUpdateNeeded(pkg)
4197                && !isRecoverSignatureUpdateNeeded(pkg)) {
4198            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4199            if (ps.signatures.mSignatures != null
4200                    && ps.signatures.mSignatures.length != 0
4201                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4202                // Optimization: reuse the existing cached certificates
4203                // if the package appears to be unchanged.
4204                pkg.mSignatures = ps.signatures.mSignatures;
4205                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4206                synchronized (mPackages) {
4207                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4208                }
4209                return;
4210            }
4211
4212            Slog.w(TAG, "PackageSetting for " + ps.name
4213                    + " is missing signatures.  Collecting certs again to recover them.");
4214        } else {
4215            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4216        }
4217
4218        try {
4219            pp.collectCertificates(pkg, parseFlags);
4220            pp.collectManifestDigest(pkg);
4221        } catch (PackageParserException e) {
4222            throw PackageManagerException.from(e);
4223        }
4224    }
4225
4226    /*
4227     *  Scan a package and return the newly parsed package.
4228     *  Returns null in case of errors and the error code is stored in mLastScanError
4229     */
4230    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4231            long currentTime, UserHandle user) throws PackageManagerException {
4232        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4233        parseFlags |= mDefParseFlags;
4234        PackageParser pp = new PackageParser();
4235        pp.setSeparateProcesses(mSeparateProcesses);
4236        pp.setOnlyCoreApps(mOnlyCore);
4237        pp.setDisplayMetrics(mMetrics);
4238
4239        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4240            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4241        }
4242
4243        final PackageParser.Package pkg;
4244        try {
4245            pkg = pp.parsePackage(scanFile, parseFlags);
4246        } catch (PackageParserException e) {
4247            throw PackageManagerException.from(e);
4248        }
4249
4250        PackageSetting ps = null;
4251        PackageSetting updatedPkg;
4252        // reader
4253        synchronized (mPackages) {
4254            // Look to see if we already know about this package.
4255            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4256            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4257                // This package has been renamed to its original name.  Let's
4258                // use that.
4259                ps = mSettings.peekPackageLPr(oldName);
4260            }
4261            // If there was no original package, see one for the real package name.
4262            if (ps == null) {
4263                ps = mSettings.peekPackageLPr(pkg.packageName);
4264            }
4265            // Check to see if this package could be hiding/updating a system
4266            // package.  Must look for it either under the original or real
4267            // package name depending on our state.
4268            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4269            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4270        }
4271        boolean updatedPkgBetter = false;
4272        // First check if this is a system package that may involve an update
4273        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4274            if (ps != null && !ps.codePath.equals(scanFile)) {
4275                // The path has changed from what was last scanned...  check the
4276                // version of the new path against what we have stored to determine
4277                // what to do.
4278                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4279                if (pkg.mVersionCode <= ps.versionCode) {
4280                    // The system package has been updated and the code path does not match
4281                    // Ignore entry. Skip it.
4282                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4283                            + " ignored: updated version " + ps.versionCode
4284                            + " better than this " + pkg.mVersionCode);
4285                    if (!updatedPkg.codePath.equals(scanFile)) {
4286                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4287                                + ps.name + " changing from " + updatedPkg.codePathString
4288                                + " to " + scanFile);
4289                        updatedPkg.codePath = scanFile;
4290                        updatedPkg.codePathString = scanFile.toString();
4291                        // This is the point at which we know that the system-disk APK
4292                        // for this package has moved during a reboot (e.g. due to an OTA),
4293                        // so we need to reevaluate it for privilege policy.
4294                        if (locationIsPrivileged(scanFile)) {
4295                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4296                        }
4297                    }
4298                    updatedPkg.pkg = pkg;
4299                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4300                } else {
4301                    // The current app on the system partition is better than
4302                    // what we have updated to on the data partition; switch
4303                    // back to the system partition version.
4304                    // At this point, its safely assumed that package installation for
4305                    // apps in system partition will go through. If not there won't be a working
4306                    // version of the app
4307                    // writer
4308                    synchronized (mPackages) {
4309                        // Just remove the loaded entries from package lists.
4310                        mPackages.remove(ps.name);
4311                    }
4312
4313                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4314                            + " reverting from " + ps.codePathString
4315                            + ": new version " + pkg.mVersionCode
4316                            + " better than installed " + ps.versionCode);
4317
4318                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4319                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4320                            getAppDexInstructionSets(ps));
4321                    synchronized (mInstallLock) {
4322                        args.cleanUpResourcesLI();
4323                    }
4324                    synchronized (mPackages) {
4325                        mSettings.enableSystemPackageLPw(ps.name);
4326                    }
4327                    updatedPkgBetter = true;
4328                }
4329            }
4330        }
4331
4332        if (updatedPkg != null) {
4333            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4334            // initially
4335            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4336
4337            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4338            // flag set initially
4339            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4340                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4341            }
4342        }
4343
4344        // Verify certificates against what was last scanned
4345        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4346
4347        /*
4348         * A new system app appeared, but we already had a non-system one of the
4349         * same name installed earlier.
4350         */
4351        boolean shouldHideSystemApp = false;
4352        if (updatedPkg == null && ps != null
4353                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4354            /*
4355             * Check to make sure the signatures match first. If they don't,
4356             * wipe the installed application and its data.
4357             */
4358            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4359                    != PackageManager.SIGNATURE_MATCH) {
4360                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4361                        + " signatures don't match existing userdata copy; removing");
4362                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4363                ps = null;
4364            } else {
4365                /*
4366                 * If the newly-added system app is an older version than the
4367                 * already installed version, hide it. It will be scanned later
4368                 * and re-added like an update.
4369                 */
4370                if (pkg.mVersionCode <= ps.versionCode) {
4371                    shouldHideSystemApp = true;
4372                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4373                            + " but new version " + pkg.mVersionCode + " better than installed "
4374                            + ps.versionCode + "; hiding system");
4375                } else {
4376                    /*
4377                     * The newly found system app is a newer version that the
4378                     * one previously installed. Simply remove the
4379                     * already-installed application and replace it with our own
4380                     * while keeping the application data.
4381                     */
4382                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4383                            + " reverting from " + ps.codePathString + ": new version "
4384                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4385                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4386                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4387                            getAppDexInstructionSets(ps));
4388                    synchronized (mInstallLock) {
4389                        args.cleanUpResourcesLI();
4390                    }
4391                }
4392            }
4393        }
4394
4395        // The apk is forward locked (not public) if its code and resources
4396        // are kept in different files. (except for app in either system or
4397        // vendor path).
4398        // TODO grab this value from PackageSettings
4399        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4400            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4401                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4402            }
4403        }
4404
4405        // TODO: extend to support forward-locked splits
4406        String resourcePath = null;
4407        String baseResourcePath = null;
4408        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4409            if (ps != null && ps.resourcePathString != null) {
4410                resourcePath = ps.resourcePathString;
4411                baseResourcePath = ps.resourcePathString;
4412            } else {
4413                // Should not happen at all. Just log an error.
4414                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4415            }
4416        } else {
4417            resourcePath = pkg.codePath;
4418            baseResourcePath = pkg.baseCodePath;
4419        }
4420
4421        // Set application objects path explicitly.
4422        pkg.applicationInfo.setCodePath(pkg.codePath);
4423        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4424        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4425        pkg.applicationInfo.setResourcePath(resourcePath);
4426        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4427        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4428
4429        // Note that we invoke the following method only if we are about to unpack an application
4430        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4431                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4432
4433        /*
4434         * If the system app should be overridden by a previously installed
4435         * data, hide the system app now and let the /data/app scan pick it up
4436         * again.
4437         */
4438        if (shouldHideSystemApp) {
4439            synchronized (mPackages) {
4440                /*
4441                 * We have to grant systems permissions before we hide, because
4442                 * grantPermissions will assume the package update is trying to
4443                 * expand its permissions.
4444                 */
4445                grantPermissionsLPw(pkg, true, pkg.packageName);
4446                mSettings.disableSystemPackageLPw(pkg.packageName);
4447            }
4448        }
4449
4450        return scannedPkg;
4451    }
4452
4453    private static String fixProcessName(String defProcessName,
4454            String processName, int uid) {
4455        if (processName == null) {
4456            return defProcessName;
4457        }
4458        return processName;
4459    }
4460
4461    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4462            throws PackageManagerException {
4463        if (pkgSetting.signatures.mSignatures != null) {
4464            // Already existing package. Make sure signatures match
4465            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4466                    == PackageManager.SIGNATURE_MATCH;
4467            if (!match) {
4468                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4469                        == PackageManager.SIGNATURE_MATCH;
4470            }
4471            if (!match) {
4472                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4473                        == PackageManager.SIGNATURE_MATCH;
4474            }
4475            if (!match) {
4476                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4477                        + pkg.packageName + " signatures do not match the "
4478                        + "previously installed version; ignoring!");
4479            }
4480        }
4481
4482        // Check for shared user signatures
4483        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4484            // Already existing package. Make sure signatures match
4485            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4486                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4487            if (!match) {
4488                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4489                        == PackageManager.SIGNATURE_MATCH;
4490            }
4491            if (!match) {
4492                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4493                        == PackageManager.SIGNATURE_MATCH;
4494            }
4495            if (!match) {
4496                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4497                        "Package " + pkg.packageName
4498                        + " has no signatures that match those in shared user "
4499                        + pkgSetting.sharedUser.name + "; ignoring!");
4500            }
4501        }
4502    }
4503
4504    /**
4505     * Enforces that only the system UID or root's UID can call a method exposed
4506     * via Binder.
4507     *
4508     * @param message used as message if SecurityException is thrown
4509     * @throws SecurityException if the caller is not system or root
4510     */
4511    private static final void enforceSystemOrRoot(String message) {
4512        final int uid = Binder.getCallingUid();
4513        if (uid != Process.SYSTEM_UID && uid != 0) {
4514            throw new SecurityException(message);
4515        }
4516    }
4517
4518    @Override
4519    public void performBootDexOpt() {
4520        enforceSystemOrRoot("Only the system can request dexopt be performed");
4521
4522        final ArraySet<PackageParser.Package> pkgs;
4523        synchronized (mPackages) {
4524            pkgs = mDeferredDexOpt;
4525            mDeferredDexOpt = null;
4526        }
4527
4528        if (pkgs != null) {
4529            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4530            // in case the device runs out of space.
4531            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4532            // Give priority to core apps.
4533            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4534                PackageParser.Package pkg = it.next();
4535                if (pkg.coreApp) {
4536                    if (DEBUG_DEXOPT) {
4537                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4538                    }
4539                    sortedPkgs.add(pkg);
4540                    it.remove();
4541                }
4542            }
4543            // Give priority to system apps that listen for pre boot complete.
4544            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4545            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4546            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4547                PackageParser.Package pkg = it.next();
4548                if (pkgNames.contains(pkg.packageName)) {
4549                    if (DEBUG_DEXOPT) {
4550                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4551                    }
4552                    sortedPkgs.add(pkg);
4553                    it.remove();
4554                }
4555            }
4556            // Give priority to system apps.
4557            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4558                PackageParser.Package pkg = it.next();
4559                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4560                    if (DEBUG_DEXOPT) {
4561                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4562                    }
4563                    sortedPkgs.add(pkg);
4564                    it.remove();
4565                }
4566            }
4567            // Give priority to updated system apps.
4568            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4569                PackageParser.Package pkg = it.next();
4570                if (isUpdatedSystemApp(pkg)) {
4571                    if (DEBUG_DEXOPT) {
4572                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4573                    }
4574                    sortedPkgs.add(pkg);
4575                    it.remove();
4576                }
4577            }
4578            // Give priority to apps that listen for boot complete.
4579            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4580            pkgNames = getPackageNamesForIntent(intent);
4581            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4582                PackageParser.Package pkg = it.next();
4583                if (pkgNames.contains(pkg.packageName)) {
4584                    if (DEBUG_DEXOPT) {
4585                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4586                    }
4587                    sortedPkgs.add(pkg);
4588                    it.remove();
4589                }
4590            }
4591            // Filter out packages that aren't recently used.
4592            filterRecentlyUsedApps(pkgs);
4593            // Add all remaining apps.
4594            for (PackageParser.Package pkg : pkgs) {
4595                if (DEBUG_DEXOPT) {
4596                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4597                }
4598                sortedPkgs.add(pkg);
4599            }
4600
4601            // If we want to be lazy, filter everything that wasn't recently used.
4602            if (mLazyDexOpt) {
4603                filterRecentlyUsedApps(sortedPkgs);
4604            }
4605
4606            int i = 0;
4607            int total = sortedPkgs.size();
4608            File dataDir = Environment.getDataDirectory();
4609            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4610            if (lowThreshold == 0) {
4611                throw new IllegalStateException("Invalid low memory threshold");
4612            }
4613            for (PackageParser.Package pkg : sortedPkgs) {
4614                long usableSpace = dataDir.getUsableSpace();
4615                if (usableSpace < lowThreshold) {
4616                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4617                    break;
4618                }
4619                performBootDexOpt(pkg, ++i, total);
4620            }
4621        }
4622    }
4623
4624    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4625        // Filter out packages that aren't recently used.
4626        //
4627        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4628        // should do a full dexopt.
4629        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4630            int total = pkgs.size();
4631            int skipped = 0;
4632            long now = System.currentTimeMillis();
4633            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4634                PackageParser.Package pkg = i.next();
4635                long then = pkg.mLastPackageUsageTimeInMills;
4636                if (then + mDexOptLRUThresholdInMills < now) {
4637                    if (DEBUG_DEXOPT) {
4638                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4639                              ((then == 0) ? "never" : new Date(then)));
4640                    }
4641                    i.remove();
4642                    skipped++;
4643                }
4644            }
4645            if (DEBUG_DEXOPT) {
4646                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4647            }
4648        }
4649    }
4650
4651    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4652        List<ResolveInfo> ris = null;
4653        try {
4654            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4655                    intent, null, 0, UserHandle.USER_OWNER);
4656        } catch (RemoteException e) {
4657        }
4658        ArraySet<String> pkgNames = new ArraySet<String>();
4659        if (ris != null) {
4660            for (ResolveInfo ri : ris) {
4661                pkgNames.add(ri.activityInfo.packageName);
4662            }
4663        }
4664        return pkgNames;
4665    }
4666
4667    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4668        if (DEBUG_DEXOPT) {
4669            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4670        }
4671        if (!isFirstBoot()) {
4672            try {
4673                ActivityManagerNative.getDefault().showBootMessage(
4674                        mContext.getResources().getString(R.string.android_upgrading_apk,
4675                                curr, total), true);
4676            } catch (RemoteException e) {
4677            }
4678        }
4679        PackageParser.Package p = pkg;
4680        synchronized (mInstallLock) {
4681            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4682                            false /* defer */, true /* include dependencies */);
4683        }
4684    }
4685
4686    @Override
4687    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4688        return performDexOpt(packageName, instructionSet, false);
4689    }
4690
4691    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4692        if (info.primaryCpuAbi == null) {
4693            return getPreferredInstructionSet();
4694        }
4695
4696        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4697    }
4698
4699    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4700        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4701        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4702        if (!dexopt && !updateUsage) {
4703            // We aren't going to dexopt or update usage, so bail early.
4704            return false;
4705        }
4706        PackageParser.Package p;
4707        final String targetInstructionSet;
4708        synchronized (mPackages) {
4709            p = mPackages.get(packageName);
4710            if (p == null) {
4711                return false;
4712            }
4713            if (updateUsage) {
4714                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4715            }
4716            mPackageUsage.write(false);
4717            if (!dexopt) {
4718                // We aren't going to dexopt, so bail early.
4719                return false;
4720            }
4721
4722            targetInstructionSet = instructionSet != null ? instructionSet :
4723                    getPrimaryInstructionSet(p.applicationInfo);
4724            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4725                return false;
4726            }
4727        }
4728
4729        synchronized (mInstallLock) {
4730            final String[] instructionSets = new String[] { targetInstructionSet };
4731            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4732                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4733        }
4734    }
4735
4736    public ArraySet<String> getPackagesThatNeedDexOpt() {
4737        ArraySet<String> pkgs = null;
4738        synchronized (mPackages) {
4739            for (PackageParser.Package p : mPackages.values()) {
4740                if (DEBUG_DEXOPT) {
4741                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4742                }
4743                if (!p.mDexOptPerformed.isEmpty()) {
4744                    continue;
4745                }
4746                if (pkgs == null) {
4747                    pkgs = new ArraySet<String>();
4748                }
4749                pkgs.add(p.packageName);
4750            }
4751        }
4752        return pkgs;
4753    }
4754
4755    public void shutdown() {
4756        mPackageUsage.write(true);
4757    }
4758
4759    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4760             boolean forceDex, boolean defer, ArraySet<String> done) {
4761        for (int i=0; i<libs.size(); i++) {
4762            PackageParser.Package libPkg;
4763            String libName;
4764            synchronized (mPackages) {
4765                libName = libs.get(i);
4766                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4767                if (lib != null && lib.apk != null) {
4768                    libPkg = mPackages.get(lib.apk);
4769                } else {
4770                    libPkg = null;
4771                }
4772            }
4773            if (libPkg != null && !done.contains(libName)) {
4774                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4775            }
4776        }
4777    }
4778
4779    static final int DEX_OPT_SKIPPED = 0;
4780    static final int DEX_OPT_PERFORMED = 1;
4781    static final int DEX_OPT_DEFERRED = 2;
4782    static final int DEX_OPT_FAILED = -1;
4783
4784    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4785            boolean forceDex, boolean defer, ArraySet<String> done) {
4786        final String[] instructionSets = targetInstructionSets != null ?
4787                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4788
4789        if (done != null) {
4790            done.add(pkg.packageName);
4791            if (pkg.usesLibraries != null) {
4792                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4793            }
4794            if (pkg.usesOptionalLibraries != null) {
4795                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4796            }
4797        }
4798
4799        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4800            return DEX_OPT_SKIPPED;
4801        }
4802
4803        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4804
4805        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4806        boolean performedDexOpt = false;
4807        // There are three basic cases here:
4808        // 1.) we need to dexopt, either because we are forced or it is needed
4809        // 2.) we are defering a needed dexopt
4810        // 3.) we are skipping an unneeded dexopt
4811        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4812        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4813            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4814                continue;
4815            }
4816
4817            for (String path : paths) {
4818                try {
4819                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4820                    // patckage or the one we find does not match the image checksum (i.e. it was
4821                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4822                    // odex file and it matches the checksum of the image but not its base address,
4823                    // meaning we need to move it.
4824                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4825                            pkg.packageName, dexCodeInstructionSet, defer);
4826                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4827                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4828                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4829                                + " vmSafeMode=" + vmSafeMode);
4830                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4831                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4832                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4833
4834                        if (ret < 0) {
4835                            // Don't bother running dexopt again if we failed, it will probably
4836                            // just result in an error again. Also, don't bother dexopting for other
4837                            // paths & ISAs.
4838                            return DEX_OPT_FAILED;
4839                        }
4840
4841                        performedDexOpt = true;
4842                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4843                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4844                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4845                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4846                                pkg.packageName, dexCodeInstructionSet);
4847
4848                        if (ret < 0) {
4849                            // Don't bother running patchoat again if we failed, it will probably
4850                            // just result in an error again. Also, don't bother dexopting for other
4851                            // paths & ISAs.
4852                            return DEX_OPT_FAILED;
4853                        }
4854
4855                        performedDexOpt = true;
4856                    }
4857
4858                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4859                    // paths and instruction sets. We'll deal with them all together when we process
4860                    // our list of deferred dexopts.
4861                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4862                        if (mDeferredDexOpt == null) {
4863                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4864                        }
4865                        mDeferredDexOpt.add(pkg);
4866                        return DEX_OPT_DEFERRED;
4867                    }
4868                } catch (FileNotFoundException e) {
4869                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4870                    return DEX_OPT_FAILED;
4871                } catch (IOException e) {
4872                    Slog.w(TAG, "IOException reading apk: " + path, e);
4873                    return DEX_OPT_FAILED;
4874                } catch (StaleDexCacheError e) {
4875                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4876                    return DEX_OPT_FAILED;
4877                } catch (Exception e) {
4878                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4879                    return DEX_OPT_FAILED;
4880                }
4881            }
4882
4883            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4884            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4885            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4886            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4887            // it.
4888            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4889        }
4890
4891        // If we've gotten here, we're sure that no error occurred and that we haven't
4892        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4893        // we've skipped all of them because they are up to date. In both cases this
4894        // package doesn't need dexopt any longer.
4895        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4896    }
4897
4898    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4899        if (info.primaryCpuAbi != null) {
4900            if (info.secondaryCpuAbi != null) {
4901                return new String[] {
4902                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4903                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4904            } else {
4905                return new String[] {
4906                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4907            }
4908        }
4909
4910        return new String[] { getPreferredInstructionSet() };
4911    }
4912
4913    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4914        if (ps.primaryCpuAbiString != null) {
4915            if (ps.secondaryCpuAbiString != null) {
4916                return new String[] {
4917                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4918                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4919            } else {
4920                return new String[] {
4921                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4922            }
4923        }
4924
4925        return new String[] { getPreferredInstructionSet() };
4926    }
4927
4928    private static String getPreferredInstructionSet() {
4929        if (sPreferredInstructionSet == null) {
4930            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4931        }
4932
4933        return sPreferredInstructionSet;
4934    }
4935
4936    private static List<String> getAllInstructionSets() {
4937        final String[] allAbis = Build.SUPPORTED_ABIS;
4938        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4939
4940        for (String abi : allAbis) {
4941            final String instructionSet = VMRuntime.getInstructionSet(abi);
4942            if (!allInstructionSets.contains(instructionSet)) {
4943                allInstructionSets.add(instructionSet);
4944            }
4945        }
4946
4947        return allInstructionSets;
4948    }
4949
4950    /**
4951     * Returns the instruction set that should be used to compile dex code. In the presence of
4952     * a native bridge this might be different than the one shared libraries use.
4953     */
4954    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4955        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4956        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4957    }
4958
4959    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4960        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
4961        for (String instructionSet : instructionSets) {
4962            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4963        }
4964        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4965    }
4966
4967    /**
4968     * Returns deduplicated list of supported instructions for dex code.
4969     */
4970    public static String[] getAllDexCodeInstructionSets() {
4971        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4972        for (int i = 0; i < supportedInstructionSets.length; i++) {
4973            String abi = Build.SUPPORTED_ABIS[i];
4974            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4975        }
4976        return getDexCodeInstructionSets(supportedInstructionSets);
4977    }
4978
4979    @Override
4980    public void forceDexOpt(String packageName) {
4981        enforceSystemOrRoot("forceDexOpt");
4982
4983        PackageParser.Package pkg;
4984        synchronized (mPackages) {
4985            pkg = mPackages.get(packageName);
4986            if (pkg == null) {
4987                throw new IllegalArgumentException("Missing package: " + packageName);
4988            }
4989        }
4990
4991        synchronized (mInstallLock) {
4992            final String[] instructionSets = new String[] {
4993                    getPrimaryInstructionSet(pkg.applicationInfo) };
4994            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4995            if (res != DEX_OPT_PERFORMED) {
4996                throw new IllegalStateException("Failed to dexopt: " + res);
4997            }
4998        }
4999    }
5000
5001    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5002                                boolean forceDex, boolean defer, boolean inclDependencies) {
5003        ArraySet<String> done;
5004        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5005            done = new ArraySet<String>();
5006            done.add(pkg.packageName);
5007        } else {
5008            done = null;
5009        }
5010        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5011    }
5012
5013    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5014        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5015            Slog.w(TAG, "Unable to update from " + oldPkg.name
5016                    + " to " + newPkg.packageName
5017                    + ": old package not in system partition");
5018            return false;
5019        } else if (mPackages.get(oldPkg.name) != null) {
5020            Slog.w(TAG, "Unable to update from " + oldPkg.name
5021                    + " to " + newPkg.packageName
5022                    + ": old package still exists");
5023            return false;
5024        }
5025        return true;
5026    }
5027
5028    File getDataPathForUser(int userId) {
5029        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5030    }
5031
5032    private File getDataPathForPackage(String packageName, int userId) {
5033        /*
5034         * Until we fully support multiple users, return the directory we
5035         * previously would have. The PackageManagerTests will need to be
5036         * revised when this is changed back..
5037         */
5038        if (userId == 0) {
5039            return new File(mAppDataDir, packageName);
5040        } else {
5041            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5042                + File.separator + packageName);
5043        }
5044    }
5045
5046    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5047        int[] users = sUserManager.getUserIds();
5048        int res = mInstaller.install(packageName, uid, uid, seinfo);
5049        if (res < 0) {
5050            return res;
5051        }
5052        for (int user : users) {
5053            if (user != 0) {
5054                res = mInstaller.createUserData(packageName,
5055                        UserHandle.getUid(user, uid), user, seinfo);
5056                if (res < 0) {
5057                    return res;
5058                }
5059            }
5060        }
5061        return res;
5062    }
5063
5064    private int removeDataDirsLI(String packageName) {
5065        int[] users = sUserManager.getUserIds();
5066        int res = 0;
5067        for (int user : users) {
5068            int resInner = mInstaller.remove(packageName, user);
5069            if (resInner < 0) {
5070                res = resInner;
5071            }
5072        }
5073
5074        return res;
5075    }
5076
5077    private int deleteCodeCacheDirsLI(String packageName) {
5078        int[] users = sUserManager.getUserIds();
5079        int res = 0;
5080        for (int user : users) {
5081            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5082            if (resInner < 0) {
5083                res = resInner;
5084            }
5085        }
5086        return res;
5087    }
5088
5089    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5090            PackageParser.Package changingLib) {
5091        if (file.path != null) {
5092            usesLibraryFiles.add(file.path);
5093            return;
5094        }
5095        PackageParser.Package p = mPackages.get(file.apk);
5096        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5097            // If we are doing this while in the middle of updating a library apk,
5098            // then we need to make sure to use that new apk for determining the
5099            // dependencies here.  (We haven't yet finished committing the new apk
5100            // to the package manager state.)
5101            if (p == null || p.packageName.equals(changingLib.packageName)) {
5102                p = changingLib;
5103            }
5104        }
5105        if (p != null) {
5106            usesLibraryFiles.addAll(p.getAllCodePaths());
5107        }
5108    }
5109
5110    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5111            PackageParser.Package changingLib) throws PackageManagerException {
5112        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5113            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5114            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5115            for (int i=0; i<N; i++) {
5116                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5117                if (file == null) {
5118                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5119                            "Package " + pkg.packageName + " requires unavailable shared library "
5120                            + pkg.usesLibraries.get(i) + "; failing!");
5121                }
5122                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5123            }
5124            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5125            for (int i=0; i<N; i++) {
5126                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5127                if (file == null) {
5128                    Slog.w(TAG, "Package " + pkg.packageName
5129                            + " desires unavailable shared library "
5130                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5131                } else {
5132                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5133                }
5134            }
5135            N = usesLibraryFiles.size();
5136            if (N > 0) {
5137                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5138            } else {
5139                pkg.usesLibraryFiles = null;
5140            }
5141        }
5142    }
5143
5144    private static boolean hasString(List<String> list, List<String> which) {
5145        if (list == null) {
5146            return false;
5147        }
5148        for (int i=list.size()-1; i>=0; i--) {
5149            for (int j=which.size()-1; j>=0; j--) {
5150                if (which.get(j).equals(list.get(i))) {
5151                    return true;
5152                }
5153            }
5154        }
5155        return false;
5156    }
5157
5158    private void updateAllSharedLibrariesLPw() {
5159        for (PackageParser.Package pkg : mPackages.values()) {
5160            try {
5161                updateSharedLibrariesLPw(pkg, null);
5162            } catch (PackageManagerException e) {
5163                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5164            }
5165        }
5166    }
5167
5168    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5169            PackageParser.Package changingPkg) {
5170        ArrayList<PackageParser.Package> res = null;
5171        for (PackageParser.Package pkg : mPackages.values()) {
5172            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5173                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5174                if (res == null) {
5175                    res = new ArrayList<PackageParser.Package>();
5176                }
5177                res.add(pkg);
5178                try {
5179                    updateSharedLibrariesLPw(pkg, changingPkg);
5180                } catch (PackageManagerException e) {
5181                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5182                }
5183            }
5184        }
5185        return res;
5186    }
5187
5188    /**
5189     * Derive the value of the {@code cpuAbiOverride} based on the provided
5190     * value and an optional stored value from the package settings.
5191     */
5192    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5193        String cpuAbiOverride = null;
5194
5195        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5196            cpuAbiOverride = null;
5197        } else if (abiOverride != null) {
5198            cpuAbiOverride = abiOverride;
5199        } else if (settings != null) {
5200            cpuAbiOverride = settings.cpuAbiOverrideString;
5201        }
5202
5203        return cpuAbiOverride;
5204    }
5205
5206    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5207            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5208        boolean success = false;
5209        try {
5210            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5211                    currentTime, user);
5212            success = true;
5213            return res;
5214        } finally {
5215            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5216                removeDataDirsLI(pkg.packageName);
5217            }
5218        }
5219    }
5220
5221    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5222            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5223        final File scanFile = new File(pkg.codePath);
5224        if (pkg.applicationInfo.getCodePath() == null ||
5225                pkg.applicationInfo.getResourcePath() == null) {
5226            // Bail out. The resource and code paths haven't been set.
5227            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5228                    "Code and resource paths haven't been set correctly");
5229        }
5230
5231        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5232            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5233        } else {
5234            // Only allow system apps to be flagged as core apps.
5235            pkg.coreApp = false;
5236        }
5237
5238        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5239            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5240        }
5241
5242        if (mCustomResolverComponentName != null &&
5243                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5244            setUpCustomResolverActivity(pkg);
5245        }
5246
5247        if (pkg.packageName.equals("android")) {
5248            synchronized (mPackages) {
5249                if (mAndroidApplication != null) {
5250                    Slog.w(TAG, "*************************************************");
5251                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5252                    Slog.w(TAG, " file=" + scanFile);
5253                    Slog.w(TAG, "*************************************************");
5254                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5255                            "Core android package being redefined.  Skipping.");
5256                }
5257
5258                // Set up information for our fall-back user intent resolution activity.
5259                mPlatformPackage = pkg;
5260                pkg.mVersionCode = mSdkVersion;
5261                mAndroidApplication = pkg.applicationInfo;
5262
5263                if (!mResolverReplaced) {
5264                    mResolveActivity.applicationInfo = mAndroidApplication;
5265                    mResolveActivity.name = ResolverActivity.class.getName();
5266                    mResolveActivity.packageName = mAndroidApplication.packageName;
5267                    mResolveActivity.processName = "system:ui";
5268                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5269                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5270                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5271                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5272                    mResolveActivity.exported = true;
5273                    mResolveActivity.enabled = true;
5274                    mResolveInfo.activityInfo = mResolveActivity;
5275                    mResolveInfo.priority = 0;
5276                    mResolveInfo.preferredOrder = 0;
5277                    mResolveInfo.match = 0;
5278                    mResolveComponentName = new ComponentName(
5279                            mAndroidApplication.packageName, mResolveActivity.name);
5280                }
5281            }
5282        }
5283
5284        if (DEBUG_PACKAGE_SCANNING) {
5285            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5286                Log.d(TAG, "Scanning package " + pkg.packageName);
5287        }
5288
5289        if (mPackages.containsKey(pkg.packageName)
5290                || mSharedLibraries.containsKey(pkg.packageName)) {
5291            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5292                    "Application package " + pkg.packageName
5293                    + " already installed.  Skipping duplicate.");
5294        }
5295
5296        // Initialize package source and resource directories
5297        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5298        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5299
5300        SharedUserSetting suid = null;
5301        PackageSetting pkgSetting = null;
5302
5303        if (!isSystemApp(pkg)) {
5304            // Only system apps can use these features.
5305            pkg.mOriginalPackages = null;
5306            pkg.mRealPackage = null;
5307            pkg.mAdoptPermissions = null;
5308        }
5309
5310        // writer
5311        synchronized (mPackages) {
5312            if (pkg.mSharedUserId != null) {
5313                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5314                if (suid == null) {
5315                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5316                            "Creating application package " + pkg.packageName
5317                            + " for shared user failed");
5318                }
5319                if (DEBUG_PACKAGE_SCANNING) {
5320                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5321                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5322                                + "): packages=" + suid.packages);
5323                }
5324            }
5325
5326            // Check if we are renaming from an original package name.
5327            PackageSetting origPackage = null;
5328            String realName = null;
5329            if (pkg.mOriginalPackages != null) {
5330                // This package may need to be renamed to a previously
5331                // installed name.  Let's check on that...
5332                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5333                if (pkg.mOriginalPackages.contains(renamed)) {
5334                    // This package had originally been installed as the
5335                    // original name, and we have already taken care of
5336                    // transitioning to the new one.  Just update the new
5337                    // one to continue using the old name.
5338                    realName = pkg.mRealPackage;
5339                    if (!pkg.packageName.equals(renamed)) {
5340                        // Callers into this function may have already taken
5341                        // care of renaming the package; only do it here if
5342                        // it is not already done.
5343                        pkg.setPackageName(renamed);
5344                    }
5345
5346                } else {
5347                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5348                        if ((origPackage = mSettings.peekPackageLPr(
5349                                pkg.mOriginalPackages.get(i))) != null) {
5350                            // We do have the package already installed under its
5351                            // original name...  should we use it?
5352                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5353                                // New package is not compatible with original.
5354                                origPackage = null;
5355                                continue;
5356                            } else if (origPackage.sharedUser != null) {
5357                                // Make sure uid is compatible between packages.
5358                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5359                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5360                                            + " to " + pkg.packageName + ": old uid "
5361                                            + origPackage.sharedUser.name
5362                                            + " differs from " + pkg.mSharedUserId);
5363                                    origPackage = null;
5364                                    continue;
5365                                }
5366                            } else {
5367                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5368                                        + pkg.packageName + " to old name " + origPackage.name);
5369                            }
5370                            break;
5371                        }
5372                    }
5373                }
5374            }
5375
5376            if (mTransferedPackages.contains(pkg.packageName)) {
5377                Slog.w(TAG, "Package " + pkg.packageName
5378                        + " was transferred to another, but its .apk remains");
5379            }
5380
5381            // Just create the setting, don't add it yet. For already existing packages
5382            // the PkgSetting exists already and doesn't have to be created.
5383            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5384                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5385                    pkg.applicationInfo.primaryCpuAbi,
5386                    pkg.applicationInfo.secondaryCpuAbi,
5387                    pkg.applicationInfo.flags, user, false);
5388            if (pkgSetting == null) {
5389                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5390                        "Creating application package " + pkg.packageName + " failed");
5391            }
5392
5393            if (pkgSetting.origPackage != null) {
5394                // If we are first transitioning from an original package,
5395                // fix up the new package's name now.  We need to do this after
5396                // looking up the package under its new name, so getPackageLP
5397                // can take care of fiddling things correctly.
5398                pkg.setPackageName(origPackage.name);
5399
5400                // File a report about this.
5401                String msg = "New package " + pkgSetting.realName
5402                        + " renamed to replace old package " + pkgSetting.name;
5403                reportSettingsProblem(Log.WARN, msg);
5404
5405                // Make a note of it.
5406                mTransferedPackages.add(origPackage.name);
5407
5408                // No longer need to retain this.
5409                pkgSetting.origPackage = null;
5410            }
5411
5412            if (realName != null) {
5413                // Make a note of it.
5414                mTransferedPackages.add(pkg.packageName);
5415            }
5416
5417            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5418                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5419            }
5420
5421            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5422                // Check all shared libraries and map to their actual file path.
5423                // We only do this here for apps not on a system dir, because those
5424                // are the only ones that can fail an install due to this.  We
5425                // will take care of the system apps by updating all of their
5426                // library paths after the scan is done.
5427                updateSharedLibrariesLPw(pkg, null);
5428            }
5429
5430            if (mFoundPolicyFile) {
5431                SELinuxMMAC.assignSeinfoValue(pkg);
5432            }
5433
5434            pkg.applicationInfo.uid = pkgSetting.appId;
5435            pkg.mExtras = pkgSetting;
5436            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5437                try {
5438                    verifySignaturesLP(pkgSetting, pkg);
5439                    // We just determined the app is signed correctly, so bring
5440                    // over the latest parsed certs.
5441                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5442                } catch (PackageManagerException e) {
5443                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5444                        throw e;
5445                    }
5446                    // The signature has changed, but this package is in the system
5447                    // image...  let's recover!
5448                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5449                    // However...  if this package is part of a shared user, but it
5450                    // doesn't match the signature of the shared user, let's fail.
5451                    // What this means is that you can't change the signatures
5452                    // associated with an overall shared user, which doesn't seem all
5453                    // that unreasonable.
5454                    if (pkgSetting.sharedUser != null) {
5455                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5456                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5457                            throw new PackageManagerException(
5458                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5459                                            "Signature mismatch for shared user : "
5460                                            + pkgSetting.sharedUser);
5461                        }
5462                    }
5463                    // File a report about this.
5464                    String msg = "System package " + pkg.packageName
5465                        + " signature changed; retaining data.";
5466                    reportSettingsProblem(Log.WARN, msg);
5467                }
5468            } else {
5469                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5470                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5471                            + pkg.packageName + " upgrade keys do not match the "
5472                            + "previously installed version");
5473                } else {
5474                    // We just determined the app is signed correctly, so bring
5475                    // over the latest parsed certs.
5476                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5477                }
5478            }
5479            // Verify that this new package doesn't have any content providers
5480            // that conflict with existing packages.  Only do this if the
5481            // package isn't already installed, since we don't want to break
5482            // things that are installed.
5483            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5484                final int N = pkg.providers.size();
5485                int i;
5486                for (i=0; i<N; i++) {
5487                    PackageParser.Provider p = pkg.providers.get(i);
5488                    if (p.info.authority != null) {
5489                        String names[] = p.info.authority.split(";");
5490                        for (int j = 0; j < names.length; j++) {
5491                            if (mProvidersByAuthority.containsKey(names[j])) {
5492                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5493                                final String otherPackageName =
5494                                        ((other != null && other.getComponentName() != null) ?
5495                                                other.getComponentName().getPackageName() : "?");
5496                                throw new PackageManagerException(
5497                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5498                                                "Can't install because provider name " + names[j]
5499                                                + " (in package " + pkg.applicationInfo.packageName
5500                                                + ") is already used by " + otherPackageName);
5501                            }
5502                        }
5503                    }
5504                }
5505            }
5506
5507            if (pkg.mAdoptPermissions != null) {
5508                // This package wants to adopt ownership of permissions from
5509                // another package.
5510                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5511                    final String origName = pkg.mAdoptPermissions.get(i);
5512                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5513                    if (orig != null) {
5514                        if (verifyPackageUpdateLPr(orig, pkg)) {
5515                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5516                                    + pkg.packageName);
5517                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5518                        }
5519                    }
5520                }
5521            }
5522        }
5523
5524        final String pkgName = pkg.packageName;
5525
5526        final long scanFileTime = scanFile.lastModified();
5527        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5528        pkg.applicationInfo.processName = fixProcessName(
5529                pkg.applicationInfo.packageName,
5530                pkg.applicationInfo.processName,
5531                pkg.applicationInfo.uid);
5532
5533        File dataPath;
5534        if (mPlatformPackage == pkg) {
5535            // The system package is special.
5536            dataPath = new File(Environment.getDataDirectory(), "system");
5537
5538            pkg.applicationInfo.dataDir = dataPath.getPath();
5539
5540        } else {
5541            // This is a normal package, need to make its data directory.
5542            dataPath = getDataPathForPackage(pkg.packageName, 0);
5543
5544            boolean uidError = false;
5545            if (dataPath.exists()) {
5546                int currentUid = 0;
5547                try {
5548                    StructStat stat = Os.stat(dataPath.getPath());
5549                    currentUid = stat.st_uid;
5550                } catch (ErrnoException e) {
5551                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5552                }
5553
5554                // If we have mismatched owners for the data path, we have a problem.
5555                if (currentUid != pkg.applicationInfo.uid) {
5556                    boolean recovered = false;
5557                    if (currentUid == 0) {
5558                        // The directory somehow became owned by root.  Wow.
5559                        // This is probably because the system was stopped while
5560                        // installd was in the middle of messing with its libs
5561                        // directory.  Ask installd to fix that.
5562                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5563                                pkg.applicationInfo.uid);
5564                        if (ret >= 0) {
5565                            recovered = true;
5566                            String msg = "Package " + pkg.packageName
5567                                    + " unexpectedly changed to uid 0; recovered to " +
5568                                    + pkg.applicationInfo.uid;
5569                            reportSettingsProblem(Log.WARN, msg);
5570                        }
5571                    }
5572                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5573                            || (scanFlags&SCAN_BOOTING) != 0)) {
5574                        // If this is a system app, we can at least delete its
5575                        // current data so the application will still work.
5576                        int ret = removeDataDirsLI(pkgName);
5577                        if (ret >= 0) {
5578                            // TODO: Kill the processes first
5579                            // Old data gone!
5580                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5581                                    ? "System package " : "Third party package ";
5582                            String msg = prefix + pkg.packageName
5583                                    + " has changed from uid: "
5584                                    + currentUid + " to "
5585                                    + pkg.applicationInfo.uid + "; old data erased";
5586                            reportSettingsProblem(Log.WARN, msg);
5587                            recovered = true;
5588
5589                            // And now re-install the app.
5590                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5591                                                   pkg.applicationInfo.seinfo);
5592                            if (ret == -1) {
5593                                // Ack should not happen!
5594                                msg = prefix + pkg.packageName
5595                                        + " could not have data directory re-created after delete.";
5596                                reportSettingsProblem(Log.WARN, msg);
5597                                throw new PackageManagerException(
5598                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5599                            }
5600                        }
5601                        if (!recovered) {
5602                            mHasSystemUidErrors = true;
5603                        }
5604                    } else if (!recovered) {
5605                        // If we allow this install to proceed, we will be broken.
5606                        // Abort, abort!
5607                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5608                                "scanPackageLI");
5609                    }
5610                    if (!recovered) {
5611                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5612                            + pkg.applicationInfo.uid + "/fs_"
5613                            + currentUid;
5614                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5615                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5616                        String msg = "Package " + pkg.packageName
5617                                + " has mismatched uid: "
5618                                + currentUid + " on disk, "
5619                                + pkg.applicationInfo.uid + " in settings";
5620                        // writer
5621                        synchronized (mPackages) {
5622                            mSettings.mReadMessages.append(msg);
5623                            mSettings.mReadMessages.append('\n');
5624                            uidError = true;
5625                            if (!pkgSetting.uidError) {
5626                                reportSettingsProblem(Log.ERROR, msg);
5627                            }
5628                        }
5629                    }
5630                }
5631                pkg.applicationInfo.dataDir = dataPath.getPath();
5632                if (mShouldRestoreconData) {
5633                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5634                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5635                                pkg.applicationInfo.uid);
5636                }
5637            } else {
5638                if (DEBUG_PACKAGE_SCANNING) {
5639                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5640                        Log.v(TAG, "Want this data dir: " + dataPath);
5641                }
5642                //invoke installer to do the actual installation
5643                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5644                                           pkg.applicationInfo.seinfo);
5645                if (ret < 0) {
5646                    // Error from installer
5647                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5648                            "Unable to create data dirs [errorCode=" + ret + "]");
5649                }
5650
5651                if (dataPath.exists()) {
5652                    pkg.applicationInfo.dataDir = dataPath.getPath();
5653                } else {
5654                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5655                    pkg.applicationInfo.dataDir = null;
5656                }
5657            }
5658
5659            pkgSetting.uidError = uidError;
5660        }
5661
5662        final String path = scanFile.getPath();
5663        final String codePath = pkg.applicationInfo.getCodePath();
5664        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5665        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5666            setBundledAppAbisAndRoots(pkg, pkgSetting);
5667
5668            // If we haven't found any native libraries for the app, check if it has
5669            // renderscript code. We'll need to force the app to 32 bit if it has
5670            // renderscript bitcode.
5671            if (pkg.applicationInfo.primaryCpuAbi == null
5672                    && pkg.applicationInfo.secondaryCpuAbi == null
5673                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5674                NativeLibraryHelper.Handle handle = null;
5675                try {
5676                    handle = NativeLibraryHelper.Handle.create(scanFile);
5677                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5678                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5679                    }
5680                } catch (IOException ioe) {
5681                    Slog.w(TAG, "Error scanning system app : " + ioe);
5682                } finally {
5683                    IoUtils.closeQuietly(handle);
5684                }
5685            }
5686
5687            setNativeLibraryPaths(pkg);
5688        } else {
5689            // TODO: We can probably be smarter about this stuff. For installed apps,
5690            // we can calculate this information at install time once and for all. For
5691            // system apps, we can probably assume that this information doesn't change
5692            // after the first boot scan. As things stand, we do lots of unnecessary work.
5693
5694            // Give ourselves some initial paths; we'll come back for another
5695            // pass once we've determined ABI below.
5696            setNativeLibraryPaths(pkg);
5697
5698            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5699            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5700            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5701
5702            NativeLibraryHelper.Handle handle = null;
5703            try {
5704                handle = NativeLibraryHelper.Handle.create(scanFile);
5705                // TODO(multiArch): This can be null for apps that didn't go through the
5706                // usual installation process. We can calculate it again, like we
5707                // do during install time.
5708                //
5709                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5710                // unnecessary.
5711                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5712
5713                // Null out the abis so that they can be recalculated.
5714                pkg.applicationInfo.primaryCpuAbi = null;
5715                pkg.applicationInfo.secondaryCpuAbi = null;
5716                if (isMultiArch(pkg.applicationInfo)) {
5717                    // Warn if we've set an abiOverride for multi-lib packages..
5718                    // By definition, we need to copy both 32 and 64 bit libraries for
5719                    // such packages.
5720                    if (pkg.cpuAbiOverride != null
5721                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5722                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5723                    }
5724
5725                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5726                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5727                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5728                        if (isAsec) {
5729                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5730                        } else {
5731                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5732                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5733                                    useIsaSpecificSubdirs);
5734                        }
5735                    }
5736
5737                    maybeThrowExceptionForMultiArchCopy(
5738                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5739
5740                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5741                        if (isAsec) {
5742                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5743                        } else {
5744                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5745                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5746                                    useIsaSpecificSubdirs);
5747                        }
5748                    }
5749
5750                    maybeThrowExceptionForMultiArchCopy(
5751                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5752
5753                    if (abi64 >= 0) {
5754                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5755                    }
5756
5757                    if (abi32 >= 0) {
5758                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5759                        if (abi64 >= 0) {
5760                            pkg.applicationInfo.secondaryCpuAbi = abi;
5761                        } else {
5762                            pkg.applicationInfo.primaryCpuAbi = abi;
5763                        }
5764                    }
5765                } else {
5766                    String[] abiList = (cpuAbiOverride != null) ?
5767                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5768
5769                    // Enable gross and lame hacks for apps that are built with old
5770                    // SDK tools. We must scan their APKs for renderscript bitcode and
5771                    // not launch them if it's present. Don't bother checking on devices
5772                    // that don't have 64 bit support.
5773                    boolean needsRenderScriptOverride = false;
5774                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5775                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5776                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5777                        needsRenderScriptOverride = true;
5778                    }
5779
5780                    final int copyRet;
5781                    if (isAsec) {
5782                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5783                    } else {
5784                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5785                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5786                    }
5787
5788                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5789                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5790                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5791                    }
5792
5793                    if (copyRet >= 0) {
5794                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5795                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5796                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5797                    } else if (needsRenderScriptOverride) {
5798                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5799                    }
5800                }
5801            } catch (IOException ioe) {
5802                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5803            } finally {
5804                IoUtils.closeQuietly(handle);
5805            }
5806
5807            // Now that we've calculated the ABIs and determined if it's an internal app,
5808            // we will go ahead and populate the nativeLibraryPath.
5809            setNativeLibraryPaths(pkg);
5810
5811            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5812            final int[] userIds = sUserManager.getUserIds();
5813            synchronized (mInstallLock) {
5814                // Create a native library symlink only if we have native libraries
5815                // and if the native libraries are 32 bit libraries. We do not provide
5816                // this symlink for 64 bit libraries.
5817                if (pkg.applicationInfo.primaryCpuAbi != null &&
5818                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5819                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5820                    for (int userId : userIds) {
5821                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5822                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5823                                    "Failed linking native library dir (user=" + userId + ")");
5824                        }
5825                    }
5826                }
5827            }
5828        }
5829
5830        // This is a special case for the "system" package, where the ABI is
5831        // dictated by the zygote configuration (and init.rc). We should keep track
5832        // of this ABI so that we can deal with "normal" applications that run under
5833        // the same UID correctly.
5834        if (mPlatformPackage == pkg) {
5835            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5836                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5837        }
5838
5839        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5840        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5841        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5842        // Copy the derived override back to the parsed package, so that we can
5843        // update the package settings accordingly.
5844        pkg.cpuAbiOverride = cpuAbiOverride;
5845
5846        if (DEBUG_ABI_SELECTION) {
5847            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5848                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5849                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5850        }
5851
5852        // Push the derived path down into PackageSettings so we know what to
5853        // clean up at uninstall time.
5854        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5855
5856        if (DEBUG_ABI_SELECTION) {
5857            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5858                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5859                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5860        }
5861
5862        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5863            // We don't do this here during boot because we can do it all
5864            // at once after scanning all existing packages.
5865            //
5866            // We also do this *before* we perform dexopt on this package, so that
5867            // we can avoid redundant dexopts, and also to make sure we've got the
5868            // code and package path correct.
5869            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5870                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5871        }
5872
5873        if ((scanFlags & SCAN_NO_DEX) == 0) {
5874            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5875                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5876                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5877            }
5878        }
5879
5880        if (mFactoryTest && pkg.requestedPermissions.contains(
5881                android.Manifest.permission.FACTORY_TEST)) {
5882            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5883        }
5884
5885        ArrayList<PackageParser.Package> clientLibPkgs = null;
5886
5887        // writer
5888        synchronized (mPackages) {
5889            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5890                // Only system apps can add new shared libraries.
5891                if (pkg.libraryNames != null) {
5892                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5893                        String name = pkg.libraryNames.get(i);
5894                        boolean allowed = false;
5895                        if (isUpdatedSystemApp(pkg)) {
5896                            // New library entries can only be added through the
5897                            // system image.  This is important to get rid of a lot
5898                            // of nasty edge cases: for example if we allowed a non-
5899                            // system update of the app to add a library, then uninstalling
5900                            // the update would make the library go away, and assumptions
5901                            // we made such as through app install filtering would now
5902                            // have allowed apps on the device which aren't compatible
5903                            // with it.  Better to just have the restriction here, be
5904                            // conservative, and create many fewer cases that can negatively
5905                            // impact the user experience.
5906                            final PackageSetting sysPs = mSettings
5907                                    .getDisabledSystemPkgLPr(pkg.packageName);
5908                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5909                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5910                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5911                                        allowed = true;
5912                                        allowed = true;
5913                                        break;
5914                                    }
5915                                }
5916                            }
5917                        } else {
5918                            allowed = true;
5919                        }
5920                        if (allowed) {
5921                            if (!mSharedLibraries.containsKey(name)) {
5922                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5923                            } else if (!name.equals(pkg.packageName)) {
5924                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5925                                        + name + " already exists; skipping");
5926                            }
5927                        } else {
5928                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5929                                    + name + " that is not declared on system image; skipping");
5930                        }
5931                    }
5932                    if ((scanFlags&SCAN_BOOTING) == 0) {
5933                        // If we are not booting, we need to update any applications
5934                        // that are clients of our shared library.  If we are booting,
5935                        // this will all be done once the scan is complete.
5936                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5937                    }
5938                }
5939            }
5940        }
5941
5942        // We also need to dexopt any apps that are dependent on this library.  Note that
5943        // if these fail, we should abort the install since installing the library will
5944        // result in some apps being broken.
5945        if (clientLibPkgs != null) {
5946            if ((scanFlags & SCAN_NO_DEX) == 0) {
5947                for (int i = 0; i < clientLibPkgs.size(); i++) {
5948                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5949                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5950                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5951                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5952                                "scanPackageLI failed to dexopt clientLibPkgs");
5953                    }
5954                }
5955            }
5956        }
5957
5958        // Request the ActivityManager to kill the process(only for existing packages)
5959        // so that we do not end up in a confused state while the user is still using the older
5960        // version of the application while the new one gets installed.
5961        if ((scanFlags & SCAN_REPLACING) != 0) {
5962            killApplication(pkg.applicationInfo.packageName,
5963                        pkg.applicationInfo.uid, "update pkg");
5964        }
5965
5966        // Also need to kill any apps that are dependent on the library.
5967        if (clientLibPkgs != null) {
5968            for (int i=0; i<clientLibPkgs.size(); i++) {
5969                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5970                killApplication(clientPkg.applicationInfo.packageName,
5971                        clientPkg.applicationInfo.uid, "update lib");
5972            }
5973        }
5974
5975        // writer
5976        synchronized (mPackages) {
5977            // We don't expect installation to fail beyond this point
5978
5979            // Add the new setting to mSettings
5980            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5981            // Add the new setting to mPackages
5982            mPackages.put(pkg.applicationInfo.packageName, pkg);
5983            // Make sure we don't accidentally delete its data.
5984            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5985            while (iter.hasNext()) {
5986                PackageCleanItem item = iter.next();
5987                if (pkgName.equals(item.packageName)) {
5988                    iter.remove();
5989                }
5990            }
5991
5992            // Take care of first install / last update times.
5993            if (currentTime != 0) {
5994                if (pkgSetting.firstInstallTime == 0) {
5995                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5996                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5997                    pkgSetting.lastUpdateTime = currentTime;
5998                }
5999            } else if (pkgSetting.firstInstallTime == 0) {
6000                // We need *something*.  Take time time stamp of the file.
6001                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6002            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6003                if (scanFileTime != pkgSetting.timeStamp) {
6004                    // A package on the system image has changed; consider this
6005                    // to be an update.
6006                    pkgSetting.lastUpdateTime = scanFileTime;
6007                }
6008            }
6009
6010            // Add the package's KeySets to the global KeySetManagerService
6011            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6012            try {
6013                // Old KeySetData no longer valid.
6014                ksms.removeAppKeySetDataLPw(pkg.packageName);
6015                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6016                if (pkg.mKeySetMapping != null) {
6017                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6018                            pkg.mKeySetMapping.entrySet()) {
6019                        if (entry.getValue() != null) {
6020                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6021                                                          entry.getValue(), entry.getKey());
6022                        }
6023                    }
6024                    if (pkg.mUpgradeKeySets != null) {
6025                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6026                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6027                        }
6028                    }
6029                }
6030            } catch (NullPointerException e) {
6031                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6032            } catch (IllegalArgumentException e) {
6033                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6034            }
6035
6036            int N = pkg.providers.size();
6037            StringBuilder r = null;
6038            int i;
6039            for (i=0; i<N; i++) {
6040                PackageParser.Provider p = pkg.providers.get(i);
6041                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6042                        p.info.processName, pkg.applicationInfo.uid);
6043                mProviders.addProvider(p);
6044                p.syncable = p.info.isSyncable;
6045                if (p.info.authority != null) {
6046                    String names[] = p.info.authority.split(";");
6047                    p.info.authority = null;
6048                    for (int j = 0; j < names.length; j++) {
6049                        if (j == 1 && p.syncable) {
6050                            // We only want the first authority for a provider to possibly be
6051                            // syncable, so if we already added this provider using a different
6052                            // authority clear the syncable flag. We copy the provider before
6053                            // changing it because the mProviders object contains a reference
6054                            // to a provider that we don't want to change.
6055                            // Only do this for the second authority since the resulting provider
6056                            // object can be the same for all future authorities for this provider.
6057                            p = new PackageParser.Provider(p);
6058                            p.syncable = false;
6059                        }
6060                        if (!mProvidersByAuthority.containsKey(names[j])) {
6061                            mProvidersByAuthority.put(names[j], p);
6062                            if (p.info.authority == null) {
6063                                p.info.authority = names[j];
6064                            } else {
6065                                p.info.authority = p.info.authority + ";" + names[j];
6066                            }
6067                            if (DEBUG_PACKAGE_SCANNING) {
6068                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6069                                    Log.d(TAG, "Registered content provider: " + names[j]
6070                                            + ", className = " + p.info.name + ", isSyncable = "
6071                                            + p.info.isSyncable);
6072                            }
6073                        } else {
6074                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6075                            Slog.w(TAG, "Skipping provider name " + names[j] +
6076                                    " (in package " + pkg.applicationInfo.packageName +
6077                                    "): name already used by "
6078                                    + ((other != null && other.getComponentName() != null)
6079                                            ? other.getComponentName().getPackageName() : "?"));
6080                        }
6081                    }
6082                }
6083                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6084                    if (r == null) {
6085                        r = new StringBuilder(256);
6086                    } else {
6087                        r.append(' ');
6088                    }
6089                    r.append(p.info.name);
6090                }
6091            }
6092            if (r != null) {
6093                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6094            }
6095
6096            N = pkg.services.size();
6097            r = null;
6098            for (i=0; i<N; i++) {
6099                PackageParser.Service s = pkg.services.get(i);
6100                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6101                        s.info.processName, pkg.applicationInfo.uid);
6102                mServices.addService(s);
6103                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6104                    if (r == null) {
6105                        r = new StringBuilder(256);
6106                    } else {
6107                        r.append(' ');
6108                    }
6109                    r.append(s.info.name);
6110                }
6111            }
6112            if (r != null) {
6113                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6114            }
6115
6116            N = pkg.receivers.size();
6117            r = null;
6118            for (i=0; i<N; i++) {
6119                PackageParser.Activity a = pkg.receivers.get(i);
6120                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6121                        a.info.processName, pkg.applicationInfo.uid);
6122                mReceivers.addActivity(a, "receiver");
6123                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6124                    if (r == null) {
6125                        r = new StringBuilder(256);
6126                    } else {
6127                        r.append(' ');
6128                    }
6129                    r.append(a.info.name);
6130                }
6131            }
6132            if (r != null) {
6133                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6134            }
6135
6136            N = pkg.activities.size();
6137            r = null;
6138            for (i=0; i<N; i++) {
6139                PackageParser.Activity a = pkg.activities.get(i);
6140                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6141                        a.info.processName, pkg.applicationInfo.uid);
6142                mActivities.addActivity(a, "activity");
6143                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6144                    if (r == null) {
6145                        r = new StringBuilder(256);
6146                    } else {
6147                        r.append(' ');
6148                    }
6149                    r.append(a.info.name);
6150                }
6151            }
6152            if (r != null) {
6153                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6154            }
6155
6156            N = pkg.permissionGroups.size();
6157            r = null;
6158            for (i=0; i<N; i++) {
6159                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6160                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6161                if (cur == null) {
6162                    mPermissionGroups.put(pg.info.name, pg);
6163                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6164                        if (r == null) {
6165                            r = new StringBuilder(256);
6166                        } else {
6167                            r.append(' ');
6168                        }
6169                        r.append(pg.info.name);
6170                    }
6171                } else {
6172                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6173                            + pg.info.packageName + " ignored: original from "
6174                            + cur.info.packageName);
6175                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6176                        if (r == null) {
6177                            r = new StringBuilder(256);
6178                        } else {
6179                            r.append(' ');
6180                        }
6181                        r.append("DUP:");
6182                        r.append(pg.info.name);
6183                    }
6184                }
6185            }
6186            if (r != null) {
6187                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6188            }
6189
6190            N = pkg.permissions.size();
6191            r = null;
6192            for (i=0; i<N; i++) {
6193                PackageParser.Permission p = pkg.permissions.get(i);
6194                ArrayMap<String, BasePermission> permissionMap =
6195                        p.tree ? mSettings.mPermissionTrees
6196                        : mSettings.mPermissions;
6197                p.group = mPermissionGroups.get(p.info.group);
6198                if (p.info.group == null || p.group != null) {
6199                    BasePermission bp = permissionMap.get(p.info.name);
6200
6201                    // Allow system apps to redefine non-system permissions
6202                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6203                        final boolean currentOwnerIsSystem = (bp.perm != null
6204                                && isSystemApp(bp.perm.owner));
6205                        if (isSystemApp(p.owner)) {
6206                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6207                                // It's a built-in permission and no owner, take ownership now
6208                                bp.packageSetting = pkgSetting;
6209                                bp.perm = p;
6210                                bp.uid = pkg.applicationInfo.uid;
6211                                bp.sourcePackage = p.info.packageName;
6212                            } else if (!currentOwnerIsSystem) {
6213                                String msg = "New decl " + p.owner + " of permission  "
6214                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6215                                reportSettingsProblem(Log.WARN, msg);
6216                                bp = null;
6217                            }
6218                        }
6219                    }
6220
6221                    if (bp == null) {
6222                        bp = new BasePermission(p.info.name, p.info.packageName,
6223                                BasePermission.TYPE_NORMAL);
6224                        permissionMap.put(p.info.name, bp);
6225                    }
6226
6227                    if (bp.perm == null) {
6228                        if (bp.sourcePackage == null
6229                                || bp.sourcePackage.equals(p.info.packageName)) {
6230                            BasePermission tree = findPermissionTreeLP(p.info.name);
6231                            if (tree == null
6232                                    || tree.sourcePackage.equals(p.info.packageName)) {
6233                                bp.packageSetting = pkgSetting;
6234                                bp.perm = p;
6235                                bp.uid = pkg.applicationInfo.uid;
6236                                bp.sourcePackage = p.info.packageName;
6237                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6238                                    if (r == null) {
6239                                        r = new StringBuilder(256);
6240                                    } else {
6241                                        r.append(' ');
6242                                    }
6243                                    r.append(p.info.name);
6244                                }
6245                            } else {
6246                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6247                                        + p.info.packageName + " ignored: base tree "
6248                                        + tree.name + " is from package "
6249                                        + tree.sourcePackage);
6250                            }
6251                        } else {
6252                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6253                                    + p.info.packageName + " ignored: original from "
6254                                    + bp.sourcePackage);
6255                        }
6256                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6257                        if (r == null) {
6258                            r = new StringBuilder(256);
6259                        } else {
6260                            r.append(' ');
6261                        }
6262                        r.append("DUP:");
6263                        r.append(p.info.name);
6264                    }
6265                    if (bp.perm == p) {
6266                        bp.protectionLevel = p.info.protectionLevel;
6267                    }
6268                } else {
6269                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6270                            + p.info.packageName + " ignored: no group "
6271                            + p.group);
6272                }
6273            }
6274            if (r != null) {
6275                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6276            }
6277
6278            N = pkg.instrumentation.size();
6279            r = null;
6280            for (i=0; i<N; i++) {
6281                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6282                a.info.packageName = pkg.applicationInfo.packageName;
6283                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6284                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6285                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6286                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6287                a.info.dataDir = pkg.applicationInfo.dataDir;
6288
6289                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6290                // need other information about the application, like the ABI and what not ?
6291                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6292                mInstrumentation.put(a.getComponentName(), a);
6293                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6294                    if (r == null) {
6295                        r = new StringBuilder(256);
6296                    } else {
6297                        r.append(' ');
6298                    }
6299                    r.append(a.info.name);
6300                }
6301            }
6302            if (r != null) {
6303                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6304            }
6305
6306            if (pkg.protectedBroadcasts != null) {
6307                N = pkg.protectedBroadcasts.size();
6308                for (i=0; i<N; i++) {
6309                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6310                }
6311            }
6312
6313            pkgSetting.setTimeStamp(scanFileTime);
6314
6315            // Create idmap files for pairs of (packages, overlay packages).
6316            // Note: "android", ie framework-res.apk, is handled by native layers.
6317            if (pkg.mOverlayTarget != null) {
6318                // This is an overlay package.
6319                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6320                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6321                        mOverlays.put(pkg.mOverlayTarget,
6322                                new ArrayMap<String, PackageParser.Package>());
6323                    }
6324                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6325                    map.put(pkg.packageName, pkg);
6326                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6327                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6328                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6329                                "scanPackageLI failed to createIdmap");
6330                    }
6331                }
6332            } else if (mOverlays.containsKey(pkg.packageName) &&
6333                    !pkg.packageName.equals("android")) {
6334                // This is a regular package, with one or more known overlay packages.
6335                createIdmapsForPackageLI(pkg);
6336            }
6337        }
6338
6339        return pkg;
6340    }
6341
6342    /**
6343     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6344     * i.e, so that all packages can be run inside a single process if required.
6345     *
6346     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6347     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6348     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6349     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6350     * updating a package that belongs to a shared user.
6351     *
6352     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6353     * adds unnecessary complexity.
6354     */
6355    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6356            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6357        String requiredInstructionSet = null;
6358        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6359            requiredInstructionSet = VMRuntime.getInstructionSet(
6360                     scannedPackage.applicationInfo.primaryCpuAbi);
6361        }
6362
6363        PackageSetting requirer = null;
6364        for (PackageSetting ps : packagesForUser) {
6365            // If packagesForUser contains scannedPackage, we skip it. This will happen
6366            // when scannedPackage is an update of an existing package. Without this check,
6367            // we will never be able to change the ABI of any package belonging to a shared
6368            // user, even if it's compatible with other packages.
6369            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6370                if (ps.primaryCpuAbiString == null) {
6371                    continue;
6372                }
6373
6374                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6375                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6376                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6377                    // this but there's not much we can do.
6378                    String errorMessage = "Instruction set mismatch, "
6379                            + ((requirer == null) ? "[caller]" : requirer)
6380                            + " requires " + requiredInstructionSet + " whereas " + ps
6381                            + " requires " + instructionSet;
6382                    Slog.w(TAG, errorMessage);
6383                }
6384
6385                if (requiredInstructionSet == null) {
6386                    requiredInstructionSet = instructionSet;
6387                    requirer = ps;
6388                }
6389            }
6390        }
6391
6392        if (requiredInstructionSet != null) {
6393            String adjustedAbi;
6394            if (requirer != null) {
6395                // requirer != null implies that either scannedPackage was null or that scannedPackage
6396                // did not require an ABI, in which case we have to adjust scannedPackage to match
6397                // the ABI of the set (which is the same as requirer's ABI)
6398                adjustedAbi = requirer.primaryCpuAbiString;
6399                if (scannedPackage != null) {
6400                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6401                }
6402            } else {
6403                // requirer == null implies that we're updating all ABIs in the set to
6404                // match scannedPackage.
6405                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6406            }
6407
6408            for (PackageSetting ps : packagesForUser) {
6409                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6410                    if (ps.primaryCpuAbiString != null) {
6411                        continue;
6412                    }
6413
6414                    ps.primaryCpuAbiString = adjustedAbi;
6415                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6416                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6417                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6418
6419                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6420                                deferDexOpt, true) == DEX_OPT_FAILED) {
6421                            ps.primaryCpuAbiString = null;
6422                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6423                            return;
6424                        } else {
6425                            mInstaller.rmdex(ps.codePathString,
6426                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6427                        }
6428                    }
6429                }
6430            }
6431        }
6432    }
6433
6434    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6435        synchronized (mPackages) {
6436            mResolverReplaced = true;
6437            // Set up information for custom user intent resolution activity.
6438            mResolveActivity.applicationInfo = pkg.applicationInfo;
6439            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6440            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6441            mResolveActivity.processName = pkg.applicationInfo.packageName;
6442            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6443            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6444                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6445            mResolveActivity.theme = 0;
6446            mResolveActivity.exported = true;
6447            mResolveActivity.enabled = true;
6448            mResolveInfo.activityInfo = mResolveActivity;
6449            mResolveInfo.priority = 0;
6450            mResolveInfo.preferredOrder = 0;
6451            mResolveInfo.match = 0;
6452            mResolveComponentName = mCustomResolverComponentName;
6453            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6454                    mResolveComponentName);
6455        }
6456    }
6457
6458    private static String calculateBundledApkRoot(final String codePathString) {
6459        final File codePath = new File(codePathString);
6460        final File codeRoot;
6461        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6462            codeRoot = Environment.getRootDirectory();
6463        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6464            codeRoot = Environment.getOemDirectory();
6465        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6466            codeRoot = Environment.getVendorDirectory();
6467        } else {
6468            // Unrecognized code path; take its top real segment as the apk root:
6469            // e.g. /something/app/blah.apk => /something
6470            try {
6471                File f = codePath.getCanonicalFile();
6472                File parent = f.getParentFile();    // non-null because codePath is a file
6473                File tmp;
6474                while ((tmp = parent.getParentFile()) != null) {
6475                    f = parent;
6476                    parent = tmp;
6477                }
6478                codeRoot = f;
6479                Slog.w(TAG, "Unrecognized code path "
6480                        + codePath + " - using " + codeRoot);
6481            } catch (IOException e) {
6482                // Can't canonicalize the code path -- shenanigans?
6483                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6484                return Environment.getRootDirectory().getPath();
6485            }
6486        }
6487        return codeRoot.getPath();
6488    }
6489
6490    /**
6491     * Derive and set the location of native libraries for the given package,
6492     * which varies depending on where and how the package was installed.
6493     */
6494    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6495        final ApplicationInfo info = pkg.applicationInfo;
6496        final String codePath = pkg.codePath;
6497        final File codeFile = new File(codePath);
6498        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6499        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6500
6501        info.nativeLibraryRootDir = null;
6502        info.nativeLibraryRootRequiresIsa = false;
6503        info.nativeLibraryDir = null;
6504        info.secondaryNativeLibraryDir = null;
6505
6506        if (isApkFile(codeFile)) {
6507            // Monolithic install
6508            if (bundledApp) {
6509                // If "/system/lib64/apkname" exists, assume that is the per-package
6510                // native library directory to use; otherwise use "/system/lib/apkname".
6511                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6512                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6513                        getPrimaryInstructionSet(info));
6514
6515                // This is a bundled system app so choose the path based on the ABI.
6516                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6517                // is just the default path.
6518                final String apkName = deriveCodePathName(codePath);
6519                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6520                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6521                        apkName).getAbsolutePath();
6522
6523                if (info.secondaryCpuAbi != null) {
6524                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6525                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6526                            secondaryLibDir, apkName).getAbsolutePath();
6527                }
6528            } else if (asecApp) {
6529                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6530                        .getAbsolutePath();
6531            } else {
6532                final String apkName = deriveCodePathName(codePath);
6533                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6534                        .getAbsolutePath();
6535            }
6536
6537            info.nativeLibraryRootRequiresIsa = false;
6538            info.nativeLibraryDir = info.nativeLibraryRootDir;
6539        } else {
6540            // Cluster install
6541            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6542            info.nativeLibraryRootRequiresIsa = true;
6543
6544            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6545                    getPrimaryInstructionSet(info)).getAbsolutePath();
6546
6547            if (info.secondaryCpuAbi != null) {
6548                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6549                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6550            }
6551        }
6552    }
6553
6554    /**
6555     * Calculate the abis and roots for a bundled app. These can uniquely
6556     * be determined from the contents of the system partition, i.e whether
6557     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6558     * of this information, and instead assume that the system was built
6559     * sensibly.
6560     */
6561    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6562                                           PackageSetting pkgSetting) {
6563        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6564
6565        // If "/system/lib64/apkname" exists, assume that is the per-package
6566        // native library directory to use; otherwise use "/system/lib/apkname".
6567        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6568        setBundledAppAbi(pkg, apkRoot, apkName);
6569        // pkgSetting might be null during rescan following uninstall of updates
6570        // to a bundled app, so accommodate that possibility.  The settings in
6571        // that case will be established later from the parsed package.
6572        //
6573        // If the settings aren't null, sync them up with what we've just derived.
6574        // note that apkRoot isn't stored in the package settings.
6575        if (pkgSetting != null) {
6576            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6577            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6578        }
6579    }
6580
6581    /**
6582     * Deduces the ABI of a bundled app and sets the relevant fields on the
6583     * parsed pkg object.
6584     *
6585     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6586     *        under which system libraries are installed.
6587     * @param apkName the name of the installed package.
6588     */
6589    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6590        final File codeFile = new File(pkg.codePath);
6591
6592        final boolean has64BitLibs;
6593        final boolean has32BitLibs;
6594        if (isApkFile(codeFile)) {
6595            // Monolithic install
6596            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6597            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6598        } else {
6599            // Cluster install
6600            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6601            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6602                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6603                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6604                has64BitLibs = (new File(rootDir, isa)).exists();
6605            } else {
6606                has64BitLibs = false;
6607            }
6608            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6609                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6610                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6611                has32BitLibs = (new File(rootDir, isa)).exists();
6612            } else {
6613                has32BitLibs = false;
6614            }
6615        }
6616
6617        if (has64BitLibs && !has32BitLibs) {
6618            // The package has 64 bit libs, but not 32 bit libs. Its primary
6619            // ABI should be 64 bit. We can safely assume here that the bundled
6620            // native libraries correspond to the most preferred ABI in the list.
6621
6622            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6623            pkg.applicationInfo.secondaryCpuAbi = null;
6624        } else if (has32BitLibs && !has64BitLibs) {
6625            // The package has 32 bit libs but not 64 bit libs. Its primary
6626            // ABI should be 32 bit.
6627
6628            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6629            pkg.applicationInfo.secondaryCpuAbi = null;
6630        } else if (has32BitLibs && has64BitLibs) {
6631            // The application has both 64 and 32 bit bundled libraries. We check
6632            // here that the app declares multiArch support, and warn if it doesn't.
6633            //
6634            // We will be lenient here and record both ABIs. The primary will be the
6635            // ABI that's higher on the list, i.e, a device that's configured to prefer
6636            // 64 bit apps will see a 64 bit primary ABI,
6637
6638            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6639                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6640            }
6641
6642            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6643                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6644                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6645            } else {
6646                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6647                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6648            }
6649        } else {
6650            pkg.applicationInfo.primaryCpuAbi = null;
6651            pkg.applicationInfo.secondaryCpuAbi = null;
6652        }
6653    }
6654
6655    private void killApplication(String pkgName, int appId, String reason) {
6656        // Request the ActivityManager to kill the process(only for existing packages)
6657        // so that we do not end up in a confused state while the user is still using the older
6658        // version of the application while the new one gets installed.
6659        IActivityManager am = ActivityManagerNative.getDefault();
6660        if (am != null) {
6661            try {
6662                am.killApplicationWithAppId(pkgName, appId, reason);
6663            } catch (RemoteException e) {
6664            }
6665        }
6666    }
6667
6668    void removePackageLI(PackageSetting ps, boolean chatty) {
6669        if (DEBUG_INSTALL) {
6670            if (chatty)
6671                Log.d(TAG, "Removing package " + ps.name);
6672        }
6673
6674        // writer
6675        synchronized (mPackages) {
6676            mPackages.remove(ps.name);
6677            final PackageParser.Package pkg = ps.pkg;
6678            if (pkg != null) {
6679                cleanPackageDataStructuresLILPw(pkg, chatty);
6680            }
6681        }
6682    }
6683
6684    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6685        if (DEBUG_INSTALL) {
6686            if (chatty)
6687                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6688        }
6689
6690        // writer
6691        synchronized (mPackages) {
6692            mPackages.remove(pkg.applicationInfo.packageName);
6693            cleanPackageDataStructuresLILPw(pkg, chatty);
6694        }
6695    }
6696
6697    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6698        int N = pkg.providers.size();
6699        StringBuilder r = null;
6700        int i;
6701        for (i=0; i<N; i++) {
6702            PackageParser.Provider p = pkg.providers.get(i);
6703            mProviders.removeProvider(p);
6704            if (p.info.authority == null) {
6705
6706                /* There was another ContentProvider with this authority when
6707                 * this app was installed so this authority is null,
6708                 * Ignore it as we don't have to unregister the provider.
6709                 */
6710                continue;
6711            }
6712            String names[] = p.info.authority.split(";");
6713            for (int j = 0; j < names.length; j++) {
6714                if (mProvidersByAuthority.get(names[j]) == p) {
6715                    mProvidersByAuthority.remove(names[j]);
6716                    if (DEBUG_REMOVE) {
6717                        if (chatty)
6718                            Log.d(TAG, "Unregistered content provider: " + names[j]
6719                                    + ", className = " + p.info.name + ", isSyncable = "
6720                                    + p.info.isSyncable);
6721                    }
6722                }
6723            }
6724            if (DEBUG_REMOVE && chatty) {
6725                if (r == null) {
6726                    r = new StringBuilder(256);
6727                } else {
6728                    r.append(' ');
6729                }
6730                r.append(p.info.name);
6731            }
6732        }
6733        if (r != null) {
6734            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6735        }
6736
6737        N = pkg.services.size();
6738        r = null;
6739        for (i=0; i<N; i++) {
6740            PackageParser.Service s = pkg.services.get(i);
6741            mServices.removeService(s);
6742            if (chatty) {
6743                if (r == null) {
6744                    r = new StringBuilder(256);
6745                } else {
6746                    r.append(' ');
6747                }
6748                r.append(s.info.name);
6749            }
6750        }
6751        if (r != null) {
6752            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6753        }
6754
6755        N = pkg.receivers.size();
6756        r = null;
6757        for (i=0; i<N; i++) {
6758            PackageParser.Activity a = pkg.receivers.get(i);
6759            mReceivers.removeActivity(a, "receiver");
6760            if (DEBUG_REMOVE && chatty) {
6761                if (r == null) {
6762                    r = new StringBuilder(256);
6763                } else {
6764                    r.append(' ');
6765                }
6766                r.append(a.info.name);
6767            }
6768        }
6769        if (r != null) {
6770            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6771        }
6772
6773        N = pkg.activities.size();
6774        r = null;
6775        for (i=0; i<N; i++) {
6776            PackageParser.Activity a = pkg.activities.get(i);
6777            mActivities.removeActivity(a, "activity");
6778            if (DEBUG_REMOVE && chatty) {
6779                if (r == null) {
6780                    r = new StringBuilder(256);
6781                } else {
6782                    r.append(' ');
6783                }
6784                r.append(a.info.name);
6785            }
6786        }
6787        if (r != null) {
6788            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6789        }
6790
6791        N = pkg.permissions.size();
6792        r = null;
6793        for (i=0; i<N; i++) {
6794            PackageParser.Permission p = pkg.permissions.get(i);
6795            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6796            if (bp == null) {
6797                bp = mSettings.mPermissionTrees.get(p.info.name);
6798            }
6799            if (bp != null && bp.perm == p) {
6800                bp.perm = null;
6801                if (DEBUG_REMOVE && chatty) {
6802                    if (r == null) {
6803                        r = new StringBuilder(256);
6804                    } else {
6805                        r.append(' ');
6806                    }
6807                    r.append(p.info.name);
6808                }
6809            }
6810            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6811                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6812                if (appOpPerms != null) {
6813                    appOpPerms.remove(pkg.packageName);
6814                }
6815            }
6816        }
6817        if (r != null) {
6818            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6819        }
6820
6821        N = pkg.requestedPermissions.size();
6822        r = null;
6823        for (i=0; i<N; i++) {
6824            String perm = pkg.requestedPermissions.get(i);
6825            BasePermission bp = mSettings.mPermissions.get(perm);
6826            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6827                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6828                if (appOpPerms != null) {
6829                    appOpPerms.remove(pkg.packageName);
6830                    if (appOpPerms.isEmpty()) {
6831                        mAppOpPermissionPackages.remove(perm);
6832                    }
6833                }
6834            }
6835        }
6836        if (r != null) {
6837            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6838        }
6839
6840        N = pkg.instrumentation.size();
6841        r = null;
6842        for (i=0; i<N; i++) {
6843            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6844            mInstrumentation.remove(a.getComponentName());
6845            if (DEBUG_REMOVE && chatty) {
6846                if (r == null) {
6847                    r = new StringBuilder(256);
6848                } else {
6849                    r.append(' ');
6850                }
6851                r.append(a.info.name);
6852            }
6853        }
6854        if (r != null) {
6855            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6856        }
6857
6858        r = null;
6859        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6860            // Only system apps can hold shared libraries.
6861            if (pkg.libraryNames != null) {
6862                for (i=0; i<pkg.libraryNames.size(); i++) {
6863                    String name = pkg.libraryNames.get(i);
6864                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6865                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6866                        mSharedLibraries.remove(name);
6867                        if (DEBUG_REMOVE && chatty) {
6868                            if (r == null) {
6869                                r = new StringBuilder(256);
6870                            } else {
6871                                r.append(' ');
6872                            }
6873                            r.append(name);
6874                        }
6875                    }
6876                }
6877            }
6878        }
6879        if (r != null) {
6880            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6881        }
6882    }
6883
6884    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6885        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6886            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6887                return true;
6888            }
6889        }
6890        return false;
6891    }
6892
6893    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6894    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6895    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6896
6897    private void updatePermissionsLPw(String changingPkg,
6898            PackageParser.Package pkgInfo, int flags) {
6899        // Make sure there are no dangling permission trees.
6900        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6901        while (it.hasNext()) {
6902            final BasePermission bp = it.next();
6903            if (bp.packageSetting == null) {
6904                // We may not yet have parsed the package, so just see if
6905                // we still know about its settings.
6906                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6907            }
6908            if (bp.packageSetting == null) {
6909                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6910                        + " from package " + bp.sourcePackage);
6911                it.remove();
6912            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6913                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6914                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6915                            + " from package " + bp.sourcePackage);
6916                    flags |= UPDATE_PERMISSIONS_ALL;
6917                    it.remove();
6918                }
6919            }
6920        }
6921
6922        // Make sure all dynamic permissions have been assigned to a package,
6923        // and make sure there are no dangling permissions.
6924        it = mSettings.mPermissions.values().iterator();
6925        while (it.hasNext()) {
6926            final BasePermission bp = it.next();
6927            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6928                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6929                        + bp.name + " pkg=" + bp.sourcePackage
6930                        + " info=" + bp.pendingInfo);
6931                if (bp.packageSetting == null && bp.pendingInfo != null) {
6932                    final BasePermission tree = findPermissionTreeLP(bp.name);
6933                    if (tree != null && tree.perm != null) {
6934                        bp.packageSetting = tree.packageSetting;
6935                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6936                                new PermissionInfo(bp.pendingInfo));
6937                        bp.perm.info.packageName = tree.perm.info.packageName;
6938                        bp.perm.info.name = bp.name;
6939                        bp.uid = tree.uid;
6940                    }
6941                }
6942            }
6943            if (bp.packageSetting == null) {
6944                // We may not yet have parsed the package, so just see if
6945                // we still know about its settings.
6946                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6947            }
6948            if (bp.packageSetting == null) {
6949                Slog.w(TAG, "Removing dangling permission: " + bp.name
6950                        + " from package " + bp.sourcePackage);
6951                it.remove();
6952            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6953                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6954                    Slog.i(TAG, "Removing old permission: " + bp.name
6955                            + " from package " + bp.sourcePackage);
6956                    flags |= UPDATE_PERMISSIONS_ALL;
6957                    it.remove();
6958                }
6959            }
6960        }
6961
6962        // Now update the permissions for all packages, in particular
6963        // replace the granted permissions of the system packages.
6964        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6965            for (PackageParser.Package pkg : mPackages.values()) {
6966                if (pkg != pkgInfo) {
6967                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6968                            changingPkg);
6969                }
6970            }
6971        }
6972
6973        if (pkgInfo != null) {
6974            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6975        }
6976    }
6977
6978    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6979            String packageOfInterest) {
6980        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6981        if (ps == null) {
6982            return;
6983        }
6984        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6985        ArraySet<String> origPermissions = gp.grantedPermissions;
6986        boolean changedPermission = false;
6987
6988        if (replace) {
6989            ps.permissionsFixed = false;
6990            if (gp == ps) {
6991                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6992                gp.grantedPermissions.clear();
6993                gp.gids = mGlobalGids;
6994            }
6995        }
6996
6997        if (gp.gids == null) {
6998            gp.gids = mGlobalGids;
6999        }
7000
7001        final int N = pkg.requestedPermissions.size();
7002        for (int i=0; i<N; i++) {
7003            final String name = pkg.requestedPermissions.get(i);
7004            final boolean required = pkg.requestedPermissionsRequired.get(i);
7005            final BasePermission bp = mSettings.mPermissions.get(name);
7006            if (DEBUG_INSTALL) {
7007                if (gp != ps) {
7008                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7009                }
7010            }
7011
7012            if (bp == null || bp.packageSetting == null) {
7013                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7014                    Slog.w(TAG, "Unknown permission " + name
7015                            + " in package " + pkg.packageName);
7016                }
7017                continue;
7018            }
7019
7020            final String perm = bp.name;
7021            boolean allowed;
7022            boolean allowedSig = false;
7023            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7024                // Keep track of app op permissions.
7025                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7026                if (pkgs == null) {
7027                    pkgs = new ArraySet<>();
7028                    mAppOpPermissionPackages.put(bp.name, pkgs);
7029                }
7030                pkgs.add(pkg.packageName);
7031            }
7032            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7033            if (level == PermissionInfo.PROTECTION_NORMAL
7034                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7035                // We grant a normal or dangerous permission if any of the following
7036                // are true:
7037                // 1) The permission is required
7038                // 2) The permission is optional, but was granted in the past
7039                // 3) The permission is optional, but was requested by an
7040                //    app in /system (not /data)
7041                //
7042                // Otherwise, reject the permission.
7043                allowed = (required || origPermissions.contains(perm)
7044                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7045            } else if (bp.packageSetting == null) {
7046                // This permission is invalid; skip it.
7047                allowed = false;
7048            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7049                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7050                if (allowed) {
7051                    allowedSig = true;
7052                }
7053            } else {
7054                allowed = false;
7055            }
7056            if (DEBUG_INSTALL) {
7057                if (gp != ps) {
7058                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7059                }
7060            }
7061            if (allowed) {
7062                if (!isSystemApp(ps) && ps.permissionsFixed) {
7063                    // If this is an existing, non-system package, then
7064                    // we can't add any new permissions to it.
7065                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7066                        // Except...  if this is a permission that was added
7067                        // to the platform (note: need to only do this when
7068                        // updating the platform).
7069                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7070                    }
7071                }
7072                if (allowed) {
7073                    if (!gp.grantedPermissions.contains(perm)) {
7074                        changedPermission = true;
7075                        gp.grantedPermissions.add(perm);
7076                        gp.gids = appendInts(gp.gids, bp.gids);
7077                    } else if (!ps.haveGids) {
7078                        gp.gids = appendInts(gp.gids, bp.gids);
7079                    }
7080                } else {
7081                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7082                        Slog.w(TAG, "Not granting permission " + perm
7083                                + " to package " + pkg.packageName
7084                                + " because it was previously installed without");
7085                    }
7086                }
7087            } else {
7088                if (gp.grantedPermissions.remove(perm)) {
7089                    changedPermission = true;
7090                    gp.gids = removeInts(gp.gids, bp.gids);
7091                    Slog.i(TAG, "Un-granting permission " + perm
7092                            + " from package " + pkg.packageName
7093                            + " (protectionLevel=" + bp.protectionLevel
7094                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7095                            + ")");
7096                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7097                    // Don't print warning for app op permissions, since it is fine for them
7098                    // not to be granted, there is a UI for the user to decide.
7099                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7100                        Slog.w(TAG, "Not granting permission " + perm
7101                                + " to package " + pkg.packageName
7102                                + " (protectionLevel=" + bp.protectionLevel
7103                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7104                                + ")");
7105                    }
7106                }
7107            }
7108        }
7109
7110        if ((changedPermission || replace) && !ps.permissionsFixed &&
7111                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7112            // This is the first that we have heard about this package, so the
7113            // permissions we have now selected are fixed until explicitly
7114            // changed.
7115            ps.permissionsFixed = true;
7116        }
7117        ps.haveGids = true;
7118    }
7119
7120    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7121        boolean allowed = false;
7122        final int NP = PackageParser.NEW_PERMISSIONS.length;
7123        for (int ip=0; ip<NP; ip++) {
7124            final PackageParser.NewPermissionInfo npi
7125                    = PackageParser.NEW_PERMISSIONS[ip];
7126            if (npi.name.equals(perm)
7127                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7128                allowed = true;
7129                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7130                        + pkg.packageName);
7131                break;
7132            }
7133        }
7134        return allowed;
7135    }
7136
7137    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7138                                          BasePermission bp, ArraySet<String> origPermissions) {
7139        boolean allowed;
7140        allowed = (compareSignatures(
7141                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7142                        == PackageManager.SIGNATURE_MATCH)
7143                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7144                        == PackageManager.SIGNATURE_MATCH);
7145        if (!allowed && (bp.protectionLevel
7146                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7147            if (isSystemApp(pkg)) {
7148                // For updated system applications, a system permission
7149                // is granted only if it had been defined by the original application.
7150                if (isUpdatedSystemApp(pkg)) {
7151                    final PackageSetting sysPs = mSettings
7152                            .getDisabledSystemPkgLPr(pkg.packageName);
7153                    final GrantedPermissions origGp = sysPs.sharedUser != null
7154                            ? sysPs.sharedUser : sysPs;
7155
7156                    if (origGp.grantedPermissions.contains(perm)) {
7157                        // If the original was granted this permission, we take
7158                        // that grant decision as read and propagate it to the
7159                        // update.
7160                        allowed = true;
7161                    } else {
7162                        // The system apk may have been updated with an older
7163                        // version of the one on the data partition, but which
7164                        // granted a new system permission that it didn't have
7165                        // before.  In this case we do want to allow the app to
7166                        // now get the new permission if the ancestral apk is
7167                        // privileged to get it.
7168                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7169                            for (int j=0;
7170                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7171                                if (perm.equals(
7172                                        sysPs.pkg.requestedPermissions.get(j))) {
7173                                    allowed = true;
7174                                    break;
7175                                }
7176                            }
7177                        }
7178                    }
7179                } else {
7180                    allowed = isPrivilegedApp(pkg);
7181                }
7182            }
7183        }
7184        if (!allowed && (bp.protectionLevel
7185                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7186            // For development permissions, a development permission
7187            // is granted only if it was already granted.
7188            allowed = origPermissions.contains(perm);
7189        }
7190        return allowed;
7191    }
7192
7193    final class ActivityIntentResolver
7194            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7195        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7196                boolean defaultOnly, int userId) {
7197            if (!sUserManager.exists(userId)) return null;
7198            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7199            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7200        }
7201
7202        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7203                int userId) {
7204            if (!sUserManager.exists(userId)) return null;
7205            mFlags = flags;
7206            return super.queryIntent(intent, resolvedType,
7207                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7208        }
7209
7210        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7211                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7212            if (!sUserManager.exists(userId)) return null;
7213            if (packageActivities == null) {
7214                return null;
7215            }
7216            mFlags = flags;
7217            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7218            final int N = packageActivities.size();
7219            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7220                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7221
7222            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7223            for (int i = 0; i < N; ++i) {
7224                intentFilters = packageActivities.get(i).intents;
7225                if (intentFilters != null && intentFilters.size() > 0) {
7226                    PackageParser.ActivityIntentInfo[] array =
7227                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7228                    intentFilters.toArray(array);
7229                    listCut.add(array);
7230                }
7231            }
7232            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7233        }
7234
7235        public final void addActivity(PackageParser.Activity a, String type) {
7236            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7237            mActivities.put(a.getComponentName(), a);
7238            if (DEBUG_SHOW_INFO)
7239                Log.v(
7240                TAG, "  " + type + " " +
7241                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7242            if (DEBUG_SHOW_INFO)
7243                Log.v(TAG, "    Class=" + a.info.name);
7244            final int NI = a.intents.size();
7245            for (int j=0; j<NI; j++) {
7246                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7247                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7248                    intent.setPriority(0);
7249                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7250                            + a.className + " with priority > 0, forcing to 0");
7251                }
7252                if (DEBUG_SHOW_INFO) {
7253                    Log.v(TAG, "    IntentFilter:");
7254                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7255                }
7256                if (!intent.debugCheck()) {
7257                    Log.w(TAG, "==> For Activity " + a.info.name);
7258                }
7259                addFilter(intent);
7260            }
7261        }
7262
7263        public final void removeActivity(PackageParser.Activity a, String type) {
7264            mActivities.remove(a.getComponentName());
7265            if (DEBUG_SHOW_INFO) {
7266                Log.v(TAG, "  " + type + " "
7267                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7268                                : a.info.name) + ":");
7269                Log.v(TAG, "    Class=" + a.info.name);
7270            }
7271            final int NI = a.intents.size();
7272            for (int j=0; j<NI; j++) {
7273                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7274                if (DEBUG_SHOW_INFO) {
7275                    Log.v(TAG, "    IntentFilter:");
7276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7277                }
7278                removeFilter(intent);
7279            }
7280        }
7281
7282        @Override
7283        protected boolean allowFilterResult(
7284                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7285            ActivityInfo filterAi = filter.activity.info;
7286            for (int i=dest.size()-1; i>=0; i--) {
7287                ActivityInfo destAi = dest.get(i).activityInfo;
7288                if (destAi.name == filterAi.name
7289                        && destAi.packageName == filterAi.packageName) {
7290                    return false;
7291                }
7292            }
7293            return true;
7294        }
7295
7296        @Override
7297        protected ActivityIntentInfo[] newArray(int size) {
7298            return new ActivityIntentInfo[size];
7299        }
7300
7301        @Override
7302        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7303            if (!sUserManager.exists(userId)) return true;
7304            PackageParser.Package p = filter.activity.owner;
7305            if (p != null) {
7306                PackageSetting ps = (PackageSetting)p.mExtras;
7307                if (ps != null) {
7308                    // System apps are never considered stopped for purposes of
7309                    // filtering, because there may be no way for the user to
7310                    // actually re-launch them.
7311                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7312                            && ps.getStopped(userId);
7313                }
7314            }
7315            return false;
7316        }
7317
7318        @Override
7319        protected boolean isPackageForFilter(String packageName,
7320                PackageParser.ActivityIntentInfo info) {
7321            return packageName.equals(info.activity.owner.packageName);
7322        }
7323
7324        @Override
7325        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7326                int match, int userId) {
7327            if (!sUserManager.exists(userId)) return null;
7328            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7329                return null;
7330            }
7331            final PackageParser.Activity activity = info.activity;
7332            if (mSafeMode && (activity.info.applicationInfo.flags
7333                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7334                return null;
7335            }
7336            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7337            if (ps == null) {
7338                return null;
7339            }
7340            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7341                    ps.readUserState(userId), userId);
7342            if (ai == null) {
7343                return null;
7344            }
7345            final ResolveInfo res = new ResolveInfo();
7346            res.activityInfo = ai;
7347            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7348                res.filter = info;
7349            }
7350            res.priority = info.getPriority();
7351            res.preferredOrder = activity.owner.mPreferredOrder;
7352            //System.out.println("Result: " + res.activityInfo.className +
7353            //                   " = " + res.priority);
7354            res.match = match;
7355            res.isDefault = info.hasDefault;
7356            res.labelRes = info.labelRes;
7357            res.nonLocalizedLabel = info.nonLocalizedLabel;
7358            if (userNeedsBadging(userId)) {
7359                res.noResourceId = true;
7360            } else {
7361                res.icon = info.icon;
7362            }
7363            res.system = isSystemApp(res.activityInfo.applicationInfo);
7364            return res;
7365        }
7366
7367        @Override
7368        protected void sortResults(List<ResolveInfo> results) {
7369            Collections.sort(results, mResolvePrioritySorter);
7370        }
7371
7372        @Override
7373        protected void dumpFilter(PrintWriter out, String prefix,
7374                PackageParser.ActivityIntentInfo filter) {
7375            out.print(prefix); out.print(
7376                    Integer.toHexString(System.identityHashCode(filter.activity)));
7377                    out.print(' ');
7378                    filter.activity.printComponentShortName(out);
7379                    out.print(" filter ");
7380                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7381        }
7382
7383        @Override
7384        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7385            return filter.activity;
7386        }
7387
7388        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7389            PackageParser.Activity activity = (PackageParser.Activity)label;
7390            out.print(prefix); out.print(
7391                    Integer.toHexString(System.identityHashCode(activity)));
7392                    out.print(' ');
7393                    activity.printComponentShortName(out);
7394            if (count > 1) {
7395                out.print(" ("); out.print(count); out.print(" filters)");
7396            }
7397            out.println();
7398        }
7399
7400//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7401//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7402//            final List<ResolveInfo> retList = Lists.newArrayList();
7403//            while (i.hasNext()) {
7404//                final ResolveInfo resolveInfo = i.next();
7405//                if (isEnabledLP(resolveInfo.activityInfo)) {
7406//                    retList.add(resolveInfo);
7407//                }
7408//            }
7409//            return retList;
7410//        }
7411
7412        // Keys are String (activity class name), values are Activity.
7413        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7414                = new ArrayMap<ComponentName, PackageParser.Activity>();
7415        private int mFlags;
7416    }
7417
7418    private final class ServiceIntentResolver
7419            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7420        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7421                boolean defaultOnly, int userId) {
7422            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7423            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7424        }
7425
7426        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7427                int userId) {
7428            if (!sUserManager.exists(userId)) return null;
7429            mFlags = flags;
7430            return super.queryIntent(intent, resolvedType,
7431                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7432        }
7433
7434        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7435                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7436            if (!sUserManager.exists(userId)) return null;
7437            if (packageServices == null) {
7438                return null;
7439            }
7440            mFlags = flags;
7441            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7442            final int N = packageServices.size();
7443            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7444                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7445
7446            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7447            for (int i = 0; i < N; ++i) {
7448                intentFilters = packageServices.get(i).intents;
7449                if (intentFilters != null && intentFilters.size() > 0) {
7450                    PackageParser.ServiceIntentInfo[] array =
7451                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7452                    intentFilters.toArray(array);
7453                    listCut.add(array);
7454                }
7455            }
7456            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7457        }
7458
7459        public final void addService(PackageParser.Service s) {
7460            mServices.put(s.getComponentName(), s);
7461            if (DEBUG_SHOW_INFO) {
7462                Log.v(TAG, "  "
7463                        + (s.info.nonLocalizedLabel != null
7464                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7465                Log.v(TAG, "    Class=" + s.info.name);
7466            }
7467            final int NI = s.intents.size();
7468            int j;
7469            for (j=0; j<NI; j++) {
7470                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7471                if (DEBUG_SHOW_INFO) {
7472                    Log.v(TAG, "    IntentFilter:");
7473                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7474                }
7475                if (!intent.debugCheck()) {
7476                    Log.w(TAG, "==> For Service " + s.info.name);
7477                }
7478                addFilter(intent);
7479            }
7480        }
7481
7482        public final void removeService(PackageParser.Service s) {
7483            mServices.remove(s.getComponentName());
7484            if (DEBUG_SHOW_INFO) {
7485                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7486                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7487                Log.v(TAG, "    Class=" + s.info.name);
7488            }
7489            final int NI = s.intents.size();
7490            int j;
7491            for (j=0; j<NI; j++) {
7492                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7493                if (DEBUG_SHOW_INFO) {
7494                    Log.v(TAG, "    IntentFilter:");
7495                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7496                }
7497                removeFilter(intent);
7498            }
7499        }
7500
7501        @Override
7502        protected boolean allowFilterResult(
7503                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7504            ServiceInfo filterSi = filter.service.info;
7505            for (int i=dest.size()-1; i>=0; i--) {
7506                ServiceInfo destAi = dest.get(i).serviceInfo;
7507                if (destAi.name == filterSi.name
7508                        && destAi.packageName == filterSi.packageName) {
7509                    return false;
7510                }
7511            }
7512            return true;
7513        }
7514
7515        @Override
7516        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7517            return new PackageParser.ServiceIntentInfo[size];
7518        }
7519
7520        @Override
7521        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7522            if (!sUserManager.exists(userId)) return true;
7523            PackageParser.Package p = filter.service.owner;
7524            if (p != null) {
7525                PackageSetting ps = (PackageSetting)p.mExtras;
7526                if (ps != null) {
7527                    // System apps are never considered stopped for purposes of
7528                    // filtering, because there may be no way for the user to
7529                    // actually re-launch them.
7530                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7531                            && ps.getStopped(userId);
7532                }
7533            }
7534            return false;
7535        }
7536
7537        @Override
7538        protected boolean isPackageForFilter(String packageName,
7539                PackageParser.ServiceIntentInfo info) {
7540            return packageName.equals(info.service.owner.packageName);
7541        }
7542
7543        @Override
7544        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7545                int match, int userId) {
7546            if (!sUserManager.exists(userId)) return null;
7547            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7548            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7549                return null;
7550            }
7551            final PackageParser.Service service = info.service;
7552            if (mSafeMode && (service.info.applicationInfo.flags
7553                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7554                return null;
7555            }
7556            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7557            if (ps == null) {
7558                return null;
7559            }
7560            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7561                    ps.readUserState(userId), userId);
7562            if (si == null) {
7563                return null;
7564            }
7565            final ResolveInfo res = new ResolveInfo();
7566            res.serviceInfo = si;
7567            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7568                res.filter = filter;
7569            }
7570            res.priority = info.getPriority();
7571            res.preferredOrder = service.owner.mPreferredOrder;
7572            //System.out.println("Result: " + res.activityInfo.className +
7573            //                   " = " + res.priority);
7574            res.match = match;
7575            res.isDefault = info.hasDefault;
7576            res.labelRes = info.labelRes;
7577            res.nonLocalizedLabel = info.nonLocalizedLabel;
7578            res.icon = info.icon;
7579            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7580            return res;
7581        }
7582
7583        @Override
7584        protected void sortResults(List<ResolveInfo> results) {
7585            Collections.sort(results, mResolvePrioritySorter);
7586        }
7587
7588        @Override
7589        protected void dumpFilter(PrintWriter out, String prefix,
7590                PackageParser.ServiceIntentInfo filter) {
7591            out.print(prefix); out.print(
7592                    Integer.toHexString(System.identityHashCode(filter.service)));
7593                    out.print(' ');
7594                    filter.service.printComponentShortName(out);
7595                    out.print(" filter ");
7596                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7597        }
7598
7599        @Override
7600        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7601            return filter.service;
7602        }
7603
7604        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7605            PackageParser.Service service = (PackageParser.Service)label;
7606            out.print(prefix); out.print(
7607                    Integer.toHexString(System.identityHashCode(service)));
7608                    out.print(' ');
7609                    service.printComponentShortName(out);
7610            if (count > 1) {
7611                out.print(" ("); out.print(count); out.print(" filters)");
7612            }
7613            out.println();
7614        }
7615
7616//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7617//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7618//            final List<ResolveInfo> retList = Lists.newArrayList();
7619//            while (i.hasNext()) {
7620//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7621//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7622//                    retList.add(resolveInfo);
7623//                }
7624//            }
7625//            return retList;
7626//        }
7627
7628        // Keys are String (activity class name), values are Activity.
7629        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7630                = new ArrayMap<ComponentName, PackageParser.Service>();
7631        private int mFlags;
7632    };
7633
7634    private final class ProviderIntentResolver
7635            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7636        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7637                boolean defaultOnly, int userId) {
7638            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7639            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7640        }
7641
7642        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7643                int userId) {
7644            if (!sUserManager.exists(userId))
7645                return null;
7646            mFlags = flags;
7647            return super.queryIntent(intent, resolvedType,
7648                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7649        }
7650
7651        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7652                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7653            if (!sUserManager.exists(userId))
7654                return null;
7655            if (packageProviders == null) {
7656                return null;
7657            }
7658            mFlags = flags;
7659            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7660            final int N = packageProviders.size();
7661            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7662                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7663
7664            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7665            for (int i = 0; i < N; ++i) {
7666                intentFilters = packageProviders.get(i).intents;
7667                if (intentFilters != null && intentFilters.size() > 0) {
7668                    PackageParser.ProviderIntentInfo[] array =
7669                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7670                    intentFilters.toArray(array);
7671                    listCut.add(array);
7672                }
7673            }
7674            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7675        }
7676
7677        public final void addProvider(PackageParser.Provider p) {
7678            if (mProviders.containsKey(p.getComponentName())) {
7679                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7680                return;
7681            }
7682
7683            mProviders.put(p.getComponentName(), p);
7684            if (DEBUG_SHOW_INFO) {
7685                Log.v(TAG, "  "
7686                        + (p.info.nonLocalizedLabel != null
7687                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7688                Log.v(TAG, "    Class=" + p.info.name);
7689            }
7690            final int NI = p.intents.size();
7691            int j;
7692            for (j = 0; j < NI; j++) {
7693                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7694                if (DEBUG_SHOW_INFO) {
7695                    Log.v(TAG, "    IntentFilter:");
7696                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7697                }
7698                if (!intent.debugCheck()) {
7699                    Log.w(TAG, "==> For Provider " + p.info.name);
7700                }
7701                addFilter(intent);
7702            }
7703        }
7704
7705        public final void removeProvider(PackageParser.Provider p) {
7706            mProviders.remove(p.getComponentName());
7707            if (DEBUG_SHOW_INFO) {
7708                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7709                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7710                Log.v(TAG, "    Class=" + p.info.name);
7711            }
7712            final int NI = p.intents.size();
7713            int j;
7714            for (j = 0; j < NI; j++) {
7715                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7716                if (DEBUG_SHOW_INFO) {
7717                    Log.v(TAG, "    IntentFilter:");
7718                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7719                }
7720                removeFilter(intent);
7721            }
7722        }
7723
7724        @Override
7725        protected boolean allowFilterResult(
7726                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7727            ProviderInfo filterPi = filter.provider.info;
7728            for (int i = dest.size() - 1; i >= 0; i--) {
7729                ProviderInfo destPi = dest.get(i).providerInfo;
7730                if (destPi.name == filterPi.name
7731                        && destPi.packageName == filterPi.packageName) {
7732                    return false;
7733                }
7734            }
7735            return true;
7736        }
7737
7738        @Override
7739        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7740            return new PackageParser.ProviderIntentInfo[size];
7741        }
7742
7743        @Override
7744        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7745            if (!sUserManager.exists(userId))
7746                return true;
7747            PackageParser.Package p = filter.provider.owner;
7748            if (p != null) {
7749                PackageSetting ps = (PackageSetting) p.mExtras;
7750                if (ps != null) {
7751                    // System apps are never considered stopped for purposes of
7752                    // filtering, because there may be no way for the user to
7753                    // actually re-launch them.
7754                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7755                            && ps.getStopped(userId);
7756                }
7757            }
7758            return false;
7759        }
7760
7761        @Override
7762        protected boolean isPackageForFilter(String packageName,
7763                PackageParser.ProviderIntentInfo info) {
7764            return packageName.equals(info.provider.owner.packageName);
7765        }
7766
7767        @Override
7768        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7769                int match, int userId) {
7770            if (!sUserManager.exists(userId))
7771                return null;
7772            final PackageParser.ProviderIntentInfo info = filter;
7773            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7774                return null;
7775            }
7776            final PackageParser.Provider provider = info.provider;
7777            if (mSafeMode && (provider.info.applicationInfo.flags
7778                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7779                return null;
7780            }
7781            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7782            if (ps == null) {
7783                return null;
7784            }
7785            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7786                    ps.readUserState(userId), userId);
7787            if (pi == null) {
7788                return null;
7789            }
7790            final ResolveInfo res = new ResolveInfo();
7791            res.providerInfo = pi;
7792            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7793                res.filter = filter;
7794            }
7795            res.priority = info.getPriority();
7796            res.preferredOrder = provider.owner.mPreferredOrder;
7797            res.match = match;
7798            res.isDefault = info.hasDefault;
7799            res.labelRes = info.labelRes;
7800            res.nonLocalizedLabel = info.nonLocalizedLabel;
7801            res.icon = info.icon;
7802            res.system = isSystemApp(res.providerInfo.applicationInfo);
7803            return res;
7804        }
7805
7806        @Override
7807        protected void sortResults(List<ResolveInfo> results) {
7808            Collections.sort(results, mResolvePrioritySorter);
7809        }
7810
7811        @Override
7812        protected void dumpFilter(PrintWriter out, String prefix,
7813                PackageParser.ProviderIntentInfo filter) {
7814            out.print(prefix);
7815            out.print(
7816                    Integer.toHexString(System.identityHashCode(filter.provider)));
7817            out.print(' ');
7818            filter.provider.printComponentShortName(out);
7819            out.print(" filter ");
7820            out.println(Integer.toHexString(System.identityHashCode(filter)));
7821        }
7822
7823        @Override
7824        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7825            return filter.provider;
7826        }
7827
7828        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7829            PackageParser.Provider provider = (PackageParser.Provider)label;
7830            out.print(prefix); out.print(
7831                    Integer.toHexString(System.identityHashCode(provider)));
7832                    out.print(' ');
7833                    provider.printComponentShortName(out);
7834            if (count > 1) {
7835                out.print(" ("); out.print(count); out.print(" filters)");
7836            }
7837            out.println();
7838        }
7839
7840        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7841                = new ArrayMap<ComponentName, PackageParser.Provider>();
7842        private int mFlags;
7843    };
7844
7845    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7846            new Comparator<ResolveInfo>() {
7847        public int compare(ResolveInfo r1, ResolveInfo r2) {
7848            int v1 = r1.priority;
7849            int v2 = r2.priority;
7850            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7851            if (v1 != v2) {
7852                return (v1 > v2) ? -1 : 1;
7853            }
7854            v1 = r1.preferredOrder;
7855            v2 = r2.preferredOrder;
7856            if (v1 != v2) {
7857                return (v1 > v2) ? -1 : 1;
7858            }
7859            if (r1.isDefault != r2.isDefault) {
7860                return r1.isDefault ? -1 : 1;
7861            }
7862            v1 = r1.match;
7863            v2 = r2.match;
7864            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7865            if (v1 != v2) {
7866                return (v1 > v2) ? -1 : 1;
7867            }
7868            if (r1.system != r2.system) {
7869                return r1.system ? -1 : 1;
7870            }
7871            return 0;
7872        }
7873    };
7874
7875    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7876            new Comparator<ProviderInfo>() {
7877        public int compare(ProviderInfo p1, ProviderInfo p2) {
7878            final int v1 = p1.initOrder;
7879            final int v2 = p2.initOrder;
7880            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7881        }
7882    };
7883
7884    static final void sendPackageBroadcast(String action, String pkg,
7885            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7886            int[] userIds) {
7887        IActivityManager am = ActivityManagerNative.getDefault();
7888        if (am != null) {
7889            try {
7890                if (userIds == null) {
7891                    userIds = am.getRunningUserIds();
7892                }
7893                for (int id : userIds) {
7894                    final Intent intent = new Intent(action,
7895                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7896                    if (extras != null) {
7897                        intent.putExtras(extras);
7898                    }
7899                    if (targetPkg != null) {
7900                        intent.setPackage(targetPkg);
7901                    }
7902                    // Modify the UID when posting to other users
7903                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7904                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7905                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7906                        intent.putExtra(Intent.EXTRA_UID, uid);
7907                    }
7908                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7909                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7910                    if (DEBUG_BROADCASTS) {
7911                        RuntimeException here = new RuntimeException("here");
7912                        here.fillInStackTrace();
7913                        Slog.d(TAG, "Sending to user " + id + ": "
7914                                + intent.toShortString(false, true, false, false)
7915                                + " " + intent.getExtras(), here);
7916                    }
7917                    am.broadcastIntent(null, intent, null, finishedReceiver,
7918                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7919                            finishedReceiver != null, false, id);
7920                }
7921            } catch (RemoteException ex) {
7922            }
7923        }
7924    }
7925
7926    /**
7927     * Check if the external storage media is available. This is true if there
7928     * is a mounted external storage medium or if the external storage is
7929     * emulated.
7930     */
7931    private boolean isExternalMediaAvailable() {
7932        return mMediaMounted || Environment.isExternalStorageEmulated();
7933    }
7934
7935    @Override
7936    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7937        // writer
7938        synchronized (mPackages) {
7939            if (!isExternalMediaAvailable()) {
7940                // If the external storage is no longer mounted at this point,
7941                // the caller may not have been able to delete all of this
7942                // packages files and can not delete any more.  Bail.
7943                return null;
7944            }
7945            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7946            if (lastPackage != null) {
7947                pkgs.remove(lastPackage);
7948            }
7949            if (pkgs.size() > 0) {
7950                return pkgs.get(0);
7951            }
7952        }
7953        return null;
7954    }
7955
7956    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7957        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7958                userId, andCode ? 1 : 0, packageName);
7959        if (mSystemReady) {
7960            msg.sendToTarget();
7961        } else {
7962            if (mPostSystemReadyMessages == null) {
7963                mPostSystemReadyMessages = new ArrayList<>();
7964            }
7965            mPostSystemReadyMessages.add(msg);
7966        }
7967    }
7968
7969    void startCleaningPackages() {
7970        // reader
7971        synchronized (mPackages) {
7972            if (!isExternalMediaAvailable()) {
7973                return;
7974            }
7975            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7976                return;
7977            }
7978        }
7979        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7980        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7981        IActivityManager am = ActivityManagerNative.getDefault();
7982        if (am != null) {
7983            try {
7984                am.startService(null, intent, null, UserHandle.USER_OWNER);
7985            } catch (RemoteException e) {
7986            }
7987        }
7988    }
7989
7990    @Override
7991    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7992            int installFlags, String installerPackageName, VerificationParams verificationParams,
7993            String packageAbiOverride) {
7994        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7995                packageAbiOverride, UserHandle.getCallingUserId());
7996    }
7997
7998    @Override
7999    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8000            int installFlags, String installerPackageName, VerificationParams verificationParams,
8001            String packageAbiOverride, int userId) {
8002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8003
8004        final int callingUid = Binder.getCallingUid();
8005        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8006
8007        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8008            try {
8009                if (observer != null) {
8010                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8011                }
8012            } catch (RemoteException re) {
8013            }
8014            return;
8015        }
8016
8017        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8018            installFlags |= PackageManager.INSTALL_FROM_ADB;
8019
8020        } else {
8021            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8022            // about installerPackageName.
8023
8024            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8025            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8026        }
8027
8028        UserHandle user;
8029        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8030            user = UserHandle.ALL;
8031        } else {
8032            user = new UserHandle(userId);
8033        }
8034
8035        verificationParams.setInstallerUid(callingUid);
8036
8037        final File originFile = new File(originPath);
8038        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8039
8040        final Message msg = mHandler.obtainMessage(INIT_COPY);
8041        msg.obj = new InstallParams(origin, observer, installFlags,
8042                installerPackageName, verificationParams, user, packageAbiOverride);
8043        mHandler.sendMessage(msg);
8044    }
8045
8046    void installStage(String packageName, File stagedDir, String stagedCid,
8047            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8048            String installerPackageName, int installerUid, UserHandle user) {
8049        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8050                params.referrerUri, installerUid, null);
8051
8052        final OriginInfo origin;
8053        if (stagedDir != null) {
8054            origin = OriginInfo.fromStagedFile(stagedDir);
8055        } else {
8056            origin = OriginInfo.fromStagedContainer(stagedCid);
8057        }
8058
8059        final Message msg = mHandler.obtainMessage(INIT_COPY);
8060        msg.obj = new InstallParams(origin, observer, params.installFlags,
8061                installerPackageName, verifParams, user, params.abiOverride);
8062        mHandler.sendMessage(msg);
8063    }
8064
8065    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8066        Bundle extras = new Bundle(1);
8067        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8068
8069        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8070                packageName, extras, null, null, new int[] {userId});
8071        try {
8072            IActivityManager am = ActivityManagerNative.getDefault();
8073            final boolean isSystem =
8074                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8075            if (isSystem && am.isUserRunning(userId, false)) {
8076                // The just-installed/enabled app is bundled on the system, so presumed
8077                // to be able to run automatically without needing an explicit launch.
8078                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8079                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8080                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8081                        .setPackage(packageName);
8082                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8083                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8084            }
8085        } catch (RemoteException e) {
8086            // shouldn't happen
8087            Slog.w(TAG, "Unable to bootstrap installed package", e);
8088        }
8089    }
8090
8091    @Override
8092    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8093            int userId) {
8094        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8095        PackageSetting pkgSetting;
8096        final int uid = Binder.getCallingUid();
8097        enforceCrossUserPermission(uid, userId, true, true,
8098                "setApplicationHiddenSetting for user " + userId);
8099
8100        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8101            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8102            return false;
8103        }
8104
8105        long callingId = Binder.clearCallingIdentity();
8106        try {
8107            boolean sendAdded = false;
8108            boolean sendRemoved = false;
8109            // writer
8110            synchronized (mPackages) {
8111                pkgSetting = mSettings.mPackages.get(packageName);
8112                if (pkgSetting == null) {
8113                    return false;
8114                }
8115                if (pkgSetting.getHidden(userId) != hidden) {
8116                    pkgSetting.setHidden(hidden, userId);
8117                    mSettings.writePackageRestrictionsLPr(userId);
8118                    if (hidden) {
8119                        sendRemoved = true;
8120                    } else {
8121                        sendAdded = true;
8122                    }
8123                }
8124            }
8125            if (sendAdded) {
8126                sendPackageAddedForUser(packageName, pkgSetting, userId);
8127                return true;
8128            }
8129            if (sendRemoved) {
8130                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8131                        "hiding pkg");
8132                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8133            }
8134        } finally {
8135            Binder.restoreCallingIdentity(callingId);
8136        }
8137        return false;
8138    }
8139
8140    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8141            int userId) {
8142        final PackageRemovedInfo info = new PackageRemovedInfo();
8143        info.removedPackage = packageName;
8144        info.removedUsers = new int[] {userId};
8145        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8146        info.sendBroadcast(false, false, false);
8147    }
8148
8149    /**
8150     * Returns true if application is not found or there was an error. Otherwise it returns
8151     * the hidden state of the package for the given user.
8152     */
8153    @Override
8154    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8156        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8157                false, "getApplicationHidden for user " + userId);
8158        PackageSetting pkgSetting;
8159        long callingId = Binder.clearCallingIdentity();
8160        try {
8161            // writer
8162            synchronized (mPackages) {
8163                pkgSetting = mSettings.mPackages.get(packageName);
8164                if (pkgSetting == null) {
8165                    return true;
8166                }
8167                return pkgSetting.getHidden(userId);
8168            }
8169        } finally {
8170            Binder.restoreCallingIdentity(callingId);
8171        }
8172    }
8173
8174    /**
8175     * @hide
8176     */
8177    @Override
8178    public int installExistingPackageAsUser(String packageName, int userId) {
8179        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8180                null);
8181        PackageSetting pkgSetting;
8182        final int uid = Binder.getCallingUid();
8183        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8184                + userId);
8185        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8186            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8187        }
8188
8189        long callingId = Binder.clearCallingIdentity();
8190        try {
8191            boolean sendAdded = false;
8192            Bundle extras = new Bundle(1);
8193
8194            // writer
8195            synchronized (mPackages) {
8196                pkgSetting = mSettings.mPackages.get(packageName);
8197                if (pkgSetting == null) {
8198                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8199                }
8200                if (!pkgSetting.getInstalled(userId)) {
8201                    pkgSetting.setInstalled(true, userId);
8202                    pkgSetting.setHidden(false, userId);
8203                    mSettings.writePackageRestrictionsLPr(userId);
8204                    sendAdded = true;
8205                }
8206            }
8207
8208            if (sendAdded) {
8209                sendPackageAddedForUser(packageName, pkgSetting, userId);
8210            }
8211        } finally {
8212            Binder.restoreCallingIdentity(callingId);
8213        }
8214
8215        return PackageManager.INSTALL_SUCCEEDED;
8216    }
8217
8218    boolean isUserRestricted(int userId, String restrictionKey) {
8219        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8220        if (restrictions.getBoolean(restrictionKey, false)) {
8221            Log.w(TAG, "User is restricted: " + restrictionKey);
8222            return true;
8223        }
8224        return false;
8225    }
8226
8227    @Override
8228    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8229        mContext.enforceCallingOrSelfPermission(
8230                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8231                "Only package verification agents can verify applications");
8232
8233        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8234        final PackageVerificationResponse response = new PackageVerificationResponse(
8235                verificationCode, Binder.getCallingUid());
8236        msg.arg1 = id;
8237        msg.obj = response;
8238        mHandler.sendMessage(msg);
8239    }
8240
8241    @Override
8242    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8243            long millisecondsToDelay) {
8244        mContext.enforceCallingOrSelfPermission(
8245                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8246                "Only package verification agents can extend verification timeouts");
8247
8248        final PackageVerificationState state = mPendingVerification.get(id);
8249        final PackageVerificationResponse response = new PackageVerificationResponse(
8250                verificationCodeAtTimeout, Binder.getCallingUid());
8251
8252        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8253            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8254        }
8255        if (millisecondsToDelay < 0) {
8256            millisecondsToDelay = 0;
8257        }
8258        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8259                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8260            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8261        }
8262
8263        if ((state != null) && !state.timeoutExtended()) {
8264            state.extendTimeout();
8265
8266            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8267            msg.arg1 = id;
8268            msg.obj = response;
8269            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8270        }
8271    }
8272
8273    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8274            int verificationCode, UserHandle user) {
8275        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8276        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8277        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8278        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8279        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8280
8281        mContext.sendBroadcastAsUser(intent, user,
8282                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8283    }
8284
8285    private ComponentName matchComponentForVerifier(String packageName,
8286            List<ResolveInfo> receivers) {
8287        ActivityInfo targetReceiver = null;
8288
8289        final int NR = receivers.size();
8290        for (int i = 0; i < NR; i++) {
8291            final ResolveInfo info = receivers.get(i);
8292            if (info.activityInfo == null) {
8293                continue;
8294            }
8295
8296            if (packageName.equals(info.activityInfo.packageName)) {
8297                targetReceiver = info.activityInfo;
8298                break;
8299            }
8300        }
8301
8302        if (targetReceiver == null) {
8303            return null;
8304        }
8305
8306        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8307    }
8308
8309    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8310            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8311        if (pkgInfo.verifiers.length == 0) {
8312            return null;
8313        }
8314
8315        final int N = pkgInfo.verifiers.length;
8316        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8317        for (int i = 0; i < N; i++) {
8318            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8319
8320            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8321                    receivers);
8322            if (comp == null) {
8323                continue;
8324            }
8325
8326            final int verifierUid = getUidForVerifier(verifierInfo);
8327            if (verifierUid == -1) {
8328                continue;
8329            }
8330
8331            if (DEBUG_VERIFY) {
8332                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8333                        + " with the correct signature");
8334            }
8335            sufficientVerifiers.add(comp);
8336            verificationState.addSufficientVerifier(verifierUid);
8337        }
8338
8339        return sufficientVerifiers;
8340    }
8341
8342    private int getUidForVerifier(VerifierInfo verifierInfo) {
8343        synchronized (mPackages) {
8344            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8345            if (pkg == null) {
8346                return -1;
8347            } else if (pkg.mSignatures.length != 1) {
8348                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8349                        + " has more than one signature; ignoring");
8350                return -1;
8351            }
8352
8353            /*
8354             * If the public key of the package's signature does not match
8355             * our expected public key, then this is a different package and
8356             * we should skip.
8357             */
8358
8359            final byte[] expectedPublicKey;
8360            try {
8361                final Signature verifierSig = pkg.mSignatures[0];
8362                final PublicKey publicKey = verifierSig.getPublicKey();
8363                expectedPublicKey = publicKey.getEncoded();
8364            } catch (CertificateException e) {
8365                return -1;
8366            }
8367
8368            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8369
8370            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8371                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8372                        + " does not have the expected public key; ignoring");
8373                return -1;
8374            }
8375
8376            return pkg.applicationInfo.uid;
8377        }
8378    }
8379
8380    @Override
8381    public void finishPackageInstall(int token) {
8382        enforceSystemOrRoot("Only the system is allowed to finish installs");
8383
8384        if (DEBUG_INSTALL) {
8385            Slog.v(TAG, "BM finishing package install for " + token);
8386        }
8387
8388        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8389        mHandler.sendMessage(msg);
8390    }
8391
8392    /**
8393     * Get the verification agent timeout.
8394     *
8395     * @return verification timeout in milliseconds
8396     */
8397    private long getVerificationTimeout() {
8398        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8399                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8400                DEFAULT_VERIFICATION_TIMEOUT);
8401    }
8402
8403    /**
8404     * Get the default verification agent response code.
8405     *
8406     * @return default verification response code
8407     */
8408    private int getDefaultVerificationResponse() {
8409        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8410                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8411                DEFAULT_VERIFICATION_RESPONSE);
8412    }
8413
8414    /**
8415     * Check whether or not package verification has been enabled.
8416     *
8417     * @return true if verification should be performed
8418     */
8419    private boolean isVerificationEnabled(int userId, int installFlags) {
8420        if (!DEFAULT_VERIFY_ENABLE) {
8421            return false;
8422        }
8423
8424        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8425
8426        // Check if installing from ADB
8427        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8428            // Do not run verification in a test harness environment
8429            if (ActivityManager.isRunningInTestHarness()) {
8430                return false;
8431            }
8432            if (ensureVerifyAppsEnabled) {
8433                return true;
8434            }
8435            // Check if the developer does not want package verification for ADB installs
8436            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8437                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8438                return false;
8439            }
8440        }
8441
8442        if (ensureVerifyAppsEnabled) {
8443            return true;
8444        }
8445
8446        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8447                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8448    }
8449
8450    /**
8451     * Get the "allow unknown sources" setting.
8452     *
8453     * @return the current "allow unknown sources" setting
8454     */
8455    private int getUnknownSourcesSettings() {
8456        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8457                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8458                -1);
8459    }
8460
8461    @Override
8462    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8463        final int uid = Binder.getCallingUid();
8464        // writer
8465        synchronized (mPackages) {
8466            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8467            if (targetPackageSetting == null) {
8468                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8469            }
8470
8471            PackageSetting installerPackageSetting;
8472            if (installerPackageName != null) {
8473                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8474                if (installerPackageSetting == null) {
8475                    throw new IllegalArgumentException("Unknown installer package: "
8476                            + installerPackageName);
8477                }
8478            } else {
8479                installerPackageSetting = null;
8480            }
8481
8482            Signature[] callerSignature;
8483            Object obj = mSettings.getUserIdLPr(uid);
8484            if (obj != null) {
8485                if (obj instanceof SharedUserSetting) {
8486                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8487                } else if (obj instanceof PackageSetting) {
8488                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8489                } else {
8490                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8491                }
8492            } else {
8493                throw new SecurityException("Unknown calling uid " + uid);
8494            }
8495
8496            // Verify: can't set installerPackageName to a package that is
8497            // not signed with the same cert as the caller.
8498            if (installerPackageSetting != null) {
8499                if (compareSignatures(callerSignature,
8500                        installerPackageSetting.signatures.mSignatures)
8501                        != PackageManager.SIGNATURE_MATCH) {
8502                    throw new SecurityException(
8503                            "Caller does not have same cert as new installer package "
8504                            + installerPackageName);
8505                }
8506            }
8507
8508            // Verify: if target already has an installer package, it must
8509            // be signed with the same cert as the caller.
8510            if (targetPackageSetting.installerPackageName != null) {
8511                PackageSetting setting = mSettings.mPackages.get(
8512                        targetPackageSetting.installerPackageName);
8513                // If the currently set package isn't valid, then it's always
8514                // okay to change it.
8515                if (setting != null) {
8516                    if (compareSignatures(callerSignature,
8517                            setting.signatures.mSignatures)
8518                            != PackageManager.SIGNATURE_MATCH) {
8519                        throw new SecurityException(
8520                                "Caller does not have same cert as old installer package "
8521                                + targetPackageSetting.installerPackageName);
8522                    }
8523                }
8524            }
8525
8526            // Okay!
8527            targetPackageSetting.installerPackageName = installerPackageName;
8528            scheduleWriteSettingsLocked();
8529        }
8530    }
8531
8532    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8533        // Queue up an async operation since the package installation may take a little while.
8534        mHandler.post(new Runnable() {
8535            public void run() {
8536                mHandler.removeCallbacks(this);
8537                 // Result object to be returned
8538                PackageInstalledInfo res = new PackageInstalledInfo();
8539                res.returnCode = currentStatus;
8540                res.uid = -1;
8541                res.pkg = null;
8542                res.removedInfo = new PackageRemovedInfo();
8543                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8544                    args.doPreInstall(res.returnCode);
8545                    synchronized (mInstallLock) {
8546                        installPackageLI(args, res);
8547                    }
8548                    args.doPostInstall(res.returnCode, res.uid);
8549                }
8550
8551                // A restore should be performed at this point if (a) the install
8552                // succeeded, (b) the operation is not an update, and (c) the new
8553                // package has not opted out of backup participation.
8554                final boolean update = res.removedInfo.removedPackage != null;
8555                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8556                boolean doRestore = !update
8557                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8558
8559                // Set up the post-install work request bookkeeping.  This will be used
8560                // and cleaned up by the post-install event handling regardless of whether
8561                // there's a restore pass performed.  Token values are >= 1.
8562                int token;
8563                if (mNextInstallToken < 0) mNextInstallToken = 1;
8564                token = mNextInstallToken++;
8565
8566                PostInstallData data = new PostInstallData(args, res);
8567                mRunningInstalls.put(token, data);
8568                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8569
8570                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8571                    // Pass responsibility to the Backup Manager.  It will perform a
8572                    // restore if appropriate, then pass responsibility back to the
8573                    // Package Manager to run the post-install observer callbacks
8574                    // and broadcasts.
8575                    IBackupManager bm = IBackupManager.Stub.asInterface(
8576                            ServiceManager.getService(Context.BACKUP_SERVICE));
8577                    if (bm != null) {
8578                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8579                                + " to BM for possible restore");
8580                        try {
8581                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8582                        } catch (RemoteException e) {
8583                            // can't happen; the backup manager is local
8584                        } catch (Exception e) {
8585                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8586                            doRestore = false;
8587                        }
8588                    } else {
8589                        Slog.e(TAG, "Backup Manager not found!");
8590                        doRestore = false;
8591                    }
8592                }
8593
8594                if (!doRestore) {
8595                    // No restore possible, or the Backup Manager was mysteriously not
8596                    // available -- just fire the post-install work request directly.
8597                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8598                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8599                    mHandler.sendMessage(msg);
8600                }
8601            }
8602        });
8603    }
8604
8605    private abstract class HandlerParams {
8606        private static final int MAX_RETRIES = 4;
8607
8608        /**
8609         * Number of times startCopy() has been attempted and had a non-fatal
8610         * error.
8611         */
8612        private int mRetries = 0;
8613
8614        /** User handle for the user requesting the information or installation. */
8615        private final UserHandle mUser;
8616
8617        HandlerParams(UserHandle user) {
8618            mUser = user;
8619        }
8620
8621        UserHandle getUser() {
8622            return mUser;
8623        }
8624
8625        final boolean startCopy() {
8626            boolean res;
8627            try {
8628                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8629
8630                if (++mRetries > MAX_RETRIES) {
8631                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8632                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8633                    handleServiceError();
8634                    return false;
8635                } else {
8636                    handleStartCopy();
8637                    res = true;
8638                }
8639            } catch (RemoteException e) {
8640                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8641                mHandler.sendEmptyMessage(MCS_RECONNECT);
8642                res = false;
8643            }
8644            handleReturnCode();
8645            return res;
8646        }
8647
8648        final void serviceError() {
8649            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8650            handleServiceError();
8651            handleReturnCode();
8652        }
8653
8654        abstract void handleStartCopy() throws RemoteException;
8655        abstract void handleServiceError();
8656        abstract void handleReturnCode();
8657    }
8658
8659    class MeasureParams extends HandlerParams {
8660        private final PackageStats mStats;
8661        private boolean mSuccess;
8662
8663        private final IPackageStatsObserver mObserver;
8664
8665        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8666            super(new UserHandle(stats.userHandle));
8667            mObserver = observer;
8668            mStats = stats;
8669        }
8670
8671        @Override
8672        public String toString() {
8673            return "MeasureParams{"
8674                + Integer.toHexString(System.identityHashCode(this))
8675                + " " + mStats.packageName + "}";
8676        }
8677
8678        @Override
8679        void handleStartCopy() throws RemoteException {
8680            synchronized (mInstallLock) {
8681                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8682            }
8683
8684            if (mSuccess) {
8685                final boolean mounted;
8686                if (Environment.isExternalStorageEmulated()) {
8687                    mounted = true;
8688                } else {
8689                    final String status = Environment.getExternalStorageState();
8690                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8691                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8692                }
8693
8694                if (mounted) {
8695                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8696
8697                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8698                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8699
8700                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8701                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8702
8703                    // Always subtract cache size, since it's a subdirectory
8704                    mStats.externalDataSize -= mStats.externalCacheSize;
8705
8706                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8707                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8708
8709                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8710                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8711                }
8712            }
8713        }
8714
8715        @Override
8716        void handleReturnCode() {
8717            if (mObserver != null) {
8718                try {
8719                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8720                } catch (RemoteException e) {
8721                    Slog.i(TAG, "Observer no longer exists.");
8722                }
8723            }
8724        }
8725
8726        @Override
8727        void handleServiceError() {
8728            Slog.e(TAG, "Could not measure application " + mStats.packageName
8729                            + " external storage");
8730        }
8731    }
8732
8733    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8734            throws RemoteException {
8735        long result = 0;
8736        for (File path : paths) {
8737            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8738        }
8739        return result;
8740    }
8741
8742    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8743        for (File path : paths) {
8744            try {
8745                mcs.clearDirectory(path.getAbsolutePath());
8746            } catch (RemoteException e) {
8747            }
8748        }
8749    }
8750
8751    static class OriginInfo {
8752        /**
8753         * Location where install is coming from, before it has been
8754         * copied/renamed into place. This could be a single monolithic APK
8755         * file, or a cluster directory. This location may be untrusted.
8756         */
8757        final File file;
8758        final String cid;
8759
8760        /**
8761         * Flag indicating that {@link #file} or {@link #cid} has already been
8762         * staged, meaning downstream users don't need to defensively copy the
8763         * contents.
8764         */
8765        final boolean staged;
8766
8767        /**
8768         * Flag indicating that {@link #file} or {@link #cid} is an already
8769         * installed app that is being moved.
8770         */
8771        final boolean existing;
8772
8773        final String resolvedPath;
8774        final File resolvedFile;
8775
8776        static OriginInfo fromNothing() {
8777            return new OriginInfo(null, null, false, false);
8778        }
8779
8780        static OriginInfo fromUntrustedFile(File file) {
8781            return new OriginInfo(file, null, false, false);
8782        }
8783
8784        static OriginInfo fromExistingFile(File file) {
8785            return new OriginInfo(file, null, false, true);
8786        }
8787
8788        static OriginInfo fromStagedFile(File file) {
8789            return new OriginInfo(file, null, true, false);
8790        }
8791
8792        static OriginInfo fromStagedContainer(String cid) {
8793            return new OriginInfo(null, cid, true, false);
8794        }
8795
8796        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8797            this.file = file;
8798            this.cid = cid;
8799            this.staged = staged;
8800            this.existing = existing;
8801
8802            if (cid != null) {
8803                resolvedPath = PackageHelper.getSdDir(cid);
8804                resolvedFile = new File(resolvedPath);
8805            } else if (file != null) {
8806                resolvedPath = file.getAbsolutePath();
8807                resolvedFile = file;
8808            } else {
8809                resolvedPath = null;
8810                resolvedFile = null;
8811            }
8812        }
8813    }
8814
8815    class InstallParams extends HandlerParams {
8816        final OriginInfo origin;
8817        final IPackageInstallObserver2 observer;
8818        int installFlags;
8819        final String installerPackageName;
8820        final VerificationParams verificationParams;
8821        private InstallArgs mArgs;
8822        private int mRet;
8823        final String packageAbiOverride;
8824
8825        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8826                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8827                String packageAbiOverride) {
8828            super(user);
8829            this.origin = origin;
8830            this.observer = observer;
8831            this.installFlags = installFlags;
8832            this.installerPackageName = installerPackageName;
8833            this.verificationParams = verificationParams;
8834            this.packageAbiOverride = packageAbiOverride;
8835        }
8836
8837        @Override
8838        public String toString() {
8839            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8840                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8841        }
8842
8843        public ManifestDigest getManifestDigest() {
8844            if (verificationParams == null) {
8845                return null;
8846            }
8847            return verificationParams.getManifestDigest();
8848        }
8849
8850        private int installLocationPolicy(PackageInfoLite pkgLite) {
8851            String packageName = pkgLite.packageName;
8852            int installLocation = pkgLite.installLocation;
8853            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8854            // reader
8855            synchronized (mPackages) {
8856                PackageParser.Package pkg = mPackages.get(packageName);
8857                if (pkg != null) {
8858                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8859                        // Check for downgrading.
8860                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8861                            try {
8862                                checkDowngrade(pkg, pkgLite);
8863                            } catch (PackageManagerException e) {
8864                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8865                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8866                            }
8867                        }
8868                        // Check for updated system application.
8869                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8870                            if (onSd) {
8871                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8872                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8873                            }
8874                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8875                        } else {
8876                            if (onSd) {
8877                                // Install flag overrides everything.
8878                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8879                            }
8880                            // If current upgrade specifies particular preference
8881                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8882                                // Application explicitly specified internal.
8883                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8884                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8885                                // App explictly prefers external. Let policy decide
8886                            } else {
8887                                // Prefer previous location
8888                                if (isExternal(pkg)) {
8889                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8890                                }
8891                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8892                            }
8893                        }
8894                    } else {
8895                        // Invalid install. Return error code
8896                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8897                    }
8898                }
8899            }
8900            // All the special cases have been taken care of.
8901            // Return result based on recommended install location.
8902            if (onSd) {
8903                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8904            }
8905            return pkgLite.recommendedInstallLocation;
8906        }
8907
8908        /*
8909         * Invoke remote method to get package information and install
8910         * location values. Override install location based on default
8911         * policy if needed and then create install arguments based
8912         * on the install location.
8913         */
8914        public void handleStartCopy() throws RemoteException {
8915            int ret = PackageManager.INSTALL_SUCCEEDED;
8916
8917            // If we're already staged, we've firmly committed to an install location
8918            if (origin.staged) {
8919                if (origin.file != null) {
8920                    installFlags |= PackageManager.INSTALL_INTERNAL;
8921                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8922                } else if (origin.cid != null) {
8923                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8924                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8925                } else {
8926                    throw new IllegalStateException("Invalid stage location");
8927                }
8928            }
8929
8930            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8931            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8932
8933            PackageInfoLite pkgLite = null;
8934
8935            if (onInt && onSd) {
8936                // Check if both bits are set.
8937                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8938                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8939            } else {
8940                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8941                        packageAbiOverride);
8942
8943                /*
8944                 * If we have too little free space, try to free cache
8945                 * before giving up.
8946                 */
8947                if (!origin.staged && pkgLite.recommendedInstallLocation
8948                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8949                    // TODO: focus freeing disk space on the target device
8950                    final StorageManager storage = StorageManager.from(mContext);
8951                    final long lowThreshold = storage.getStorageLowBytes(
8952                            Environment.getDataDirectory());
8953
8954                    final long sizeBytes = mContainerService.calculateInstalledSize(
8955                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8956
8957                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8958                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8959                                installFlags, packageAbiOverride);
8960                    }
8961
8962                    /*
8963                     * The cache free must have deleted the file we
8964                     * downloaded to install.
8965                     *
8966                     * TODO: fix the "freeCache" call to not delete
8967                     *       the file we care about.
8968                     */
8969                    if (pkgLite.recommendedInstallLocation
8970                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8971                        pkgLite.recommendedInstallLocation
8972                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8973                    }
8974                }
8975            }
8976
8977            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8978                int loc = pkgLite.recommendedInstallLocation;
8979                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8980                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8981                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8982                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8983                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8984                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8985                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8986                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8987                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8988                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8989                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8990                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8991                } else {
8992                    // Override with defaults if needed.
8993                    loc = installLocationPolicy(pkgLite);
8994                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8995                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8996                    } else if (!onSd && !onInt) {
8997                        // Override install location with flags
8998                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8999                            // Set the flag to install on external media.
9000                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9001                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9002                        } else {
9003                            // Make sure the flag for installing on external
9004                            // media is unset
9005                            installFlags |= PackageManager.INSTALL_INTERNAL;
9006                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9007                        }
9008                    }
9009                }
9010            }
9011
9012            final InstallArgs args = createInstallArgs(this);
9013            mArgs = args;
9014
9015            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9016                 /*
9017                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9018                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9019                 */
9020                int userIdentifier = getUser().getIdentifier();
9021                if (userIdentifier == UserHandle.USER_ALL
9022                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9023                    userIdentifier = UserHandle.USER_OWNER;
9024                }
9025
9026                /*
9027                 * Determine if we have any installed package verifiers. If we
9028                 * do, then we'll defer to them to verify the packages.
9029                 */
9030                final int requiredUid = mRequiredVerifierPackage == null ? -1
9031                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9032                if (!origin.existing && requiredUid != -1
9033                        && isVerificationEnabled(userIdentifier, installFlags)) {
9034                    final Intent verification = new Intent(
9035                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9036                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9037                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9038                            PACKAGE_MIME_TYPE);
9039                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9040
9041                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9042                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9043                            0 /* TODO: Which userId? */);
9044
9045                    if (DEBUG_VERIFY) {
9046                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9047                                + verification.toString() + " with " + pkgLite.verifiers.length
9048                                + " optional verifiers");
9049                    }
9050
9051                    final int verificationId = mPendingVerificationToken++;
9052
9053                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9054
9055                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9056                            installerPackageName);
9057
9058                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9059                            installFlags);
9060
9061                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9062                            pkgLite.packageName);
9063
9064                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9065                            pkgLite.versionCode);
9066
9067                    if (verificationParams != null) {
9068                        if (verificationParams.getVerificationURI() != null) {
9069                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9070                                 verificationParams.getVerificationURI());
9071                        }
9072                        if (verificationParams.getOriginatingURI() != null) {
9073                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9074                                  verificationParams.getOriginatingURI());
9075                        }
9076                        if (verificationParams.getReferrer() != null) {
9077                            verification.putExtra(Intent.EXTRA_REFERRER,
9078                                  verificationParams.getReferrer());
9079                        }
9080                        if (verificationParams.getOriginatingUid() >= 0) {
9081                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9082                                  verificationParams.getOriginatingUid());
9083                        }
9084                        if (verificationParams.getInstallerUid() >= 0) {
9085                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9086                                  verificationParams.getInstallerUid());
9087                        }
9088                    }
9089
9090                    final PackageVerificationState verificationState = new PackageVerificationState(
9091                            requiredUid, args);
9092
9093                    mPendingVerification.append(verificationId, verificationState);
9094
9095                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9096                            receivers, verificationState);
9097
9098                    /*
9099                     * If any sufficient verifiers were listed in the package
9100                     * manifest, attempt to ask them.
9101                     */
9102                    if (sufficientVerifiers != null) {
9103                        final int N = sufficientVerifiers.size();
9104                        if (N == 0) {
9105                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9106                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9107                        } else {
9108                            for (int i = 0; i < N; i++) {
9109                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9110
9111                                final Intent sufficientIntent = new Intent(verification);
9112                                sufficientIntent.setComponent(verifierComponent);
9113
9114                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9115                            }
9116                        }
9117                    }
9118
9119                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9120                            mRequiredVerifierPackage, receivers);
9121                    if (ret == PackageManager.INSTALL_SUCCEEDED
9122                            && mRequiredVerifierPackage != null) {
9123                        /*
9124                         * Send the intent to the required verification agent,
9125                         * but only start the verification timeout after the
9126                         * target BroadcastReceivers have run.
9127                         */
9128                        verification.setComponent(requiredVerifierComponent);
9129                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9130                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9131                                new BroadcastReceiver() {
9132                                    @Override
9133                                    public void onReceive(Context context, Intent intent) {
9134                                        final Message msg = mHandler
9135                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9136                                        msg.arg1 = verificationId;
9137                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9138                                    }
9139                                }, null, 0, null, null);
9140
9141                        /*
9142                         * We don't want the copy to proceed until verification
9143                         * succeeds, so null out this field.
9144                         */
9145                        mArgs = null;
9146                    }
9147                } else {
9148                    /*
9149                     * No package verification is enabled, so immediately start
9150                     * the remote call to initiate copy using temporary file.
9151                     */
9152                    ret = args.copyApk(mContainerService, true);
9153                }
9154            }
9155
9156            mRet = ret;
9157        }
9158
9159        @Override
9160        void handleReturnCode() {
9161            // If mArgs is null, then MCS couldn't be reached. When it
9162            // reconnects, it will try again to install. At that point, this
9163            // will succeed.
9164            if (mArgs != null) {
9165                processPendingInstall(mArgs, mRet);
9166            }
9167        }
9168
9169        @Override
9170        void handleServiceError() {
9171            mArgs = createInstallArgs(this);
9172            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9173        }
9174
9175        public boolean isForwardLocked() {
9176            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9177        }
9178    }
9179
9180    /**
9181     * Used during creation of InstallArgs
9182     *
9183     * @param installFlags package installation flags
9184     * @return true if should be installed on external storage
9185     */
9186    private static boolean installOnSd(int installFlags) {
9187        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9188            return false;
9189        }
9190        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9191            return true;
9192        }
9193        return false;
9194    }
9195
9196    /**
9197     * Used during creation of InstallArgs
9198     *
9199     * @param installFlags package installation flags
9200     * @return true if should be installed as forward locked
9201     */
9202    private static boolean installForwardLocked(int installFlags) {
9203        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9204    }
9205
9206    private InstallArgs createInstallArgs(InstallParams params) {
9207        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9208            return new AsecInstallArgs(params);
9209        } else {
9210            return new FileInstallArgs(params);
9211        }
9212    }
9213
9214    /**
9215     * Create args that describe an existing installed package. Typically used
9216     * when cleaning up old installs, or used as a move source.
9217     */
9218    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9219            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9220        final boolean isInAsec;
9221        if (installOnSd(installFlags)) {
9222            /* Apps on SD card are always in ASEC containers. */
9223            isInAsec = true;
9224        } else if (installForwardLocked(installFlags)
9225                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9226            /*
9227             * Forward-locked apps are only in ASEC containers if they're the
9228             * new style
9229             */
9230            isInAsec = true;
9231        } else {
9232            isInAsec = false;
9233        }
9234
9235        if (isInAsec) {
9236            return new AsecInstallArgs(codePath, instructionSets,
9237                    installOnSd(installFlags), installForwardLocked(installFlags));
9238        } else {
9239            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9240                    instructionSets);
9241        }
9242    }
9243
9244    static abstract class InstallArgs {
9245        /** @see InstallParams#origin */
9246        final OriginInfo origin;
9247
9248        final IPackageInstallObserver2 observer;
9249        // Always refers to PackageManager flags only
9250        final int installFlags;
9251        final String installerPackageName;
9252        final ManifestDigest manifestDigest;
9253        final UserHandle user;
9254        final String abiOverride;
9255
9256        // The list of instruction sets supported by this app. This is currently
9257        // only used during the rmdex() phase to clean up resources. We can get rid of this
9258        // if we move dex files under the common app path.
9259        /* nullable */ String[] instructionSets;
9260
9261        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9262                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9263                String[] instructionSets, String abiOverride) {
9264            this.origin = origin;
9265            this.installFlags = installFlags;
9266            this.observer = observer;
9267            this.installerPackageName = installerPackageName;
9268            this.manifestDigest = manifestDigest;
9269            this.user = user;
9270            this.instructionSets = instructionSets;
9271            this.abiOverride = abiOverride;
9272        }
9273
9274        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9275        abstract int doPreInstall(int status);
9276
9277        /**
9278         * Rename package into final resting place. All paths on the given
9279         * scanned package should be updated to reflect the rename.
9280         */
9281        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9282        abstract int doPostInstall(int status, int uid);
9283
9284        /** @see PackageSettingBase#codePathString */
9285        abstract String getCodePath();
9286        /** @see PackageSettingBase#resourcePathString */
9287        abstract String getResourcePath();
9288        abstract String getLegacyNativeLibraryPath();
9289
9290        // Need installer lock especially for dex file removal.
9291        abstract void cleanUpResourcesLI();
9292        abstract boolean doPostDeleteLI(boolean delete);
9293        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9294
9295        /**
9296         * Called before the source arguments are copied. This is used mostly
9297         * for MoveParams when it needs to read the source file to put it in the
9298         * destination.
9299         */
9300        int doPreCopy() {
9301            return PackageManager.INSTALL_SUCCEEDED;
9302        }
9303
9304        /**
9305         * Called after the source arguments are copied. This is used mostly for
9306         * MoveParams when it needs to read the source file to put it in the
9307         * destination.
9308         *
9309         * @return
9310         */
9311        int doPostCopy(int uid) {
9312            return PackageManager.INSTALL_SUCCEEDED;
9313        }
9314
9315        protected boolean isFwdLocked() {
9316            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9317        }
9318
9319        protected boolean isExternal() {
9320            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9321        }
9322
9323        UserHandle getUser() {
9324            return user;
9325        }
9326    }
9327
9328    /**
9329     * Logic to handle installation of non-ASEC applications, including copying
9330     * and renaming logic.
9331     */
9332    class FileInstallArgs extends InstallArgs {
9333        private File codeFile;
9334        private File resourceFile;
9335        private File legacyNativeLibraryPath;
9336
9337        // Example topology:
9338        // /data/app/com.example/base.apk
9339        // /data/app/com.example/split_foo.apk
9340        // /data/app/com.example/lib/arm/libfoo.so
9341        // /data/app/com.example/lib/arm64/libfoo.so
9342        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9343
9344        /** New install */
9345        FileInstallArgs(InstallParams params) {
9346            super(params.origin, params.observer, params.installFlags,
9347                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9348                    null /* instruction sets */, params.packageAbiOverride);
9349            if (isFwdLocked()) {
9350                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9351            }
9352        }
9353
9354        /** Existing install */
9355        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9356                String[] instructionSets) {
9357            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9358            this.codeFile = (codePath != null) ? new File(codePath) : null;
9359            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9360            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9361                    new File(legacyNativeLibraryPath) : null;
9362        }
9363
9364        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9365            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9366                    isFwdLocked(), abiOverride);
9367
9368            final StorageManager storage = StorageManager.from(mContext);
9369            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9370        }
9371
9372        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9373            if (origin.staged) {
9374                Slog.d(TAG, origin.file + " already staged; skipping copy");
9375                codeFile = origin.file;
9376                resourceFile = origin.file;
9377                return PackageManager.INSTALL_SUCCEEDED;
9378            }
9379
9380            try {
9381                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9382                codeFile = tempDir;
9383                resourceFile = tempDir;
9384            } catch (IOException e) {
9385                Slog.w(TAG, "Failed to create copy file: " + e);
9386                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9387            }
9388
9389            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9390                @Override
9391                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9392                    if (!FileUtils.isValidExtFilename(name)) {
9393                        throw new IllegalArgumentException("Invalid filename: " + name);
9394                    }
9395                    try {
9396                        final File file = new File(codeFile, name);
9397                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9398                                O_RDWR | O_CREAT, 0644);
9399                        Os.chmod(file.getAbsolutePath(), 0644);
9400                        return new ParcelFileDescriptor(fd);
9401                    } catch (ErrnoException e) {
9402                        throw new RemoteException("Failed to open: " + e.getMessage());
9403                    }
9404                }
9405            };
9406
9407            int ret = PackageManager.INSTALL_SUCCEEDED;
9408            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9409            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9410                Slog.e(TAG, "Failed to copy package");
9411                return ret;
9412            }
9413
9414            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9415            NativeLibraryHelper.Handle handle = null;
9416            try {
9417                handle = NativeLibraryHelper.Handle.create(codeFile);
9418                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9419                        abiOverride);
9420            } catch (IOException e) {
9421                Slog.e(TAG, "Copying native libraries failed", e);
9422                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9423            } finally {
9424                IoUtils.closeQuietly(handle);
9425            }
9426
9427            return ret;
9428        }
9429
9430        int doPreInstall(int status) {
9431            if (status != PackageManager.INSTALL_SUCCEEDED) {
9432                cleanUp();
9433            }
9434            return status;
9435        }
9436
9437        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9438            if (status != PackageManager.INSTALL_SUCCEEDED) {
9439                cleanUp();
9440                return false;
9441            } else {
9442                final File beforeCodeFile = codeFile;
9443                final File afterCodeFile = getNextCodePath(pkg.packageName);
9444
9445                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9446                try {
9447                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9448                } catch (ErrnoException e) {
9449                    Slog.d(TAG, "Failed to rename", e);
9450                    return false;
9451                }
9452
9453                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9454                    Slog.d(TAG, "Failed to restorecon");
9455                    return false;
9456                }
9457
9458                // Reflect the rename internally
9459                codeFile = afterCodeFile;
9460                resourceFile = afterCodeFile;
9461
9462                // Reflect the rename in scanned details
9463                pkg.codePath = afterCodeFile.getAbsolutePath();
9464                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9465                        pkg.baseCodePath);
9466                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9467                        pkg.splitCodePaths);
9468
9469                // Reflect the rename in app info
9470                pkg.applicationInfo.setCodePath(pkg.codePath);
9471                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9472                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9473                pkg.applicationInfo.setResourcePath(pkg.codePath);
9474                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9475                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9476
9477                return true;
9478            }
9479        }
9480
9481        int doPostInstall(int status, int uid) {
9482            if (status != PackageManager.INSTALL_SUCCEEDED) {
9483                cleanUp();
9484            }
9485            return status;
9486        }
9487
9488        @Override
9489        String getCodePath() {
9490            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9491        }
9492
9493        @Override
9494        String getResourcePath() {
9495            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9496        }
9497
9498        @Override
9499        String getLegacyNativeLibraryPath() {
9500            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9501        }
9502
9503        private boolean cleanUp() {
9504            if (codeFile == null || !codeFile.exists()) {
9505                return false;
9506            }
9507
9508            if (codeFile.isDirectory()) {
9509                FileUtils.deleteContents(codeFile);
9510            }
9511            codeFile.delete();
9512
9513            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9514                resourceFile.delete();
9515            }
9516
9517            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9518                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9519                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9520                }
9521                legacyNativeLibraryPath.delete();
9522            }
9523
9524            return true;
9525        }
9526
9527        void cleanUpResourcesLI() {
9528            // Try enumerating all code paths before deleting
9529            List<String> allCodePaths = Collections.EMPTY_LIST;
9530            if (codeFile != null && codeFile.exists()) {
9531                try {
9532                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9533                    allCodePaths = pkg.getAllCodePaths();
9534                } catch (PackageParserException e) {
9535                    // Ignored; we tried our best
9536                }
9537            }
9538
9539            cleanUp();
9540
9541            if (!allCodePaths.isEmpty()) {
9542                if (instructionSets == null) {
9543                    throw new IllegalStateException("instructionSet == null");
9544                }
9545                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9546                for (String codePath : allCodePaths) {
9547                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9548                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9549                        if (retCode < 0) {
9550                            Slog.w(TAG, "Couldn't remove dex file for package: "
9551                                    + " at location " + codePath + ", retcode=" + retCode);
9552                            // we don't consider this to be a failure of the core package deletion
9553                        }
9554                    }
9555                }
9556            }
9557        }
9558
9559        boolean doPostDeleteLI(boolean delete) {
9560            // XXX err, shouldn't we respect the delete flag?
9561            cleanUpResourcesLI();
9562            return true;
9563        }
9564    }
9565
9566    private boolean isAsecExternal(String cid) {
9567        final String asecPath = PackageHelper.getSdFilesystem(cid);
9568        return !asecPath.startsWith(mAsecInternalPath);
9569    }
9570
9571    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9572            PackageManagerException {
9573        if (copyRet < 0) {
9574            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9575                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9576                throw new PackageManagerException(copyRet, message);
9577            }
9578        }
9579    }
9580
9581    /**
9582     * Extract the MountService "container ID" from the full code path of an
9583     * .apk.
9584     */
9585    static String cidFromCodePath(String fullCodePath) {
9586        int eidx = fullCodePath.lastIndexOf("/");
9587        String subStr1 = fullCodePath.substring(0, eidx);
9588        int sidx = subStr1.lastIndexOf("/");
9589        return subStr1.substring(sidx+1, eidx);
9590    }
9591
9592    /**
9593     * Logic to handle installation of ASEC applications, including copying and
9594     * renaming logic.
9595     */
9596    class AsecInstallArgs extends InstallArgs {
9597        static final String RES_FILE_NAME = "pkg.apk";
9598        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9599
9600        String cid;
9601        String packagePath;
9602        String resourcePath;
9603        String legacyNativeLibraryDir;
9604
9605        /** New install */
9606        AsecInstallArgs(InstallParams params) {
9607            super(params.origin, params.observer, params.installFlags,
9608                    params.installerPackageName, params.getManifestDigest(),
9609                    params.getUser(), null /* instruction sets */,
9610                    params.packageAbiOverride);
9611        }
9612
9613        /** Existing install */
9614        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9615                        boolean isExternal, boolean isForwardLocked) {
9616            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9617                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9618                    instructionSets, null);
9619            // Hackily pretend we're still looking at a full code path
9620            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9621                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9622            }
9623
9624            // Extract cid from fullCodePath
9625            int eidx = fullCodePath.lastIndexOf("/");
9626            String subStr1 = fullCodePath.substring(0, eidx);
9627            int sidx = subStr1.lastIndexOf("/");
9628            cid = subStr1.substring(sidx+1, eidx);
9629            setMountPath(subStr1);
9630        }
9631
9632        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9633            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9634                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9635                    instructionSets, null);
9636            this.cid = cid;
9637            setMountPath(PackageHelper.getSdDir(cid));
9638        }
9639
9640        void createCopyFile() {
9641            cid = mInstallerService.allocateExternalStageCidLegacy();
9642        }
9643
9644        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9645            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9646                    abiOverride);
9647
9648            final File target;
9649            if (isExternal()) {
9650                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9651            } else {
9652                target = Environment.getDataDirectory();
9653            }
9654
9655            final StorageManager storage = StorageManager.from(mContext);
9656            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9657        }
9658
9659        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9660            if (origin.staged) {
9661                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9662                cid = origin.cid;
9663                setMountPath(PackageHelper.getSdDir(cid));
9664                return PackageManager.INSTALL_SUCCEEDED;
9665            }
9666
9667            if (temp) {
9668                createCopyFile();
9669            } else {
9670                /*
9671                 * Pre-emptively destroy the container since it's destroyed if
9672                 * copying fails due to it existing anyway.
9673                 */
9674                PackageHelper.destroySdDir(cid);
9675            }
9676
9677            final String newMountPath = imcs.copyPackageToContainer(
9678                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9679                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9680
9681            if (newMountPath != null) {
9682                setMountPath(newMountPath);
9683                return PackageManager.INSTALL_SUCCEEDED;
9684            } else {
9685                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9686            }
9687        }
9688
9689        @Override
9690        String getCodePath() {
9691            return packagePath;
9692        }
9693
9694        @Override
9695        String getResourcePath() {
9696            return resourcePath;
9697        }
9698
9699        @Override
9700        String getLegacyNativeLibraryPath() {
9701            return legacyNativeLibraryDir;
9702        }
9703
9704        int doPreInstall(int status) {
9705            if (status != PackageManager.INSTALL_SUCCEEDED) {
9706                // Destroy container
9707                PackageHelper.destroySdDir(cid);
9708            } else {
9709                boolean mounted = PackageHelper.isContainerMounted(cid);
9710                if (!mounted) {
9711                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9712                            Process.SYSTEM_UID);
9713                    if (newMountPath != null) {
9714                        setMountPath(newMountPath);
9715                    } else {
9716                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9717                    }
9718                }
9719            }
9720            return status;
9721        }
9722
9723        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9724            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9725            String newMountPath = null;
9726            if (PackageHelper.isContainerMounted(cid)) {
9727                // Unmount the container
9728                if (!PackageHelper.unMountSdDir(cid)) {
9729                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9730                    return false;
9731                }
9732            }
9733            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9734                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9735                        " which might be stale. Will try to clean up.");
9736                // Clean up the stale container and proceed to recreate.
9737                if (!PackageHelper.destroySdDir(newCacheId)) {
9738                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9739                    return false;
9740                }
9741                // Successfully cleaned up stale container. Try to rename again.
9742                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9743                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9744                            + " inspite of cleaning it up.");
9745                    return false;
9746                }
9747            }
9748            if (!PackageHelper.isContainerMounted(newCacheId)) {
9749                Slog.w(TAG, "Mounting container " + newCacheId);
9750                newMountPath = PackageHelper.mountSdDir(newCacheId,
9751                        getEncryptKey(), Process.SYSTEM_UID);
9752            } else {
9753                newMountPath = PackageHelper.getSdDir(newCacheId);
9754            }
9755            if (newMountPath == null) {
9756                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9757                return false;
9758            }
9759            Log.i(TAG, "Succesfully renamed " + cid +
9760                    " to " + newCacheId +
9761                    " at new path: " + newMountPath);
9762            cid = newCacheId;
9763
9764            final File beforeCodeFile = new File(packagePath);
9765            setMountPath(newMountPath);
9766            final File afterCodeFile = new File(packagePath);
9767
9768            // Reflect the rename in scanned details
9769            pkg.codePath = afterCodeFile.getAbsolutePath();
9770            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9771                    pkg.baseCodePath);
9772            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9773                    pkg.splitCodePaths);
9774
9775            // Reflect the rename in app info
9776            pkg.applicationInfo.setCodePath(pkg.codePath);
9777            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9778            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9779            pkg.applicationInfo.setResourcePath(pkg.codePath);
9780            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9781            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9782
9783            return true;
9784        }
9785
9786        private void setMountPath(String mountPath) {
9787            final File mountFile = new File(mountPath);
9788
9789            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9790            if (monolithicFile.exists()) {
9791                packagePath = monolithicFile.getAbsolutePath();
9792                if (isFwdLocked()) {
9793                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9794                } else {
9795                    resourcePath = packagePath;
9796                }
9797            } else {
9798                packagePath = mountFile.getAbsolutePath();
9799                resourcePath = packagePath;
9800            }
9801
9802            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9803        }
9804
9805        int doPostInstall(int status, int uid) {
9806            if (status != PackageManager.INSTALL_SUCCEEDED) {
9807                cleanUp();
9808            } else {
9809                final int groupOwner;
9810                final String protectedFile;
9811                if (isFwdLocked()) {
9812                    groupOwner = UserHandle.getSharedAppGid(uid);
9813                    protectedFile = RES_FILE_NAME;
9814                } else {
9815                    groupOwner = -1;
9816                    protectedFile = null;
9817                }
9818
9819                if (uid < Process.FIRST_APPLICATION_UID
9820                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9821                    Slog.e(TAG, "Failed to finalize " + cid);
9822                    PackageHelper.destroySdDir(cid);
9823                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9824                }
9825
9826                boolean mounted = PackageHelper.isContainerMounted(cid);
9827                if (!mounted) {
9828                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9829                }
9830            }
9831            return status;
9832        }
9833
9834        private void cleanUp() {
9835            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9836
9837            // Destroy secure container
9838            PackageHelper.destroySdDir(cid);
9839        }
9840
9841        private List<String> getAllCodePaths() {
9842            final File codeFile = new File(getCodePath());
9843            if (codeFile != null && codeFile.exists()) {
9844                try {
9845                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9846                    return pkg.getAllCodePaths();
9847                } catch (PackageParserException e) {
9848                    // Ignored; we tried our best
9849                }
9850            }
9851            return Collections.EMPTY_LIST;
9852        }
9853
9854        void cleanUpResourcesLI() {
9855            // Enumerate all code paths before deleting
9856            cleanUpResourcesLI(getAllCodePaths());
9857        }
9858
9859        private void cleanUpResourcesLI(List<String> allCodePaths) {
9860            cleanUp();
9861
9862            if (!allCodePaths.isEmpty()) {
9863                if (instructionSets == null) {
9864                    throw new IllegalStateException("instructionSet == null");
9865                }
9866                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9867                for (String codePath : allCodePaths) {
9868                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9869                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9870                        if (retCode < 0) {
9871                            Slog.w(TAG, "Couldn't remove dex file for package: "
9872                                    + " at location " + codePath + ", retcode=" + retCode);
9873                            // we don't consider this to be a failure of the core package deletion
9874                        }
9875                    }
9876                }
9877            }
9878        }
9879
9880        boolean matchContainer(String app) {
9881            if (cid.startsWith(app)) {
9882                return true;
9883            }
9884            return false;
9885        }
9886
9887        String getPackageName() {
9888            return getAsecPackageName(cid);
9889        }
9890
9891        boolean doPostDeleteLI(boolean delete) {
9892            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9893            final List<String> allCodePaths = getAllCodePaths();
9894            boolean mounted = PackageHelper.isContainerMounted(cid);
9895            if (mounted) {
9896                // Unmount first
9897                if (PackageHelper.unMountSdDir(cid)) {
9898                    mounted = false;
9899                }
9900            }
9901            if (!mounted && delete) {
9902                cleanUpResourcesLI(allCodePaths);
9903            }
9904            return !mounted;
9905        }
9906
9907        @Override
9908        int doPreCopy() {
9909            if (isFwdLocked()) {
9910                if (!PackageHelper.fixSdPermissions(cid,
9911                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9912                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9913                }
9914            }
9915
9916            return PackageManager.INSTALL_SUCCEEDED;
9917        }
9918
9919        @Override
9920        int doPostCopy(int uid) {
9921            if (isFwdLocked()) {
9922                if (uid < Process.FIRST_APPLICATION_UID
9923                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9924                                RES_FILE_NAME)) {
9925                    Slog.e(TAG, "Failed to finalize " + cid);
9926                    PackageHelper.destroySdDir(cid);
9927                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9928                }
9929            }
9930
9931            return PackageManager.INSTALL_SUCCEEDED;
9932        }
9933    }
9934
9935    static String getAsecPackageName(String packageCid) {
9936        int idx = packageCid.lastIndexOf("-");
9937        if (idx == -1) {
9938            return packageCid;
9939        }
9940        return packageCid.substring(0, idx);
9941    }
9942
9943    // Utility method used to create code paths based on package name and available index.
9944    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9945        String idxStr = "";
9946        int idx = 1;
9947        // Fall back to default value of idx=1 if prefix is not
9948        // part of oldCodePath
9949        if (oldCodePath != null) {
9950            String subStr = oldCodePath;
9951            // Drop the suffix right away
9952            if (suffix != null && subStr.endsWith(suffix)) {
9953                subStr = subStr.substring(0, subStr.length() - suffix.length());
9954            }
9955            // If oldCodePath already contains prefix find out the
9956            // ending index to either increment or decrement.
9957            int sidx = subStr.lastIndexOf(prefix);
9958            if (sidx != -1) {
9959                subStr = subStr.substring(sidx + prefix.length());
9960                if (subStr != null) {
9961                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9962                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9963                    }
9964                    try {
9965                        idx = Integer.parseInt(subStr);
9966                        if (idx <= 1) {
9967                            idx++;
9968                        } else {
9969                            idx--;
9970                        }
9971                    } catch(NumberFormatException e) {
9972                    }
9973                }
9974            }
9975        }
9976        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9977        return prefix + idxStr;
9978    }
9979
9980    private File getNextCodePath(String packageName) {
9981        int suffix = 1;
9982        File result;
9983        do {
9984            result = new File(mAppInstallDir, packageName + "-" + suffix);
9985            suffix++;
9986        } while (result.exists());
9987        return result;
9988    }
9989
9990    // Utility method used to ignore ADD/REMOVE events
9991    // by directory observer.
9992    private static boolean ignoreCodePath(String fullPathStr) {
9993        String apkName = deriveCodePathName(fullPathStr);
9994        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9995        if (idx != -1 && ((idx+1) < apkName.length())) {
9996            // Make sure the package ends with a numeral
9997            String version = apkName.substring(idx+1);
9998            try {
9999                Integer.parseInt(version);
10000                return true;
10001            } catch (NumberFormatException e) {}
10002        }
10003        return false;
10004    }
10005
10006    // Utility method that returns the relative package path with respect
10007    // to the installation directory. Like say for /data/data/com.test-1.apk
10008    // string com.test-1 is returned.
10009    static String deriveCodePathName(String codePath) {
10010        if (codePath == null) {
10011            return null;
10012        }
10013        final File codeFile = new File(codePath);
10014        final String name = codeFile.getName();
10015        if (codeFile.isDirectory()) {
10016            return name;
10017        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10018            final int lastDot = name.lastIndexOf('.');
10019            return name.substring(0, lastDot);
10020        } else {
10021            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10022            return null;
10023        }
10024    }
10025
10026    class PackageInstalledInfo {
10027        String name;
10028        int uid;
10029        // The set of users that originally had this package installed.
10030        int[] origUsers;
10031        // The set of users that now have this package installed.
10032        int[] newUsers;
10033        PackageParser.Package pkg;
10034        int returnCode;
10035        String returnMsg;
10036        PackageRemovedInfo removedInfo;
10037
10038        public void setError(int code, String msg) {
10039            returnCode = code;
10040            returnMsg = msg;
10041            Slog.w(TAG, msg);
10042        }
10043
10044        public void setError(String msg, PackageParserException e) {
10045            returnCode = e.error;
10046            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10047            Slog.w(TAG, msg, e);
10048        }
10049
10050        public void setError(String msg, PackageManagerException e) {
10051            returnCode = e.error;
10052            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10053            Slog.w(TAG, msg, e);
10054        }
10055
10056        // In some error cases we want to convey more info back to the observer
10057        String origPackage;
10058        String origPermission;
10059    }
10060
10061    /*
10062     * Install a non-existing package.
10063     */
10064    private void installNewPackageLI(PackageParser.Package pkg,
10065            int parseFlags, int scanFlags, UserHandle user,
10066            String installerPackageName, PackageInstalledInfo res) {
10067        // Remember this for later, in case we need to rollback this install
10068        String pkgName = pkg.packageName;
10069
10070        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10071        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10072        synchronized(mPackages) {
10073            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10074                // A package with the same name is already installed, though
10075                // it has been renamed to an older name.  The package we
10076                // are trying to install should be installed as an update to
10077                // the existing one, but that has not been requested, so bail.
10078                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10079                        + " without first uninstalling package running as "
10080                        + mSettings.mRenamedPackages.get(pkgName));
10081                return;
10082            }
10083            if (mPackages.containsKey(pkgName)) {
10084                // Don't allow installation over an existing package with the same name.
10085                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10086                        + " without first uninstalling.");
10087                return;
10088            }
10089        }
10090
10091        try {
10092            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10093                    System.currentTimeMillis(), user);
10094
10095            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10096            // delete the partially installed application. the data directory will have to be
10097            // restored if it was already existing
10098            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10099                // remove package from internal structures.  Note that we want deletePackageX to
10100                // delete the package data and cache directories that it created in
10101                // scanPackageLocked, unless those directories existed before we even tried to
10102                // install.
10103                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10104                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10105                                res.removedInfo, true);
10106            }
10107
10108        } catch (PackageManagerException e) {
10109            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10110        }
10111    }
10112
10113    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10114        // Upgrade keysets are being used.  Determine if new package has a superset of the
10115        // required keys.
10116        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10117        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10118        for (int i = 0; i < upgradeKeySets.length; i++) {
10119            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10120            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10121                return true;
10122            }
10123        }
10124        return false;
10125    }
10126
10127    private void replacePackageLI(PackageParser.Package pkg,
10128            int parseFlags, int scanFlags, UserHandle user,
10129            String installerPackageName, PackageInstalledInfo res) {
10130        PackageParser.Package oldPackage;
10131        String pkgName = pkg.packageName;
10132        int[] allUsers;
10133        boolean[] perUserInstalled;
10134
10135        // First find the old package info and check signatures
10136        synchronized(mPackages) {
10137            oldPackage = mPackages.get(pkgName);
10138            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10139            PackageSetting ps = mSettings.mPackages.get(pkgName);
10140            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10141                // default to original signature matching
10142                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10143                    != PackageManager.SIGNATURE_MATCH) {
10144                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10145                            "New package has a different signature: " + pkgName);
10146                    return;
10147                }
10148            } else {
10149                if(!checkUpgradeKeySetLP(ps, pkg)) {
10150                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10151                            "New package not signed by keys specified by upgrade-keysets: "
10152                            + pkgName);
10153                    return;
10154                }
10155            }
10156
10157            // In case of rollback, remember per-user/profile install state
10158            allUsers = sUserManager.getUserIds();
10159            perUserInstalled = new boolean[allUsers.length];
10160            for (int i = 0; i < allUsers.length; i++) {
10161                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10162            }
10163        }
10164
10165        boolean sysPkg = (isSystemApp(oldPackage));
10166        if (sysPkg) {
10167            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10168                    user, allUsers, perUserInstalled, installerPackageName, res);
10169        } else {
10170            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10171                    user, allUsers, perUserInstalled, installerPackageName, res);
10172        }
10173    }
10174
10175    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10176            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10177            int[] allUsers, boolean[] perUserInstalled,
10178            String installerPackageName, PackageInstalledInfo res) {
10179        String pkgName = deletedPackage.packageName;
10180        boolean deletedPkg = true;
10181        boolean updatedSettings = false;
10182
10183        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10184                + deletedPackage);
10185        long origUpdateTime;
10186        if (pkg.mExtras != null) {
10187            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10188        } else {
10189            origUpdateTime = 0;
10190        }
10191
10192        // First delete the existing package while retaining the data directory
10193        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10194                res.removedInfo, true)) {
10195            // If the existing package wasn't successfully deleted
10196            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10197            deletedPkg = false;
10198        } else {
10199            // Successfully deleted the old package; proceed with replace.
10200
10201            // If deleted package lived in a container, give users a chance to
10202            // relinquish resources before killing.
10203            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10204                if (DEBUG_INSTALL) {
10205                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10206                }
10207                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10208                final ArrayList<String> pkgList = new ArrayList<String>(1);
10209                pkgList.add(deletedPackage.applicationInfo.packageName);
10210                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10211            }
10212
10213            deleteCodeCacheDirsLI(pkgName);
10214            try {
10215                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10216                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10217                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10218                updatedSettings = true;
10219            } catch (PackageManagerException e) {
10220                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10221            }
10222        }
10223
10224        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10225            // remove package from internal structures.  Note that we want deletePackageX to
10226            // delete the package data and cache directories that it created in
10227            // scanPackageLocked, unless those directories existed before we even tried to
10228            // install.
10229            if(updatedSettings) {
10230                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10231                deletePackageLI(
10232                        pkgName, null, true, allUsers, perUserInstalled,
10233                        PackageManager.DELETE_KEEP_DATA,
10234                                res.removedInfo, true);
10235            }
10236            // Since we failed to install the new package we need to restore the old
10237            // package that we deleted.
10238            if (deletedPkg) {
10239                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10240                File restoreFile = new File(deletedPackage.codePath);
10241                // Parse old package
10242                boolean oldOnSd = isExternal(deletedPackage);
10243                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10244                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10245                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10246                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10247                try {
10248                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10249                } catch (PackageManagerException e) {
10250                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10251                            + e.getMessage());
10252                    return;
10253                }
10254                // Restore of old package succeeded. Update permissions.
10255                // writer
10256                synchronized (mPackages) {
10257                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10258                            UPDATE_PERMISSIONS_ALL);
10259                    // can downgrade to reader
10260                    mSettings.writeLPr();
10261                }
10262                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10263            }
10264        }
10265    }
10266
10267    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10268            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10269            int[] allUsers, boolean[] perUserInstalled,
10270            String installerPackageName, PackageInstalledInfo res) {
10271        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10272                + ", old=" + deletedPackage);
10273        boolean disabledSystem = false;
10274        boolean updatedSettings = false;
10275        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10276        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10277            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10278        }
10279        String packageName = deletedPackage.packageName;
10280        if (packageName == null) {
10281            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10282                    "Attempt to delete null packageName.");
10283            return;
10284        }
10285        PackageParser.Package oldPkg;
10286        PackageSetting oldPkgSetting;
10287        // reader
10288        synchronized (mPackages) {
10289            oldPkg = mPackages.get(packageName);
10290            oldPkgSetting = mSettings.mPackages.get(packageName);
10291            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10292                    (oldPkgSetting == null)) {
10293                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10294                        "Couldn't find package:" + packageName + " information");
10295                return;
10296            }
10297        }
10298
10299        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10300
10301        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10302        res.removedInfo.removedPackage = packageName;
10303        // Remove existing system package
10304        removePackageLI(oldPkgSetting, true);
10305        // writer
10306        synchronized (mPackages) {
10307            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10308            if (!disabledSystem && deletedPackage != null) {
10309                // We didn't need to disable the .apk as a current system package,
10310                // which means we are replacing another update that is already
10311                // installed.  We need to make sure to delete the older one's .apk.
10312                res.removedInfo.args = createInstallArgsForExisting(0,
10313                        deletedPackage.applicationInfo.getCodePath(),
10314                        deletedPackage.applicationInfo.getResourcePath(),
10315                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10316                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10317            } else {
10318                res.removedInfo.args = null;
10319            }
10320        }
10321
10322        // Successfully disabled the old package. Now proceed with re-installation
10323        deleteCodeCacheDirsLI(packageName);
10324
10325        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10326        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10327
10328        PackageParser.Package newPackage = null;
10329        try {
10330            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10331            if (newPackage.mExtras != null) {
10332                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10333                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10334                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10335
10336                // is the update attempting to change shared user? that isn't going to work...
10337                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10338                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10339                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10340                            + " to " + newPkgSetting.sharedUser);
10341                    updatedSettings = true;
10342                }
10343            }
10344
10345            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10346                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10347                updatedSettings = true;
10348            }
10349
10350        } catch (PackageManagerException e) {
10351            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10352        }
10353
10354        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10355            // Re installation failed. Restore old information
10356            // Remove new pkg information
10357            if (newPackage != null) {
10358                removeInstalledPackageLI(newPackage, true);
10359            }
10360            // Add back the old system package
10361            try {
10362                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10363            } catch (PackageManagerException e) {
10364                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10365            }
10366            // Restore the old system information in Settings
10367            synchronized (mPackages) {
10368                if (disabledSystem) {
10369                    mSettings.enableSystemPackageLPw(packageName);
10370                }
10371                if (updatedSettings) {
10372                    mSettings.setInstallerPackageName(packageName,
10373                            oldPkgSetting.installerPackageName);
10374                }
10375                mSettings.writeLPr();
10376            }
10377        }
10378    }
10379
10380    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10381            int[] allUsers, boolean[] perUserInstalled,
10382            PackageInstalledInfo res) {
10383        String pkgName = newPackage.packageName;
10384        synchronized (mPackages) {
10385            //write settings. the installStatus will be incomplete at this stage.
10386            //note that the new package setting would have already been
10387            //added to mPackages. It hasn't been persisted yet.
10388            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10389            mSettings.writeLPr();
10390        }
10391
10392        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10393
10394        synchronized (mPackages) {
10395            updatePermissionsLPw(newPackage.packageName, newPackage,
10396                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10397                            ? UPDATE_PERMISSIONS_ALL : 0));
10398            // For system-bundled packages, we assume that installing an upgraded version
10399            // of the package implies that the user actually wants to run that new code,
10400            // so we enable the package.
10401            if (isSystemApp(newPackage)) {
10402                // NB: implicit assumption that system package upgrades apply to all users
10403                if (DEBUG_INSTALL) {
10404                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10405                }
10406                PackageSetting ps = mSettings.mPackages.get(pkgName);
10407                if (ps != null) {
10408                    if (res.origUsers != null) {
10409                        for (int userHandle : res.origUsers) {
10410                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10411                                    userHandle, installerPackageName);
10412                        }
10413                    }
10414                    // Also convey the prior install/uninstall state
10415                    if (allUsers != null && perUserInstalled != null) {
10416                        for (int i = 0; i < allUsers.length; i++) {
10417                            if (DEBUG_INSTALL) {
10418                                Slog.d(TAG, "    user " + allUsers[i]
10419                                        + " => " + perUserInstalled[i]);
10420                            }
10421                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10422                        }
10423                        // these install state changes will be persisted in the
10424                        // upcoming call to mSettings.writeLPr().
10425                    }
10426                }
10427            }
10428            res.name = pkgName;
10429            res.uid = newPackage.applicationInfo.uid;
10430            res.pkg = newPackage;
10431            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10432            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10433            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10434            //to update install status
10435            mSettings.writeLPr();
10436        }
10437    }
10438
10439    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10440        final int installFlags = args.installFlags;
10441        String installerPackageName = args.installerPackageName;
10442        File tmpPackageFile = new File(args.getCodePath());
10443        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10444        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10445        boolean replace = false;
10446        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10447        // Result object to be returned
10448        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10449
10450        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10451        // Retrieve PackageSettings and parse package
10452        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10453                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10454                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10455        PackageParser pp = new PackageParser();
10456        pp.setSeparateProcesses(mSeparateProcesses);
10457        pp.setDisplayMetrics(mMetrics);
10458
10459        final PackageParser.Package pkg;
10460        try {
10461            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10462        } catch (PackageParserException e) {
10463            res.setError("Failed parse during installPackageLI", e);
10464            return;
10465        }
10466
10467        // Mark that we have an install time CPU ABI override.
10468        pkg.cpuAbiOverride = args.abiOverride;
10469
10470        String pkgName = res.name = pkg.packageName;
10471        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10472            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10473                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10474                return;
10475            }
10476        }
10477
10478        try {
10479            pp.collectCertificates(pkg, parseFlags);
10480            pp.collectManifestDigest(pkg);
10481        } catch (PackageParserException e) {
10482            res.setError("Failed collect during installPackageLI", e);
10483            return;
10484        }
10485
10486        /* If the installer passed in a manifest digest, compare it now. */
10487        if (args.manifestDigest != null) {
10488            if (DEBUG_INSTALL) {
10489                final String parsedManifest = pkg.manifestDigest == null ? "null"
10490                        : pkg.manifestDigest.toString();
10491                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10492                        + parsedManifest);
10493            }
10494
10495            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10496                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10497                return;
10498            }
10499        } else if (DEBUG_INSTALL) {
10500            final String parsedManifest = pkg.manifestDigest == null
10501                    ? "null" : pkg.manifestDigest.toString();
10502            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10503        }
10504
10505        // Get rid of all references to package scan path via parser.
10506        pp = null;
10507        String oldCodePath = null;
10508        boolean systemApp = false;
10509        synchronized (mPackages) {
10510            // Check if installing already existing package
10511            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10512                String oldName = mSettings.mRenamedPackages.get(pkgName);
10513                if (pkg.mOriginalPackages != null
10514                        && pkg.mOriginalPackages.contains(oldName)
10515                        && mPackages.containsKey(oldName)) {
10516                    // This package is derived from an original package,
10517                    // and this device has been updating from that original
10518                    // name.  We must continue using the original name, so
10519                    // rename the new package here.
10520                    pkg.setPackageName(oldName);
10521                    pkgName = pkg.packageName;
10522                    replace = true;
10523                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10524                            + oldName + " pkgName=" + pkgName);
10525                } else if (mPackages.containsKey(pkgName)) {
10526                    // This package, under its official name, already exists
10527                    // on the device; we should replace it.
10528                    replace = true;
10529                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10530                }
10531            }
10532
10533            PackageSetting ps = mSettings.mPackages.get(pkgName);
10534            if (ps != null) {
10535                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10536
10537                // Quick sanity check that we're signed correctly if updating;
10538                // we'll check this again later when scanning, but we want to
10539                // bail early here before tripping over redefined permissions.
10540                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10541                    try {
10542                        verifySignaturesLP(ps, pkg);
10543                    } catch (PackageManagerException e) {
10544                        res.setError(e.error, e.getMessage());
10545                        return;
10546                    }
10547                } else {
10548                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10549                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10550                                + pkg.packageName + " upgrade keys do not match the "
10551                                + "previously installed version");
10552                        return;
10553                    }
10554                }
10555
10556                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10557                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10558                    systemApp = (ps.pkg.applicationInfo.flags &
10559                            ApplicationInfo.FLAG_SYSTEM) != 0;
10560                }
10561                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10562            }
10563
10564            // Check whether the newly-scanned package wants to define an already-defined perm
10565            int N = pkg.permissions.size();
10566            for (int i = N-1; i >= 0; i--) {
10567                PackageParser.Permission perm = pkg.permissions.get(i);
10568                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10569                if (bp != null) {
10570                    // If the defining package is signed with our cert, it's okay.  This
10571                    // also includes the "updating the same package" case, of course.
10572                    // "updating same package" could also involve key-rotation.
10573                    final boolean sigsOk;
10574                    if (!bp.sourcePackage.equals(pkg.packageName)
10575                            || !(bp.packageSetting instanceof PackageSetting)
10576                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10577                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10578                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10579                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10580                    } else {
10581                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10582                    }
10583                    if (!sigsOk) {
10584                        // If the owning package is the system itself, we log but allow
10585                        // install to proceed; we fail the install on all other permission
10586                        // redefinitions.
10587                        if (!bp.sourcePackage.equals("android")) {
10588                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10589                                    + pkg.packageName + " attempting to redeclare permission "
10590                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10591                            res.origPermission = perm.info.name;
10592                            res.origPackage = bp.sourcePackage;
10593                            return;
10594                        } else {
10595                            Slog.w(TAG, "Package " + pkg.packageName
10596                                    + " attempting to redeclare system permission "
10597                                    + perm.info.name + "; ignoring new declaration");
10598                            pkg.permissions.remove(i);
10599                        }
10600                    }
10601                }
10602            }
10603
10604        }
10605
10606        if (systemApp && onSd) {
10607            // Disable updates to system apps on sdcard
10608            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10609                    "Cannot install updates to system apps on sdcard");
10610            return;
10611        }
10612
10613        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10614            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10615            return;
10616        }
10617
10618        if (replace) {
10619            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10620                    installerPackageName, res);
10621        } else {
10622            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10623                    args.user, installerPackageName, res);
10624        }
10625        synchronized (mPackages) {
10626            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10627            if (ps != null) {
10628                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10629            }
10630        }
10631    }
10632
10633    private static boolean isForwardLocked(PackageParser.Package pkg) {
10634        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10635    }
10636
10637    private static boolean isForwardLocked(ApplicationInfo info) {
10638        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10639    }
10640
10641    private boolean isForwardLocked(PackageSetting ps) {
10642        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10643    }
10644
10645    private static boolean isMultiArch(PackageSetting ps) {
10646        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10647    }
10648
10649    private static boolean isMultiArch(ApplicationInfo info) {
10650        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10651    }
10652
10653    private static boolean isExternal(PackageParser.Package pkg) {
10654        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10655    }
10656
10657    private static boolean isExternal(PackageSetting ps) {
10658        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10659    }
10660
10661    private static boolean isExternal(ApplicationInfo info) {
10662        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10663    }
10664
10665    private static boolean isSystemApp(PackageParser.Package pkg) {
10666        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10667    }
10668
10669    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10670        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10671    }
10672
10673    private static boolean isSystemApp(ApplicationInfo info) {
10674        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10675    }
10676
10677    private static boolean isSystemApp(PackageSetting ps) {
10678        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10679    }
10680
10681    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10682        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10683    }
10684
10685    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10686        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10687    }
10688
10689    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10690        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10691    }
10692
10693    private int packageFlagsToInstallFlags(PackageSetting ps) {
10694        int installFlags = 0;
10695        if (isExternal(ps)) {
10696            installFlags |= PackageManager.INSTALL_EXTERNAL;
10697        }
10698        if (isForwardLocked(ps)) {
10699            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10700        }
10701        return installFlags;
10702    }
10703
10704    private void deleteTempPackageFiles() {
10705        final FilenameFilter filter = new FilenameFilter() {
10706            public boolean accept(File dir, String name) {
10707                return name.startsWith("vmdl") && name.endsWith(".tmp");
10708            }
10709        };
10710        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10711            file.delete();
10712        }
10713    }
10714
10715    @Override
10716    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10717            int flags) {
10718        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10719                flags);
10720    }
10721
10722    @Override
10723    public void deletePackage(final String packageName,
10724            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10725        mContext.enforceCallingOrSelfPermission(
10726                android.Manifest.permission.DELETE_PACKAGES, null);
10727        final int uid = Binder.getCallingUid();
10728        if (UserHandle.getUserId(uid) != userId) {
10729            mContext.enforceCallingPermission(
10730                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10731                    "deletePackage for user " + userId);
10732        }
10733        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10734            try {
10735                observer.onPackageDeleted(packageName,
10736                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10737            } catch (RemoteException re) {
10738            }
10739            return;
10740        }
10741
10742        boolean uninstallBlocked = false;
10743        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10744            int[] users = sUserManager.getUserIds();
10745            for (int i = 0; i < users.length; ++i) {
10746                if (getBlockUninstallForUser(packageName, users[i])) {
10747                    uninstallBlocked = true;
10748                    break;
10749                }
10750            }
10751        } else {
10752            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10753        }
10754        if (uninstallBlocked) {
10755            try {
10756                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10757                        null);
10758            } catch (RemoteException re) {
10759            }
10760            return;
10761        }
10762
10763        if (DEBUG_REMOVE) {
10764            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10765        }
10766        // Queue up an async operation since the package deletion may take a little while.
10767        mHandler.post(new Runnable() {
10768            public void run() {
10769                mHandler.removeCallbacks(this);
10770                final int returnCode = deletePackageX(packageName, userId, flags);
10771                if (observer != null) {
10772                    try {
10773                        observer.onPackageDeleted(packageName, returnCode, null);
10774                    } catch (RemoteException e) {
10775                        Log.i(TAG, "Observer no longer exists.");
10776                    } //end catch
10777                } //end if
10778            } //end run
10779        });
10780    }
10781
10782    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10783        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10784                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10785        try {
10786            if (dpm != null) {
10787                if (dpm.isDeviceOwner(packageName)) {
10788                    return true;
10789                }
10790                int[] users;
10791                if (userId == UserHandle.USER_ALL) {
10792                    users = sUserManager.getUserIds();
10793                } else {
10794                    users = new int[]{userId};
10795                }
10796                for (int i = 0; i < users.length; ++i) {
10797                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10798                        return true;
10799                    }
10800                }
10801            }
10802        } catch (RemoteException e) {
10803        }
10804        return false;
10805    }
10806
10807    /**
10808     *  This method is an internal method that could be get invoked either
10809     *  to delete an installed package or to clean up a failed installation.
10810     *  After deleting an installed package, a broadcast is sent to notify any
10811     *  listeners that the package has been installed. For cleaning up a failed
10812     *  installation, the broadcast is not necessary since the package's
10813     *  installation wouldn't have sent the initial broadcast either
10814     *  The key steps in deleting a package are
10815     *  deleting the package information in internal structures like mPackages,
10816     *  deleting the packages base directories through installd
10817     *  updating mSettings to reflect current status
10818     *  persisting settings for later use
10819     *  sending a broadcast if necessary
10820     */
10821    private int deletePackageX(String packageName, int userId, int flags) {
10822        final PackageRemovedInfo info = new PackageRemovedInfo();
10823        final boolean res;
10824
10825        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10826                ? UserHandle.ALL : new UserHandle(userId);
10827
10828        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10829            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10830            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10831        }
10832
10833        boolean removedForAllUsers = false;
10834        boolean systemUpdate = false;
10835
10836        // for the uninstall-updates case and restricted profiles, remember the per-
10837        // userhandle installed state
10838        int[] allUsers;
10839        boolean[] perUserInstalled;
10840        synchronized (mPackages) {
10841            PackageSetting ps = mSettings.mPackages.get(packageName);
10842            allUsers = sUserManager.getUserIds();
10843            perUserInstalled = new boolean[allUsers.length];
10844            for (int i = 0; i < allUsers.length; i++) {
10845                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10846            }
10847        }
10848
10849        synchronized (mInstallLock) {
10850            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10851            res = deletePackageLI(packageName, removeForUser,
10852                    true, allUsers, perUserInstalled,
10853                    flags | REMOVE_CHATTY, info, true);
10854            systemUpdate = info.isRemovedPackageSystemUpdate;
10855            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10856                removedForAllUsers = true;
10857            }
10858            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10859                    + " removedForAllUsers=" + removedForAllUsers);
10860        }
10861
10862        if (res) {
10863            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10864
10865            // If the removed package was a system update, the old system package
10866            // was re-enabled; we need to broadcast this information
10867            if (systemUpdate) {
10868                Bundle extras = new Bundle(1);
10869                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10870                        ? info.removedAppId : info.uid);
10871                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10872
10873                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10874                        extras, null, null, null);
10875                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10876                        extras, null, null, null);
10877                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10878                        null, packageName, null, null);
10879            }
10880        }
10881        // Force a gc here.
10882        Runtime.getRuntime().gc();
10883        // Delete the resources here after sending the broadcast to let
10884        // other processes clean up before deleting resources.
10885        if (info.args != null) {
10886            synchronized (mInstallLock) {
10887                info.args.doPostDeleteLI(true);
10888            }
10889        }
10890
10891        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10892    }
10893
10894    static class PackageRemovedInfo {
10895        String removedPackage;
10896        int uid = -1;
10897        int removedAppId = -1;
10898        int[] removedUsers = null;
10899        boolean isRemovedPackageSystemUpdate = false;
10900        // Clean up resources deleted packages.
10901        InstallArgs args = null;
10902
10903        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10904            Bundle extras = new Bundle(1);
10905            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10906            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10907            if (replacing) {
10908                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10909            }
10910            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10911            if (removedPackage != null) {
10912                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10913                        extras, null, null, removedUsers);
10914                if (fullRemove && !replacing) {
10915                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10916                            extras, null, null, removedUsers);
10917                }
10918            }
10919            if (removedAppId >= 0) {
10920                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10921                        removedUsers);
10922            }
10923        }
10924    }
10925
10926    /*
10927     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10928     * flag is not set, the data directory is removed as well.
10929     * make sure this flag is set for partially installed apps. If not its meaningless to
10930     * delete a partially installed application.
10931     */
10932    private void removePackageDataLI(PackageSetting ps,
10933            int[] allUserHandles, boolean[] perUserInstalled,
10934            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10935        String packageName = ps.name;
10936        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10937        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10938        // Retrieve object to delete permissions for shared user later on
10939        final PackageSetting deletedPs;
10940        // reader
10941        synchronized (mPackages) {
10942            deletedPs = mSettings.mPackages.get(packageName);
10943            if (outInfo != null) {
10944                outInfo.removedPackage = packageName;
10945                outInfo.removedUsers = deletedPs != null
10946                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10947                        : null;
10948            }
10949        }
10950        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10951            removeDataDirsLI(packageName);
10952            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10953        }
10954        // writer
10955        synchronized (mPackages) {
10956            if (deletedPs != null) {
10957                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10958                    if (outInfo != null) {
10959                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10960                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10961                    }
10962                    if (deletedPs != null) {
10963                        updatePermissionsLPw(deletedPs.name, null, 0);
10964                        if (deletedPs.sharedUser != null) {
10965                            // remove permissions associated with package
10966                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10967                        }
10968                    }
10969                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10970                }
10971                // make sure to preserve per-user disabled state if this removal was just
10972                // a downgrade of a system app to the factory package
10973                if (allUserHandles != null && perUserInstalled != null) {
10974                    if (DEBUG_REMOVE) {
10975                        Slog.d(TAG, "Propagating install state across downgrade");
10976                    }
10977                    for (int i = 0; i < allUserHandles.length; i++) {
10978                        if (DEBUG_REMOVE) {
10979                            Slog.d(TAG, "    user " + allUserHandles[i]
10980                                    + " => " + perUserInstalled[i]);
10981                        }
10982                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10983                    }
10984                }
10985            }
10986            // can downgrade to reader
10987            if (writeSettings) {
10988                // Save settings now
10989                mSettings.writeLPr();
10990            }
10991        }
10992        if (outInfo != null) {
10993            // A user ID was deleted here. Go through all users and remove it
10994            // from KeyStore.
10995            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10996        }
10997    }
10998
10999    static boolean locationIsPrivileged(File path) {
11000        try {
11001            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11002                    .getCanonicalPath();
11003            return path.getCanonicalPath().startsWith(privilegedAppDir);
11004        } catch (IOException e) {
11005            Slog.e(TAG, "Unable to access code path " + path);
11006        }
11007        return false;
11008    }
11009
11010    /*
11011     * Tries to delete system package.
11012     */
11013    private boolean deleteSystemPackageLI(PackageSetting newPs,
11014            int[] allUserHandles, boolean[] perUserInstalled,
11015            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11016        final boolean applyUserRestrictions
11017                = (allUserHandles != null) && (perUserInstalled != null);
11018        PackageSetting disabledPs = null;
11019        // Confirm if the system package has been updated
11020        // An updated system app can be deleted. This will also have to restore
11021        // the system pkg from system partition
11022        // reader
11023        synchronized (mPackages) {
11024            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11025        }
11026        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11027                + " disabledPs=" + disabledPs);
11028        if (disabledPs == null) {
11029            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11030            return false;
11031        } else if (DEBUG_REMOVE) {
11032            Slog.d(TAG, "Deleting system pkg from data partition");
11033        }
11034        if (DEBUG_REMOVE) {
11035            if (applyUserRestrictions) {
11036                Slog.d(TAG, "Remembering install states:");
11037                for (int i = 0; i < allUserHandles.length; i++) {
11038                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11039                }
11040            }
11041        }
11042        // Delete the updated package
11043        outInfo.isRemovedPackageSystemUpdate = true;
11044        if (disabledPs.versionCode < newPs.versionCode) {
11045            // Delete data for downgrades
11046            flags &= ~PackageManager.DELETE_KEEP_DATA;
11047        } else {
11048            // Preserve data by setting flag
11049            flags |= PackageManager.DELETE_KEEP_DATA;
11050        }
11051        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11052                allUserHandles, perUserInstalled, outInfo, writeSettings);
11053        if (!ret) {
11054            return false;
11055        }
11056        // writer
11057        synchronized (mPackages) {
11058            // Reinstate the old system package
11059            mSettings.enableSystemPackageLPw(newPs.name);
11060            // Remove any native libraries from the upgraded package.
11061            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11062        }
11063        // Install the system package
11064        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11065        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11066        if (locationIsPrivileged(disabledPs.codePath)) {
11067            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11068        }
11069
11070        final PackageParser.Package newPkg;
11071        try {
11072            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11073        } catch (PackageManagerException e) {
11074            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11075            return false;
11076        }
11077
11078        // writer
11079        synchronized (mPackages) {
11080            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11081            updatePermissionsLPw(newPkg.packageName, newPkg,
11082                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11083            if (applyUserRestrictions) {
11084                if (DEBUG_REMOVE) {
11085                    Slog.d(TAG, "Propagating install state across reinstall");
11086                }
11087                for (int i = 0; i < allUserHandles.length; i++) {
11088                    if (DEBUG_REMOVE) {
11089                        Slog.d(TAG, "    user " + allUserHandles[i]
11090                                + " => " + perUserInstalled[i]);
11091                    }
11092                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11093                }
11094                // Regardless of writeSettings we need to ensure that this restriction
11095                // state propagation is persisted
11096                mSettings.writeAllUsersPackageRestrictionsLPr();
11097            }
11098            // can downgrade to reader here
11099            if (writeSettings) {
11100                mSettings.writeLPr();
11101            }
11102        }
11103        return true;
11104    }
11105
11106    private boolean deleteInstalledPackageLI(PackageSetting ps,
11107            boolean deleteCodeAndResources, int flags,
11108            int[] allUserHandles, boolean[] perUserInstalled,
11109            PackageRemovedInfo outInfo, boolean writeSettings) {
11110        if (outInfo != null) {
11111            outInfo.uid = ps.appId;
11112        }
11113
11114        // Delete package data from internal structures and also remove data if flag is set
11115        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11116
11117        // Delete application code and resources
11118        if (deleteCodeAndResources && (outInfo != null)) {
11119            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11120                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11121                    getAppDexInstructionSets(ps));
11122            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11123        }
11124        return true;
11125    }
11126
11127    @Override
11128    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11129            int userId) {
11130        mContext.enforceCallingOrSelfPermission(
11131                android.Manifest.permission.DELETE_PACKAGES, null);
11132        synchronized (mPackages) {
11133            PackageSetting ps = mSettings.mPackages.get(packageName);
11134            if (ps == null) {
11135                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11136                return false;
11137            }
11138            if (!ps.getInstalled(userId)) {
11139                // Can't block uninstall for an app that is not installed or enabled.
11140                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11141                return false;
11142            }
11143            ps.setBlockUninstall(blockUninstall, userId);
11144            mSettings.writePackageRestrictionsLPr(userId);
11145        }
11146        return true;
11147    }
11148
11149    @Override
11150    public boolean getBlockUninstallForUser(String packageName, int userId) {
11151        synchronized (mPackages) {
11152            PackageSetting ps = mSettings.mPackages.get(packageName);
11153            if (ps == null) {
11154                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11155                return false;
11156            }
11157            return ps.getBlockUninstall(userId);
11158        }
11159    }
11160
11161    /*
11162     * This method handles package deletion in general
11163     */
11164    private boolean deletePackageLI(String packageName, UserHandle user,
11165            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11166            int flags, PackageRemovedInfo outInfo,
11167            boolean writeSettings) {
11168        if (packageName == null) {
11169            Slog.w(TAG, "Attempt to delete null packageName.");
11170            return false;
11171        }
11172        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11173        PackageSetting ps;
11174        boolean dataOnly = false;
11175        int removeUser = -1;
11176        int appId = -1;
11177        synchronized (mPackages) {
11178            ps = mSettings.mPackages.get(packageName);
11179            if (ps == null) {
11180                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11181                return false;
11182            }
11183            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11184                    && user.getIdentifier() != UserHandle.USER_ALL) {
11185                // The caller is asking that the package only be deleted for a single
11186                // user.  To do this, we just mark its uninstalled state and delete
11187                // its data.  If this is a system app, we only allow this to happen if
11188                // they have set the special DELETE_SYSTEM_APP which requests different
11189                // semantics than normal for uninstalling system apps.
11190                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11191                ps.setUserState(user.getIdentifier(),
11192                        COMPONENT_ENABLED_STATE_DEFAULT,
11193                        false, //installed
11194                        true,  //stopped
11195                        true,  //notLaunched
11196                        false, //hidden
11197                        null, null, null,
11198                        false // blockUninstall
11199                        );
11200                if (!isSystemApp(ps)) {
11201                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11202                        // Other user still have this package installed, so all
11203                        // we need to do is clear this user's data and save that
11204                        // it is uninstalled.
11205                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11206                        removeUser = user.getIdentifier();
11207                        appId = ps.appId;
11208                        mSettings.writePackageRestrictionsLPr(removeUser);
11209                    } else {
11210                        // We need to set it back to 'installed' so the uninstall
11211                        // broadcasts will be sent correctly.
11212                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11213                        ps.setInstalled(true, user.getIdentifier());
11214                    }
11215                } else {
11216                    // This is a system app, so we assume that the
11217                    // other users still have this package installed, so all
11218                    // we need to do is clear this user's data and save that
11219                    // it is uninstalled.
11220                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11221                    removeUser = user.getIdentifier();
11222                    appId = ps.appId;
11223                    mSettings.writePackageRestrictionsLPr(removeUser);
11224                }
11225            }
11226        }
11227
11228        if (removeUser >= 0) {
11229            // From above, we determined that we are deleting this only
11230            // for a single user.  Continue the work here.
11231            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11232            if (outInfo != null) {
11233                outInfo.removedPackage = packageName;
11234                outInfo.removedAppId = appId;
11235                outInfo.removedUsers = new int[] {removeUser};
11236            }
11237            mInstaller.clearUserData(packageName, removeUser);
11238            removeKeystoreDataIfNeeded(removeUser, appId);
11239            schedulePackageCleaning(packageName, removeUser, false);
11240            return true;
11241        }
11242
11243        if (dataOnly) {
11244            // Delete application data first
11245            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11246            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11247            return true;
11248        }
11249
11250        boolean ret = false;
11251        if (isSystemApp(ps)) {
11252            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11253            // When an updated system application is deleted we delete the existing resources as well and
11254            // fall back to existing code in system partition
11255            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11256                    flags, outInfo, writeSettings);
11257        } else {
11258            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11259            // Kill application pre-emptively especially for apps on sd.
11260            killApplication(packageName, ps.appId, "uninstall pkg");
11261            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11262                    allUserHandles, perUserInstalled,
11263                    outInfo, writeSettings);
11264        }
11265
11266        return ret;
11267    }
11268
11269    private final class ClearStorageConnection implements ServiceConnection {
11270        IMediaContainerService mContainerService;
11271
11272        @Override
11273        public void onServiceConnected(ComponentName name, IBinder service) {
11274            synchronized (this) {
11275                mContainerService = IMediaContainerService.Stub.asInterface(service);
11276                notifyAll();
11277            }
11278        }
11279
11280        @Override
11281        public void onServiceDisconnected(ComponentName name) {
11282        }
11283    }
11284
11285    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11286        final boolean mounted;
11287        if (Environment.isExternalStorageEmulated()) {
11288            mounted = true;
11289        } else {
11290            final String status = Environment.getExternalStorageState();
11291
11292            mounted = status.equals(Environment.MEDIA_MOUNTED)
11293                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11294        }
11295
11296        if (!mounted) {
11297            return;
11298        }
11299
11300        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11301        int[] users;
11302        if (userId == UserHandle.USER_ALL) {
11303            users = sUserManager.getUserIds();
11304        } else {
11305            users = new int[] { userId };
11306        }
11307        final ClearStorageConnection conn = new ClearStorageConnection();
11308        if (mContext.bindServiceAsUser(
11309                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11310            try {
11311                for (int curUser : users) {
11312                    long timeout = SystemClock.uptimeMillis() + 5000;
11313                    synchronized (conn) {
11314                        long now = SystemClock.uptimeMillis();
11315                        while (conn.mContainerService == null && now < timeout) {
11316                            try {
11317                                conn.wait(timeout - now);
11318                            } catch (InterruptedException e) {
11319                            }
11320                        }
11321                    }
11322                    if (conn.mContainerService == null) {
11323                        return;
11324                    }
11325
11326                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11327                    clearDirectory(conn.mContainerService,
11328                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11329                    if (allData) {
11330                        clearDirectory(conn.mContainerService,
11331                                userEnv.buildExternalStorageAppDataDirs(packageName));
11332                        clearDirectory(conn.mContainerService,
11333                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11334                    }
11335                }
11336            } finally {
11337                mContext.unbindService(conn);
11338            }
11339        }
11340    }
11341
11342    @Override
11343    public void clearApplicationUserData(final String packageName,
11344            final IPackageDataObserver observer, final int userId) {
11345        mContext.enforceCallingOrSelfPermission(
11346                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11347        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11348        // Queue up an async operation since the package deletion may take a little while.
11349        mHandler.post(new Runnable() {
11350            public void run() {
11351                mHandler.removeCallbacks(this);
11352                final boolean succeeded;
11353                synchronized (mInstallLock) {
11354                    succeeded = clearApplicationUserDataLI(packageName, userId);
11355                }
11356                clearExternalStorageDataSync(packageName, userId, true);
11357                if (succeeded) {
11358                    // invoke DeviceStorageMonitor's update method to clear any notifications
11359                    DeviceStorageMonitorInternal
11360                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11361                    if (dsm != null) {
11362                        dsm.checkMemory();
11363                    }
11364                }
11365                if(observer != null) {
11366                    try {
11367                        observer.onRemoveCompleted(packageName, succeeded);
11368                    } catch (RemoteException e) {
11369                        Log.i(TAG, "Observer no longer exists.");
11370                    }
11371                } //end if observer
11372            } //end run
11373        });
11374    }
11375
11376    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11377        if (packageName == null) {
11378            Slog.w(TAG, "Attempt to delete null packageName.");
11379            return false;
11380        }
11381
11382        // Try finding details about the requested package
11383        PackageParser.Package pkg;
11384        synchronized (mPackages) {
11385            pkg = mPackages.get(packageName);
11386            if (pkg == null) {
11387                final PackageSetting ps = mSettings.mPackages.get(packageName);
11388                if (ps != null) {
11389                    pkg = ps.pkg;
11390                }
11391            }
11392        }
11393
11394        if (pkg == null) {
11395            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11396        }
11397
11398        // Always delete data directories for package, even if we found no other
11399        // record of app. This helps users recover from UID mismatches without
11400        // resorting to a full data wipe.
11401        int retCode = mInstaller.clearUserData(packageName, userId);
11402        if (retCode < 0) {
11403            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11404            return false;
11405        }
11406
11407        if (pkg == null) {
11408            return false;
11409        }
11410
11411        if (pkg != null && pkg.applicationInfo != null) {
11412            final int appId = pkg.applicationInfo.uid;
11413            removeKeystoreDataIfNeeded(userId, appId);
11414        }
11415
11416        // Create a native library symlink only if we have native libraries
11417        // and if the native libraries are 32 bit libraries. We do not provide
11418        // this symlink for 64 bit libraries.
11419        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11420                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11421            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11422            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11423                Slog.w(TAG, "Failed linking native library dir");
11424                return false;
11425            }
11426        }
11427
11428        return true;
11429    }
11430
11431    /**
11432     * Remove entries from the keystore daemon. Will only remove it if the
11433     * {@code appId} is valid.
11434     */
11435    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11436        if (appId < 0) {
11437            return;
11438        }
11439
11440        final KeyStore keyStore = KeyStore.getInstance();
11441        if (keyStore != null) {
11442            if (userId == UserHandle.USER_ALL) {
11443                for (final int individual : sUserManager.getUserIds()) {
11444                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11445                }
11446            } else {
11447                keyStore.clearUid(UserHandle.getUid(userId, appId));
11448            }
11449        } else {
11450            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11451        }
11452    }
11453
11454    @Override
11455    public void deleteApplicationCacheFiles(final String packageName,
11456            final IPackageDataObserver observer) {
11457        mContext.enforceCallingOrSelfPermission(
11458                android.Manifest.permission.DELETE_CACHE_FILES, null);
11459        // Queue up an async operation since the package deletion may take a little while.
11460        final int userId = UserHandle.getCallingUserId();
11461        mHandler.post(new Runnable() {
11462            public void run() {
11463                mHandler.removeCallbacks(this);
11464                final boolean succeded;
11465                synchronized (mInstallLock) {
11466                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11467                }
11468                clearExternalStorageDataSync(packageName, userId, false);
11469                if(observer != null) {
11470                    try {
11471                        observer.onRemoveCompleted(packageName, succeded);
11472                    } catch (RemoteException e) {
11473                        Log.i(TAG, "Observer no longer exists.");
11474                    }
11475                } //end if observer
11476            } //end run
11477        });
11478    }
11479
11480    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11481        if (packageName == null) {
11482            Slog.w(TAG, "Attempt to delete null packageName.");
11483            return false;
11484        }
11485        PackageParser.Package p;
11486        synchronized (mPackages) {
11487            p = mPackages.get(packageName);
11488        }
11489        if (p == null) {
11490            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11491            return false;
11492        }
11493        final ApplicationInfo applicationInfo = p.applicationInfo;
11494        if (applicationInfo == null) {
11495            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11496            return false;
11497        }
11498        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11499        if (retCode < 0) {
11500            Slog.w(TAG, "Couldn't remove cache files for package: "
11501                       + packageName + " u" + userId);
11502            return false;
11503        }
11504        return true;
11505    }
11506
11507    @Override
11508    public void getPackageSizeInfo(final String packageName, int userHandle,
11509            final IPackageStatsObserver observer) {
11510        mContext.enforceCallingOrSelfPermission(
11511                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11512        if (packageName == null) {
11513            throw new IllegalArgumentException("Attempt to get size of null packageName");
11514        }
11515
11516        PackageStats stats = new PackageStats(packageName, userHandle);
11517
11518        /*
11519         * Queue up an async operation since the package measurement may take a
11520         * little while.
11521         */
11522        Message msg = mHandler.obtainMessage(INIT_COPY);
11523        msg.obj = new MeasureParams(stats, observer);
11524        mHandler.sendMessage(msg);
11525    }
11526
11527    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11528            PackageStats pStats) {
11529        if (packageName == null) {
11530            Slog.w(TAG, "Attempt to get size of null packageName.");
11531            return false;
11532        }
11533        PackageParser.Package p;
11534        boolean dataOnly = false;
11535        String libDirRoot = null;
11536        String asecPath = null;
11537        PackageSetting ps = null;
11538        synchronized (mPackages) {
11539            p = mPackages.get(packageName);
11540            ps = mSettings.mPackages.get(packageName);
11541            if(p == null) {
11542                dataOnly = true;
11543                if((ps == null) || (ps.pkg == null)) {
11544                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11545                    return false;
11546                }
11547                p = ps.pkg;
11548            }
11549            if (ps != null) {
11550                libDirRoot = ps.legacyNativeLibraryPathString;
11551            }
11552            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11553                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11554                if (secureContainerId != null) {
11555                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11556                }
11557            }
11558        }
11559        String publicSrcDir = null;
11560        if(!dataOnly) {
11561            final ApplicationInfo applicationInfo = p.applicationInfo;
11562            if (applicationInfo == null) {
11563                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11564                return false;
11565            }
11566            if (isForwardLocked(p)) {
11567                publicSrcDir = applicationInfo.getBaseResourcePath();
11568            }
11569        }
11570        // TODO: extend to measure size of split APKs
11571        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11572        // not just the first level.
11573        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11574        // just the primary.
11575        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11576        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11577                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11578        if (res < 0) {
11579            return false;
11580        }
11581
11582        // Fix-up for forward-locked applications in ASEC containers.
11583        if (!isExternal(p)) {
11584            pStats.codeSize += pStats.externalCodeSize;
11585            pStats.externalCodeSize = 0L;
11586        }
11587
11588        return true;
11589    }
11590
11591
11592    @Override
11593    public void addPackageToPreferred(String packageName) {
11594        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11595    }
11596
11597    @Override
11598    public void removePackageFromPreferred(String packageName) {
11599        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11600    }
11601
11602    @Override
11603    public List<PackageInfo> getPreferredPackages(int flags) {
11604        return new ArrayList<PackageInfo>();
11605    }
11606
11607    private int getUidTargetSdkVersionLockedLPr(int uid) {
11608        Object obj = mSettings.getUserIdLPr(uid);
11609        if (obj instanceof SharedUserSetting) {
11610            final SharedUserSetting sus = (SharedUserSetting) obj;
11611            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11612            final Iterator<PackageSetting> it = sus.packages.iterator();
11613            while (it.hasNext()) {
11614                final PackageSetting ps = it.next();
11615                if (ps.pkg != null) {
11616                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11617                    if (v < vers) vers = v;
11618                }
11619            }
11620            return vers;
11621        } else if (obj instanceof PackageSetting) {
11622            final PackageSetting ps = (PackageSetting) obj;
11623            if (ps.pkg != null) {
11624                return ps.pkg.applicationInfo.targetSdkVersion;
11625            }
11626        }
11627        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11628    }
11629
11630    @Override
11631    public void addPreferredActivity(IntentFilter filter, int match,
11632            ComponentName[] set, ComponentName activity, int userId) {
11633        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11634                "Adding preferred");
11635    }
11636
11637    private void addPreferredActivityInternal(IntentFilter filter, int match,
11638            ComponentName[] set, ComponentName activity, boolean always, int userId,
11639            String opname) {
11640        // writer
11641        int callingUid = Binder.getCallingUid();
11642        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11643        if (filter.countActions() == 0) {
11644            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11645            return;
11646        }
11647        synchronized (mPackages) {
11648            if (mContext.checkCallingOrSelfPermission(
11649                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11650                    != PackageManager.PERMISSION_GRANTED) {
11651                if (getUidTargetSdkVersionLockedLPr(callingUid)
11652                        < Build.VERSION_CODES.FROYO) {
11653                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11654                            + callingUid);
11655                    return;
11656                }
11657                mContext.enforceCallingOrSelfPermission(
11658                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11659            }
11660
11661            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11662            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11663                    + userId + ":");
11664            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11665            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11666            scheduleWritePackageRestrictionsLocked(userId);
11667        }
11668    }
11669
11670    @Override
11671    public void replacePreferredActivity(IntentFilter filter, int match,
11672            ComponentName[] set, ComponentName activity, int userId) {
11673        if (filter.countActions() != 1) {
11674            throw new IllegalArgumentException(
11675                    "replacePreferredActivity expects filter to have only 1 action.");
11676        }
11677        if (filter.countDataAuthorities() != 0
11678                || filter.countDataPaths() != 0
11679                || filter.countDataSchemes() > 1
11680                || filter.countDataTypes() != 0) {
11681            throw new IllegalArgumentException(
11682                    "replacePreferredActivity expects filter to have no data authorities, " +
11683                    "paths, or types; and at most one scheme.");
11684        }
11685
11686        final int callingUid = Binder.getCallingUid();
11687        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11688        synchronized (mPackages) {
11689            if (mContext.checkCallingOrSelfPermission(
11690                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11691                    != PackageManager.PERMISSION_GRANTED) {
11692                if (getUidTargetSdkVersionLockedLPr(callingUid)
11693                        < Build.VERSION_CODES.FROYO) {
11694                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11695                            + Binder.getCallingUid());
11696                    return;
11697                }
11698                mContext.enforceCallingOrSelfPermission(
11699                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11700            }
11701
11702            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11703            if (pir != null) {
11704                // Get all of the existing entries that exactly match this filter.
11705                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11706                if (existing != null && existing.size() == 1) {
11707                    PreferredActivity cur = existing.get(0);
11708                    if (DEBUG_PREFERRED) {
11709                        Slog.i(TAG, "Checking replace of preferred:");
11710                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11711                        if (!cur.mPref.mAlways) {
11712                            Slog.i(TAG, "  -- CUR; not mAlways!");
11713                        } else {
11714                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11715                            Slog.i(TAG, "  -- CUR: mSet="
11716                                    + Arrays.toString(cur.mPref.mSetComponents));
11717                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11718                            Slog.i(TAG, "  -- NEW: mMatch="
11719                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11720                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11721                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11722                        }
11723                    }
11724                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11725                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11726                            && cur.mPref.sameSet(set)) {
11727                        // Setting the preferred activity to what it happens to be already
11728                        if (DEBUG_PREFERRED) {
11729                            Slog.i(TAG, "Replacing with same preferred activity "
11730                                    + cur.mPref.mShortComponent + " for user "
11731                                    + userId + ":");
11732                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11733                        }
11734                        return;
11735                    }
11736                }
11737
11738                if (existing != null) {
11739                    if (DEBUG_PREFERRED) {
11740                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11741                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11742                    }
11743                    for (int i = 0; i < existing.size(); i++) {
11744                        PreferredActivity pa = existing.get(i);
11745                        if (DEBUG_PREFERRED) {
11746                            Slog.i(TAG, "Removing existing preferred activity "
11747                                    + pa.mPref.mComponent + ":");
11748                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11749                        }
11750                        pir.removeFilter(pa);
11751                    }
11752                }
11753            }
11754            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11755                    "Replacing preferred");
11756        }
11757    }
11758
11759    @Override
11760    public void clearPackagePreferredActivities(String packageName) {
11761        final int uid = Binder.getCallingUid();
11762        // writer
11763        synchronized (mPackages) {
11764            PackageParser.Package pkg = mPackages.get(packageName);
11765            if (pkg == null || pkg.applicationInfo.uid != uid) {
11766                if (mContext.checkCallingOrSelfPermission(
11767                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11768                        != PackageManager.PERMISSION_GRANTED) {
11769                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11770                            < Build.VERSION_CODES.FROYO) {
11771                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11772                                + Binder.getCallingUid());
11773                        return;
11774                    }
11775                    mContext.enforceCallingOrSelfPermission(
11776                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11777                }
11778            }
11779
11780            int user = UserHandle.getCallingUserId();
11781            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11782                scheduleWritePackageRestrictionsLocked(user);
11783            }
11784        }
11785    }
11786
11787    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11788    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11789        ArrayList<PreferredActivity> removed = null;
11790        boolean changed = false;
11791        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11792            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11793            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11794            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11795                continue;
11796            }
11797            Iterator<PreferredActivity> it = pir.filterIterator();
11798            while (it.hasNext()) {
11799                PreferredActivity pa = it.next();
11800                // Mark entry for removal only if it matches the package name
11801                // and the entry is of type "always".
11802                if (packageName == null ||
11803                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11804                                && pa.mPref.mAlways)) {
11805                    if (removed == null) {
11806                        removed = new ArrayList<PreferredActivity>();
11807                    }
11808                    removed.add(pa);
11809                }
11810            }
11811            if (removed != null) {
11812                for (int j=0; j<removed.size(); j++) {
11813                    PreferredActivity pa = removed.get(j);
11814                    pir.removeFilter(pa);
11815                }
11816                changed = true;
11817            }
11818        }
11819        return changed;
11820    }
11821
11822    @Override
11823    public void resetPreferredActivities(int userId) {
11824        /* TODO: Actually use userId. Why is it being passed in? */
11825        mContext.enforceCallingOrSelfPermission(
11826                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11827        // writer
11828        synchronized (mPackages) {
11829            int user = UserHandle.getCallingUserId();
11830            clearPackagePreferredActivitiesLPw(null, user);
11831            mSettings.readDefaultPreferredAppsLPw(this, user);
11832            scheduleWritePackageRestrictionsLocked(user);
11833        }
11834    }
11835
11836    @Override
11837    public int getPreferredActivities(List<IntentFilter> outFilters,
11838            List<ComponentName> outActivities, String packageName) {
11839
11840        int num = 0;
11841        final int userId = UserHandle.getCallingUserId();
11842        // reader
11843        synchronized (mPackages) {
11844            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11845            if (pir != null) {
11846                final Iterator<PreferredActivity> it = pir.filterIterator();
11847                while (it.hasNext()) {
11848                    final PreferredActivity pa = it.next();
11849                    if (packageName == null
11850                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11851                                    && pa.mPref.mAlways)) {
11852                        if (outFilters != null) {
11853                            outFilters.add(new IntentFilter(pa));
11854                        }
11855                        if (outActivities != null) {
11856                            outActivities.add(pa.mPref.mComponent);
11857                        }
11858                    }
11859                }
11860            }
11861        }
11862
11863        return num;
11864    }
11865
11866    @Override
11867    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11868            int userId) {
11869        int callingUid = Binder.getCallingUid();
11870        if (callingUid != Process.SYSTEM_UID) {
11871            throw new SecurityException(
11872                    "addPersistentPreferredActivity can only be run by the system");
11873        }
11874        if (filter.countActions() == 0) {
11875            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11876            return;
11877        }
11878        synchronized (mPackages) {
11879            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11880                    " :");
11881            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11882            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11883                    new PersistentPreferredActivity(filter, activity));
11884            scheduleWritePackageRestrictionsLocked(userId);
11885        }
11886    }
11887
11888    @Override
11889    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11890        int callingUid = Binder.getCallingUid();
11891        if (callingUid != Process.SYSTEM_UID) {
11892            throw new SecurityException(
11893                    "clearPackagePersistentPreferredActivities can only be run by the system");
11894        }
11895        ArrayList<PersistentPreferredActivity> removed = null;
11896        boolean changed = false;
11897        synchronized (mPackages) {
11898            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11899                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11900                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11901                        .valueAt(i);
11902                if (userId != thisUserId) {
11903                    continue;
11904                }
11905                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11906                while (it.hasNext()) {
11907                    PersistentPreferredActivity ppa = it.next();
11908                    // Mark entry for removal only if it matches the package name.
11909                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11910                        if (removed == null) {
11911                            removed = new ArrayList<PersistentPreferredActivity>();
11912                        }
11913                        removed.add(ppa);
11914                    }
11915                }
11916                if (removed != null) {
11917                    for (int j=0; j<removed.size(); j++) {
11918                        PersistentPreferredActivity ppa = removed.get(j);
11919                        ppir.removeFilter(ppa);
11920                    }
11921                    changed = true;
11922                }
11923            }
11924
11925            if (changed) {
11926                scheduleWritePackageRestrictionsLocked(userId);
11927            }
11928        }
11929    }
11930
11931    @Override
11932    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11933            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11934        mContext.enforceCallingOrSelfPermission(
11935                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11936        int callingUid = Binder.getCallingUid();
11937        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11938        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11939        if (intentFilter.countActions() == 0) {
11940            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11941            return;
11942        }
11943        synchronized (mPackages) {
11944            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11945                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11946            CrossProfileIntentResolver resolver =
11947                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11948            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11949            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11950            if (existing != null) {
11951                int size = existing.size();
11952                for (int i = 0; i < size; i++) {
11953                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11954                        return;
11955                    }
11956                }
11957            }
11958            resolver.addFilter(newFilter);
11959            scheduleWritePackageRestrictionsLocked(sourceUserId);
11960        }
11961    }
11962
11963    @Override
11964    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11965            int ownerUserId) {
11966        mContext.enforceCallingOrSelfPermission(
11967                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11968        int callingUid = Binder.getCallingUid();
11969        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11970        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11971        int callingUserId = UserHandle.getUserId(callingUid);
11972        synchronized (mPackages) {
11973            CrossProfileIntentResolver resolver =
11974                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11975            ArraySet<CrossProfileIntentFilter> set =
11976                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11977            for (CrossProfileIntentFilter filter : set) {
11978                if (filter.getOwnerPackage().equals(ownerPackage)
11979                        && filter.getOwnerUserId() == callingUserId) {
11980                    resolver.removeFilter(filter);
11981                }
11982            }
11983            scheduleWritePackageRestrictionsLocked(sourceUserId);
11984        }
11985    }
11986
11987    // Enforcing that callingUid is owning pkg on userId
11988    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11989        // The system owns everything.
11990        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11991            return;
11992        }
11993        int callingUserId = UserHandle.getUserId(callingUid);
11994        if (callingUserId != userId) {
11995            throw new SecurityException("calling uid " + callingUid
11996                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11997                    + callingUserId);
11998        }
11999        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12000        if (pi == null) {
12001            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12002                    + callingUserId);
12003        }
12004        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12005            throw new SecurityException("Calling uid " + callingUid
12006                    + " does not own package " + pkg);
12007        }
12008    }
12009
12010    @Override
12011    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12012        Intent intent = new Intent(Intent.ACTION_MAIN);
12013        intent.addCategory(Intent.CATEGORY_HOME);
12014
12015        final int callingUserId = UserHandle.getCallingUserId();
12016        List<ResolveInfo> list = queryIntentActivities(intent, null,
12017                PackageManager.GET_META_DATA, callingUserId);
12018        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12019                true, false, false, callingUserId);
12020
12021        allHomeCandidates.clear();
12022        if (list != null) {
12023            for (ResolveInfo ri : list) {
12024                allHomeCandidates.add(ri);
12025            }
12026        }
12027        return (preferred == null || preferred.activityInfo == null)
12028                ? null
12029                : new ComponentName(preferred.activityInfo.packageName,
12030                        preferred.activityInfo.name);
12031    }
12032
12033    @Override
12034    public void setApplicationEnabledSetting(String appPackageName,
12035            int newState, int flags, int userId, String callingPackage) {
12036        if (!sUserManager.exists(userId)) return;
12037        if (callingPackage == null) {
12038            callingPackage = Integer.toString(Binder.getCallingUid());
12039        }
12040        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12041    }
12042
12043    @Override
12044    public void setComponentEnabledSetting(ComponentName componentName,
12045            int newState, int flags, int userId) {
12046        if (!sUserManager.exists(userId)) return;
12047        setEnabledSetting(componentName.getPackageName(),
12048                componentName.getClassName(), newState, flags, userId, null);
12049    }
12050
12051    private void setEnabledSetting(final String packageName, String className, int newState,
12052            final int flags, int userId, String callingPackage) {
12053        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12054              || newState == COMPONENT_ENABLED_STATE_ENABLED
12055              || newState == COMPONENT_ENABLED_STATE_DISABLED
12056              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12057              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12058            throw new IllegalArgumentException("Invalid new component state: "
12059                    + newState);
12060        }
12061        PackageSetting pkgSetting;
12062        final int uid = Binder.getCallingUid();
12063        final int permission = mContext.checkCallingOrSelfPermission(
12064                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12065        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12066        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12067        boolean sendNow = false;
12068        boolean isApp = (className == null);
12069        String componentName = isApp ? packageName : className;
12070        int packageUid = -1;
12071        ArrayList<String> components;
12072
12073        // writer
12074        synchronized (mPackages) {
12075            pkgSetting = mSettings.mPackages.get(packageName);
12076            if (pkgSetting == null) {
12077                if (className == null) {
12078                    throw new IllegalArgumentException(
12079                            "Unknown package: " + packageName);
12080                }
12081                throw new IllegalArgumentException(
12082                        "Unknown component: " + packageName
12083                        + "/" + className);
12084            }
12085            // Allow root and verify that userId is not being specified by a different user
12086            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12087                throw new SecurityException(
12088                        "Permission Denial: attempt to change component state from pid="
12089                        + Binder.getCallingPid()
12090                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12091            }
12092            if (className == null) {
12093                // We're dealing with an application/package level state change
12094                if (pkgSetting.getEnabled(userId) == newState) {
12095                    // Nothing to do
12096                    return;
12097                }
12098                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12099                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12100                    // Don't care about who enables an app.
12101                    callingPackage = null;
12102                }
12103                pkgSetting.setEnabled(newState, userId, callingPackage);
12104                // pkgSetting.pkg.mSetEnabled = newState;
12105            } else {
12106                // We're dealing with a component level state change
12107                // First, verify that this is a valid class name.
12108                PackageParser.Package pkg = pkgSetting.pkg;
12109                if (pkg == null || !pkg.hasComponentClassName(className)) {
12110                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12111                        throw new IllegalArgumentException("Component class " + className
12112                                + " does not exist in " + packageName);
12113                    } else {
12114                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12115                                + className + " does not exist in " + packageName);
12116                    }
12117                }
12118                switch (newState) {
12119                case COMPONENT_ENABLED_STATE_ENABLED:
12120                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12121                        return;
12122                    }
12123                    break;
12124                case COMPONENT_ENABLED_STATE_DISABLED:
12125                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12126                        return;
12127                    }
12128                    break;
12129                case COMPONENT_ENABLED_STATE_DEFAULT:
12130                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12131                        return;
12132                    }
12133                    break;
12134                default:
12135                    Slog.e(TAG, "Invalid new component state: " + newState);
12136                    return;
12137                }
12138            }
12139            mSettings.writePackageRestrictionsLPr(userId);
12140            components = mPendingBroadcasts.get(userId, packageName);
12141            final boolean newPackage = components == null;
12142            if (newPackage) {
12143                components = new ArrayList<String>();
12144            }
12145            if (!components.contains(componentName)) {
12146                components.add(componentName);
12147            }
12148            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12149                sendNow = true;
12150                // Purge entry from pending broadcast list if another one exists already
12151                // since we are sending one right away.
12152                mPendingBroadcasts.remove(userId, packageName);
12153            } else {
12154                if (newPackage) {
12155                    mPendingBroadcasts.put(userId, packageName, components);
12156                }
12157                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12158                    // Schedule a message
12159                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12160                }
12161            }
12162        }
12163
12164        long callingId = Binder.clearCallingIdentity();
12165        try {
12166            if (sendNow) {
12167                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12168                sendPackageChangedBroadcast(packageName,
12169                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12170            }
12171        } finally {
12172            Binder.restoreCallingIdentity(callingId);
12173        }
12174    }
12175
12176    private void sendPackageChangedBroadcast(String packageName,
12177            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12178        if (DEBUG_INSTALL)
12179            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12180                    + componentNames);
12181        Bundle extras = new Bundle(4);
12182        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12183        String nameList[] = new String[componentNames.size()];
12184        componentNames.toArray(nameList);
12185        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12186        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12187        extras.putInt(Intent.EXTRA_UID, packageUid);
12188        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12189                new int[] {UserHandle.getUserId(packageUid)});
12190    }
12191
12192    @Override
12193    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12194        if (!sUserManager.exists(userId)) return;
12195        final int uid = Binder.getCallingUid();
12196        final int permission = mContext.checkCallingOrSelfPermission(
12197                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12198        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12199        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12200        // writer
12201        synchronized (mPackages) {
12202            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12203                    uid, userId)) {
12204                scheduleWritePackageRestrictionsLocked(userId);
12205            }
12206        }
12207    }
12208
12209    @Override
12210    public String getInstallerPackageName(String packageName) {
12211        // reader
12212        synchronized (mPackages) {
12213            return mSettings.getInstallerPackageNameLPr(packageName);
12214        }
12215    }
12216
12217    @Override
12218    public int getApplicationEnabledSetting(String packageName, int userId) {
12219        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12220        int uid = Binder.getCallingUid();
12221        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12222        // reader
12223        synchronized (mPackages) {
12224            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12225        }
12226    }
12227
12228    @Override
12229    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12230        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12231        int uid = Binder.getCallingUid();
12232        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12233        // reader
12234        synchronized (mPackages) {
12235            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12236        }
12237    }
12238
12239    @Override
12240    public void enterSafeMode() {
12241        enforceSystemOrRoot("Only the system can request entering safe mode");
12242
12243        if (!mSystemReady) {
12244            mSafeMode = true;
12245        }
12246    }
12247
12248    @Override
12249    public void systemReady() {
12250        mSystemReady = true;
12251
12252        // Read the compatibilty setting when the system is ready.
12253        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12254                mContext.getContentResolver(),
12255                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12256        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12257        if (DEBUG_SETTINGS) {
12258            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12259        }
12260
12261        synchronized (mPackages) {
12262            // Verify that all of the preferred activity components actually
12263            // exist.  It is possible for applications to be updated and at
12264            // that point remove a previously declared activity component that
12265            // had been set as a preferred activity.  We try to clean this up
12266            // the next time we encounter that preferred activity, but it is
12267            // possible for the user flow to never be able to return to that
12268            // situation so here we do a sanity check to make sure we haven't
12269            // left any junk around.
12270            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12271            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12272                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12273                removed.clear();
12274                for (PreferredActivity pa : pir.filterSet()) {
12275                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12276                        removed.add(pa);
12277                    }
12278                }
12279                if (removed.size() > 0) {
12280                    for (int r=0; r<removed.size(); r++) {
12281                        PreferredActivity pa = removed.get(r);
12282                        Slog.w(TAG, "Removing dangling preferred activity: "
12283                                + pa.mPref.mComponent);
12284                        pir.removeFilter(pa);
12285                    }
12286                    mSettings.writePackageRestrictionsLPr(
12287                            mSettings.mPreferredActivities.keyAt(i));
12288                }
12289            }
12290        }
12291        sUserManager.systemReady();
12292
12293        // Kick off any messages waiting for system ready
12294        if (mPostSystemReadyMessages != null) {
12295            for (Message msg : mPostSystemReadyMessages) {
12296                msg.sendToTarget();
12297            }
12298            mPostSystemReadyMessages = null;
12299        }
12300    }
12301
12302    @Override
12303    public boolean isSafeMode() {
12304        return mSafeMode;
12305    }
12306
12307    @Override
12308    public boolean hasSystemUidErrors() {
12309        return mHasSystemUidErrors;
12310    }
12311
12312    static String arrayToString(int[] array) {
12313        StringBuffer buf = new StringBuffer(128);
12314        buf.append('[');
12315        if (array != null) {
12316            for (int i=0; i<array.length; i++) {
12317                if (i > 0) buf.append(", ");
12318                buf.append(array[i]);
12319            }
12320        }
12321        buf.append(']');
12322        return buf.toString();
12323    }
12324
12325    static class DumpState {
12326        public static final int DUMP_LIBS = 1 << 0;
12327        public static final int DUMP_FEATURES = 1 << 1;
12328        public static final int DUMP_RESOLVERS = 1 << 2;
12329        public static final int DUMP_PERMISSIONS = 1 << 3;
12330        public static final int DUMP_PACKAGES = 1 << 4;
12331        public static final int DUMP_SHARED_USERS = 1 << 5;
12332        public static final int DUMP_MESSAGES = 1 << 6;
12333        public static final int DUMP_PROVIDERS = 1 << 7;
12334        public static final int DUMP_VERIFIERS = 1 << 8;
12335        public static final int DUMP_PREFERRED = 1 << 9;
12336        public static final int DUMP_PREFERRED_XML = 1 << 10;
12337        public static final int DUMP_KEYSETS = 1 << 11;
12338        public static final int DUMP_VERSION = 1 << 12;
12339        public static final int DUMP_INSTALLS = 1 << 13;
12340
12341        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12342
12343        private int mTypes;
12344
12345        private int mOptions;
12346
12347        private boolean mTitlePrinted;
12348
12349        private SharedUserSetting mSharedUser;
12350
12351        public boolean isDumping(int type) {
12352            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12353                return true;
12354            }
12355
12356            return (mTypes & type) != 0;
12357        }
12358
12359        public void setDump(int type) {
12360            mTypes |= type;
12361        }
12362
12363        public boolean isOptionEnabled(int option) {
12364            return (mOptions & option) != 0;
12365        }
12366
12367        public void setOptionEnabled(int option) {
12368            mOptions |= option;
12369        }
12370
12371        public boolean onTitlePrinted() {
12372            final boolean printed = mTitlePrinted;
12373            mTitlePrinted = true;
12374            return printed;
12375        }
12376
12377        public boolean getTitlePrinted() {
12378            return mTitlePrinted;
12379        }
12380
12381        public void setTitlePrinted(boolean enabled) {
12382            mTitlePrinted = enabled;
12383        }
12384
12385        public SharedUserSetting getSharedUser() {
12386            return mSharedUser;
12387        }
12388
12389        public void setSharedUser(SharedUserSetting user) {
12390            mSharedUser = user;
12391        }
12392    }
12393
12394    @Override
12395    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12396        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12397                != PackageManager.PERMISSION_GRANTED) {
12398            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12399                    + Binder.getCallingPid()
12400                    + ", uid=" + Binder.getCallingUid()
12401                    + " without permission "
12402                    + android.Manifest.permission.DUMP);
12403            return;
12404        }
12405
12406        DumpState dumpState = new DumpState();
12407        boolean fullPreferred = false;
12408        boolean checkin = false;
12409
12410        String packageName = null;
12411
12412        int opti = 0;
12413        while (opti < args.length) {
12414            String opt = args[opti];
12415            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12416                break;
12417            }
12418            opti++;
12419
12420            if ("-a".equals(opt)) {
12421                // Right now we only know how to print all.
12422            } else if ("-h".equals(opt)) {
12423                pw.println("Package manager dump options:");
12424                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12425                pw.println("    --checkin: dump for a checkin");
12426                pw.println("    -f: print details of intent filters");
12427                pw.println("    -h: print this help");
12428                pw.println("  cmd may be one of:");
12429                pw.println("    l[ibraries]: list known shared libraries");
12430                pw.println("    f[ibraries]: list device features");
12431                pw.println("    k[eysets]: print known keysets");
12432                pw.println("    r[esolvers]: dump intent resolvers");
12433                pw.println("    perm[issions]: dump permissions");
12434                pw.println("    pref[erred]: print preferred package settings");
12435                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12436                pw.println("    prov[iders]: dump content providers");
12437                pw.println("    p[ackages]: dump installed packages");
12438                pw.println("    s[hared-users]: dump shared user IDs");
12439                pw.println("    m[essages]: print collected runtime messages");
12440                pw.println("    v[erifiers]: print package verifier info");
12441                pw.println("    version: print database version info");
12442                pw.println("    write: write current settings now");
12443                pw.println("    <package.name>: info about given package");
12444                pw.println("    installs: details about install sessions");
12445                return;
12446            } else if ("--checkin".equals(opt)) {
12447                checkin = true;
12448            } else if ("-f".equals(opt)) {
12449                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12450            } else {
12451                pw.println("Unknown argument: " + opt + "; use -h for help");
12452            }
12453        }
12454
12455        // Is the caller requesting to dump a particular piece of data?
12456        if (opti < args.length) {
12457            String cmd = args[opti];
12458            opti++;
12459            // Is this a package name?
12460            if ("android".equals(cmd) || cmd.contains(".")) {
12461                packageName = cmd;
12462                // When dumping a single package, we always dump all of its
12463                // filter information since the amount of data will be reasonable.
12464                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12465            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12466                dumpState.setDump(DumpState.DUMP_LIBS);
12467            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12468                dumpState.setDump(DumpState.DUMP_FEATURES);
12469            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12470                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12471            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12472                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12473            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12474                dumpState.setDump(DumpState.DUMP_PREFERRED);
12475            } else if ("preferred-xml".equals(cmd)) {
12476                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12477                if (opti < args.length && "--full".equals(args[opti])) {
12478                    fullPreferred = true;
12479                    opti++;
12480                }
12481            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12482                dumpState.setDump(DumpState.DUMP_PACKAGES);
12483            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12484                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12485            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12486                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12487            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12488                dumpState.setDump(DumpState.DUMP_MESSAGES);
12489            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12490                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12491            } else if ("version".equals(cmd)) {
12492                dumpState.setDump(DumpState.DUMP_VERSION);
12493            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12494                dumpState.setDump(DumpState.DUMP_KEYSETS);
12495            } else if ("installs".equals(cmd)) {
12496                dumpState.setDump(DumpState.DUMP_INSTALLS);
12497            } else if ("write".equals(cmd)) {
12498                synchronized (mPackages) {
12499                    mSettings.writeLPr();
12500                    pw.println("Settings written.");
12501                    return;
12502                }
12503            }
12504        }
12505
12506        if (checkin) {
12507            pw.println("vers,1");
12508        }
12509
12510        // reader
12511        synchronized (mPackages) {
12512            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12513                if (!checkin) {
12514                    if (dumpState.onTitlePrinted())
12515                        pw.println();
12516                    pw.println("Database versions:");
12517                    pw.print("  SDK Version:");
12518                    pw.print(" internal=");
12519                    pw.print(mSettings.mInternalSdkPlatform);
12520                    pw.print(" external=");
12521                    pw.println(mSettings.mExternalSdkPlatform);
12522                    pw.print("  DB Version:");
12523                    pw.print(" internal=");
12524                    pw.print(mSettings.mInternalDatabaseVersion);
12525                    pw.print(" external=");
12526                    pw.println(mSettings.mExternalDatabaseVersion);
12527                }
12528            }
12529
12530            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12531                if (!checkin) {
12532                    if (dumpState.onTitlePrinted())
12533                        pw.println();
12534                    pw.println("Verifiers:");
12535                    pw.print("  Required: ");
12536                    pw.print(mRequiredVerifierPackage);
12537                    pw.print(" (uid=");
12538                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12539                    pw.println(")");
12540                } else if (mRequiredVerifierPackage != null) {
12541                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12542                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12543                }
12544            }
12545
12546            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12547                boolean printedHeader = false;
12548                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12549                while (it.hasNext()) {
12550                    String name = it.next();
12551                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12552                    if (!checkin) {
12553                        if (!printedHeader) {
12554                            if (dumpState.onTitlePrinted())
12555                                pw.println();
12556                            pw.println("Libraries:");
12557                            printedHeader = true;
12558                        }
12559                        pw.print("  ");
12560                    } else {
12561                        pw.print("lib,");
12562                    }
12563                    pw.print(name);
12564                    if (!checkin) {
12565                        pw.print(" -> ");
12566                    }
12567                    if (ent.path != null) {
12568                        if (!checkin) {
12569                            pw.print("(jar) ");
12570                            pw.print(ent.path);
12571                        } else {
12572                            pw.print(",jar,");
12573                            pw.print(ent.path);
12574                        }
12575                    } else {
12576                        if (!checkin) {
12577                            pw.print("(apk) ");
12578                            pw.print(ent.apk);
12579                        } else {
12580                            pw.print(",apk,");
12581                            pw.print(ent.apk);
12582                        }
12583                    }
12584                    pw.println();
12585                }
12586            }
12587
12588            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12589                if (dumpState.onTitlePrinted())
12590                    pw.println();
12591                if (!checkin) {
12592                    pw.println("Features:");
12593                }
12594                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12595                while (it.hasNext()) {
12596                    String name = it.next();
12597                    if (!checkin) {
12598                        pw.print("  ");
12599                    } else {
12600                        pw.print("feat,");
12601                    }
12602                    pw.println(name);
12603                }
12604            }
12605
12606            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12607                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12608                        : "Activity Resolver Table:", "  ", packageName,
12609                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12610                    dumpState.setTitlePrinted(true);
12611                }
12612                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12613                        : "Receiver Resolver Table:", "  ", packageName,
12614                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12615                    dumpState.setTitlePrinted(true);
12616                }
12617                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12618                        : "Service Resolver Table:", "  ", packageName,
12619                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12620                    dumpState.setTitlePrinted(true);
12621                }
12622                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12623                        : "Provider Resolver Table:", "  ", packageName,
12624                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12625                    dumpState.setTitlePrinted(true);
12626                }
12627            }
12628
12629            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12630                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12631                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12632                    int user = mSettings.mPreferredActivities.keyAt(i);
12633                    if (pir.dump(pw,
12634                            dumpState.getTitlePrinted()
12635                                ? "\nPreferred Activities User " + user + ":"
12636                                : "Preferred Activities User " + user + ":", "  ",
12637                            packageName, true, false)) {
12638                        dumpState.setTitlePrinted(true);
12639                    }
12640                }
12641            }
12642
12643            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12644                pw.flush();
12645                FileOutputStream fout = new FileOutputStream(fd);
12646                BufferedOutputStream str = new BufferedOutputStream(fout);
12647                XmlSerializer serializer = new FastXmlSerializer();
12648                try {
12649                    serializer.setOutput(str, "utf-8");
12650                    serializer.startDocument(null, true);
12651                    serializer.setFeature(
12652                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12653                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12654                    serializer.endDocument();
12655                    serializer.flush();
12656                } catch (IllegalArgumentException e) {
12657                    pw.println("Failed writing: " + e);
12658                } catch (IllegalStateException e) {
12659                    pw.println("Failed writing: " + e);
12660                } catch (IOException e) {
12661                    pw.println("Failed writing: " + e);
12662                }
12663            }
12664
12665            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12666                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12667                if (packageName == null) {
12668                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12669                        if (iperm == 0) {
12670                            if (dumpState.onTitlePrinted())
12671                                pw.println();
12672                            pw.println("AppOp Permissions:");
12673                        }
12674                        pw.print("  AppOp Permission ");
12675                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12676                        pw.println(":");
12677                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12678                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12679                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12680                        }
12681                    }
12682                }
12683            }
12684
12685            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12686                boolean printedSomething = false;
12687                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12688                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12689                        continue;
12690                    }
12691                    if (!printedSomething) {
12692                        if (dumpState.onTitlePrinted())
12693                            pw.println();
12694                        pw.println("Registered ContentProviders:");
12695                        printedSomething = true;
12696                    }
12697                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12698                    pw.print("    "); pw.println(p.toString());
12699                }
12700                printedSomething = false;
12701                for (Map.Entry<String, PackageParser.Provider> entry :
12702                        mProvidersByAuthority.entrySet()) {
12703                    PackageParser.Provider p = entry.getValue();
12704                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12705                        continue;
12706                    }
12707                    if (!printedSomething) {
12708                        if (dumpState.onTitlePrinted())
12709                            pw.println();
12710                        pw.println("ContentProvider Authorities:");
12711                        printedSomething = true;
12712                    }
12713                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12714                    pw.print("    "); pw.println(p.toString());
12715                    if (p.info != null && p.info.applicationInfo != null) {
12716                        final String appInfo = p.info.applicationInfo.toString();
12717                        pw.print("      applicationInfo="); pw.println(appInfo);
12718                    }
12719                }
12720            }
12721
12722            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12723                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12724            }
12725
12726            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12727                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12728            }
12729
12730            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12731                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12732            }
12733
12734            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12735                // XXX should handle packageName != null by dumping only install data that
12736                // the given package is involved with.
12737                if (dumpState.onTitlePrinted()) pw.println();
12738                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12739            }
12740
12741            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12742                if (dumpState.onTitlePrinted()) pw.println();
12743                mSettings.dumpReadMessagesLPr(pw, dumpState);
12744
12745                pw.println();
12746                pw.println("Package warning messages:");
12747                BufferedReader in = null;
12748                String line = null;
12749                try {
12750                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12751                    while ((line = in.readLine()) != null) {
12752                        if (line.contains("ignored: updated version")) continue;
12753                        pw.println(line);
12754                    }
12755                } catch (IOException ignored) {
12756                } finally {
12757                    IoUtils.closeQuietly(in);
12758                }
12759            }
12760
12761            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12762                BufferedReader in = null;
12763                String line = null;
12764                try {
12765                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12766                    while ((line = in.readLine()) != null) {
12767                        if (line.contains("ignored: updated version")) continue;
12768                        pw.print("msg,");
12769                        pw.println(line);
12770                    }
12771                } catch (IOException ignored) {
12772                } finally {
12773                    IoUtils.closeQuietly(in);
12774                }
12775            }
12776        }
12777    }
12778
12779    // ------- apps on sdcard specific code -------
12780    static final boolean DEBUG_SD_INSTALL = false;
12781
12782    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12783
12784    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12785
12786    private boolean mMediaMounted = false;
12787
12788    static String getEncryptKey() {
12789        try {
12790            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12791                    SD_ENCRYPTION_KEYSTORE_NAME);
12792            if (sdEncKey == null) {
12793                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12794                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12795                if (sdEncKey == null) {
12796                    Slog.e(TAG, "Failed to create encryption keys");
12797                    return null;
12798                }
12799            }
12800            return sdEncKey;
12801        } catch (NoSuchAlgorithmException nsae) {
12802            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12803            return null;
12804        } catch (IOException ioe) {
12805            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12806            return null;
12807        }
12808    }
12809
12810    /*
12811     * Update media status on PackageManager.
12812     */
12813    @Override
12814    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12815        int callingUid = Binder.getCallingUid();
12816        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12817            throw new SecurityException("Media status can only be updated by the system");
12818        }
12819        // reader; this apparently protects mMediaMounted, but should probably
12820        // be a different lock in that case.
12821        synchronized (mPackages) {
12822            Log.i(TAG, "Updating external media status from "
12823                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12824                    + (mediaStatus ? "mounted" : "unmounted"));
12825            if (DEBUG_SD_INSTALL)
12826                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12827                        + ", mMediaMounted=" + mMediaMounted);
12828            if (mediaStatus == mMediaMounted) {
12829                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12830                        : 0, -1);
12831                mHandler.sendMessage(msg);
12832                return;
12833            }
12834            mMediaMounted = mediaStatus;
12835        }
12836        // Queue up an async operation since the package installation may take a
12837        // little while.
12838        mHandler.post(new Runnable() {
12839            public void run() {
12840                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12841            }
12842        });
12843    }
12844
12845    /**
12846     * Called by MountService when the initial ASECs to scan are available.
12847     * Should block until all the ASEC containers are finished being scanned.
12848     */
12849    public void scanAvailableAsecs() {
12850        updateExternalMediaStatusInner(true, false, false);
12851        if (mShouldRestoreconData) {
12852            SELinuxMMAC.setRestoreconDone();
12853            mShouldRestoreconData = false;
12854        }
12855    }
12856
12857    /*
12858     * Collect information of applications on external media, map them against
12859     * existing containers and update information based on current mount status.
12860     * Please note that we always have to report status if reportStatus has been
12861     * set to true especially when unloading packages.
12862     */
12863    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12864            boolean externalStorage) {
12865        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12866        int[] uidArr = EmptyArray.INT;
12867
12868        final String[] list = PackageHelper.getSecureContainerList();
12869        if (ArrayUtils.isEmpty(list)) {
12870            Log.i(TAG, "No secure containers found");
12871        } else {
12872            // Process list of secure containers and categorize them
12873            // as active or stale based on their package internal state.
12874
12875            // reader
12876            synchronized (mPackages) {
12877                for (String cid : list) {
12878                    // Leave stages untouched for now; installer service owns them
12879                    if (PackageInstallerService.isStageName(cid)) continue;
12880
12881                    if (DEBUG_SD_INSTALL)
12882                        Log.i(TAG, "Processing container " + cid);
12883                    String pkgName = getAsecPackageName(cid);
12884                    if (pkgName == null) {
12885                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12886                        continue;
12887                    }
12888                    if (DEBUG_SD_INSTALL)
12889                        Log.i(TAG, "Looking for pkg : " + pkgName);
12890
12891                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12892                    if (ps == null) {
12893                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12894                        continue;
12895                    }
12896
12897                    /*
12898                     * Skip packages that are not external if we're unmounting
12899                     * external storage.
12900                     */
12901                    if (externalStorage && !isMounted && !isExternal(ps)) {
12902                        continue;
12903                    }
12904
12905                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12906                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12907                    // The package status is changed only if the code path
12908                    // matches between settings and the container id.
12909                    if (ps.codePathString != null
12910                            && ps.codePathString.startsWith(args.getCodePath())) {
12911                        if (DEBUG_SD_INSTALL) {
12912                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12913                                    + " at code path: " + ps.codePathString);
12914                        }
12915
12916                        // We do have a valid package installed on sdcard
12917                        processCids.put(args, ps.codePathString);
12918                        final int uid = ps.appId;
12919                        if (uid != -1) {
12920                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12921                        }
12922                    } else {
12923                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12924                                + ps.codePathString);
12925                    }
12926                }
12927            }
12928
12929            Arrays.sort(uidArr);
12930        }
12931
12932        // Process packages with valid entries.
12933        if (isMounted) {
12934            if (DEBUG_SD_INSTALL)
12935                Log.i(TAG, "Loading packages");
12936            loadMediaPackages(processCids, uidArr);
12937            startCleaningPackages();
12938            mInstallerService.onSecureContainersAvailable();
12939        } else {
12940            if (DEBUG_SD_INSTALL)
12941                Log.i(TAG, "Unloading packages");
12942            unloadMediaPackages(processCids, uidArr, reportStatus);
12943        }
12944    }
12945
12946    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12947            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12948        int size = pkgList.size();
12949        if (size > 0) {
12950            // Send broadcasts here
12951            Bundle extras = new Bundle();
12952            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12953                    .toArray(new String[size]));
12954            if (uidArr != null) {
12955                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12956            }
12957            if (replacing) {
12958                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12959            }
12960            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12961                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12962            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12963        }
12964    }
12965
12966   /*
12967     * Look at potentially valid container ids from processCids If package
12968     * information doesn't match the one on record or package scanning fails,
12969     * the cid is added to list of removeCids. We currently don't delete stale
12970     * containers.
12971     */
12972    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12973        ArrayList<String> pkgList = new ArrayList<String>();
12974        Set<AsecInstallArgs> keys = processCids.keySet();
12975
12976        for (AsecInstallArgs args : keys) {
12977            String codePath = processCids.get(args);
12978            if (DEBUG_SD_INSTALL)
12979                Log.i(TAG, "Loading container : " + args.cid);
12980            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12981            try {
12982                // Make sure there are no container errors first.
12983                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12984                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12985                            + " when installing from sdcard");
12986                    continue;
12987                }
12988                // Check code path here.
12989                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12990                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12991                            + " does not match one in settings " + codePath);
12992                    continue;
12993                }
12994                // Parse package
12995                int parseFlags = mDefParseFlags;
12996                if (args.isExternal()) {
12997                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12998                }
12999                if (args.isFwdLocked()) {
13000                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13001                }
13002
13003                synchronized (mInstallLock) {
13004                    PackageParser.Package pkg = null;
13005                    try {
13006                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13007                    } catch (PackageManagerException e) {
13008                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13009                    }
13010                    // Scan the package
13011                    if (pkg != null) {
13012                        /*
13013                         * TODO why is the lock being held? doPostInstall is
13014                         * called in other places without the lock. This needs
13015                         * to be straightened out.
13016                         */
13017                        // writer
13018                        synchronized (mPackages) {
13019                            retCode = PackageManager.INSTALL_SUCCEEDED;
13020                            pkgList.add(pkg.packageName);
13021                            // Post process args
13022                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13023                                    pkg.applicationInfo.uid);
13024                        }
13025                    } else {
13026                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13027                    }
13028                }
13029
13030            } finally {
13031                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13032                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13033                }
13034            }
13035        }
13036        // writer
13037        synchronized (mPackages) {
13038            // If the platform SDK has changed since the last time we booted,
13039            // we need to re-grant app permission to catch any new ones that
13040            // appear. This is really a hack, and means that apps can in some
13041            // cases get permissions that the user didn't initially explicitly
13042            // allow... it would be nice to have some better way to handle
13043            // this situation.
13044            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13045            if (regrantPermissions)
13046                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13047                        + mSdkVersion + "; regranting permissions for external storage");
13048            mSettings.mExternalSdkPlatform = mSdkVersion;
13049
13050            // Make sure group IDs have been assigned, and any permission
13051            // changes in other apps are accounted for
13052            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13053                    | (regrantPermissions
13054                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13055                            : 0));
13056
13057            mSettings.updateExternalDatabaseVersion();
13058
13059            // can downgrade to reader
13060            // Persist settings
13061            mSettings.writeLPr();
13062        }
13063        // Send a broadcast to let everyone know we are done processing
13064        if (pkgList.size() > 0) {
13065            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13066        }
13067    }
13068
13069   /*
13070     * Utility method to unload a list of specified containers
13071     */
13072    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13073        // Just unmount all valid containers.
13074        for (AsecInstallArgs arg : cidArgs) {
13075            synchronized (mInstallLock) {
13076                arg.doPostDeleteLI(false);
13077           }
13078       }
13079   }
13080
13081    /*
13082     * Unload packages mounted on external media. This involves deleting package
13083     * data from internal structures, sending broadcasts about diabled packages,
13084     * gc'ing to free up references, unmounting all secure containers
13085     * corresponding to packages on external media, and posting a
13086     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13087     * that we always have to post this message if status has been requested no
13088     * matter what.
13089     */
13090    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13091            final boolean reportStatus) {
13092        if (DEBUG_SD_INSTALL)
13093            Log.i(TAG, "unloading media packages");
13094        ArrayList<String> pkgList = new ArrayList<String>();
13095        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13096        final Set<AsecInstallArgs> keys = processCids.keySet();
13097        for (AsecInstallArgs args : keys) {
13098            String pkgName = args.getPackageName();
13099            if (DEBUG_SD_INSTALL)
13100                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13101            // Delete package internally
13102            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13103            synchronized (mInstallLock) {
13104                boolean res = deletePackageLI(pkgName, null, false, null, null,
13105                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13106                if (res) {
13107                    pkgList.add(pkgName);
13108                } else {
13109                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13110                    failedList.add(args);
13111                }
13112            }
13113        }
13114
13115        // reader
13116        synchronized (mPackages) {
13117            // We didn't update the settings after removing each package;
13118            // write them now for all packages.
13119            mSettings.writeLPr();
13120        }
13121
13122        // We have to absolutely send UPDATED_MEDIA_STATUS only
13123        // after confirming that all the receivers processed the ordered
13124        // broadcast when packages get disabled, force a gc to clean things up.
13125        // and unload all the containers.
13126        if (pkgList.size() > 0) {
13127            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13128                    new IIntentReceiver.Stub() {
13129                public void performReceive(Intent intent, int resultCode, String data,
13130                        Bundle extras, boolean ordered, boolean sticky,
13131                        int sendingUser) throws RemoteException {
13132                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13133                            reportStatus ? 1 : 0, 1, keys);
13134                    mHandler.sendMessage(msg);
13135                }
13136            });
13137        } else {
13138            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13139                    keys);
13140            mHandler.sendMessage(msg);
13141        }
13142    }
13143
13144    /** Binder call */
13145    @Override
13146    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13147            final int flags) {
13148        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13149        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13150        int returnCode = PackageManager.MOVE_SUCCEEDED;
13151        int currInstallFlags = 0;
13152        int newInstallFlags = 0;
13153
13154        File codeFile = null;
13155        String installerPackageName = null;
13156        String packageAbiOverride = null;
13157
13158        // reader
13159        synchronized (mPackages) {
13160            final PackageParser.Package pkg = mPackages.get(packageName);
13161            final PackageSetting ps = mSettings.mPackages.get(packageName);
13162            if (pkg == null || ps == null) {
13163                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13164            } else {
13165                // Disable moving fwd locked apps and system packages
13166                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13167                    Slog.w(TAG, "Cannot move system application");
13168                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13169                } else if (pkg.mOperationPending) {
13170                    Slog.w(TAG, "Attempt to move package which has pending operations");
13171                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13172                } else {
13173                    // Find install location first
13174                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13175                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13176                        Slog.w(TAG, "Ambigous flags specified for move location.");
13177                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13178                    } else {
13179                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13180                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13181                        currInstallFlags = isExternal(pkg)
13182                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13183
13184                        if (newInstallFlags == currInstallFlags) {
13185                            Slog.w(TAG, "No move required. Trying to move to same location");
13186                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13187                        } else {
13188                            if (isForwardLocked(pkg)) {
13189                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13190                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13191                            }
13192                        }
13193                    }
13194                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13195                        pkg.mOperationPending = true;
13196                    }
13197                }
13198
13199                codeFile = new File(pkg.codePath);
13200                installerPackageName = ps.installerPackageName;
13201                packageAbiOverride = ps.cpuAbiOverrideString;
13202            }
13203        }
13204
13205        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13206            try {
13207                observer.packageMoved(packageName, returnCode);
13208            } catch (RemoteException ignored) {
13209            }
13210            return;
13211        }
13212
13213        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13214            @Override
13215            public void onUserActionRequired(Intent intent) throws RemoteException {
13216                throw new IllegalStateException();
13217            }
13218
13219            @Override
13220            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13221                    Bundle extras) throws RemoteException {
13222                Slog.d(TAG, "Install result for move: "
13223                        + PackageManager.installStatusToString(returnCode, msg));
13224
13225                // We usually have a new package now after the install, but if
13226                // we failed we need to clear the pending flag on the original
13227                // package object.
13228                synchronized (mPackages) {
13229                    final PackageParser.Package pkg = mPackages.get(packageName);
13230                    if (pkg != null) {
13231                        pkg.mOperationPending = false;
13232                    }
13233                }
13234
13235                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13236                switch (status) {
13237                    case PackageInstaller.STATUS_SUCCESS:
13238                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13239                        break;
13240                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13241                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13242                        break;
13243                    default:
13244                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13245                        break;
13246                }
13247            }
13248        };
13249
13250        // Treat a move like reinstalling an existing app, which ensures that we
13251        // process everythign uniformly, like unpacking native libraries.
13252        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13253
13254        final Message msg = mHandler.obtainMessage(INIT_COPY);
13255        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13256        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13257                installerPackageName, null, user, packageAbiOverride);
13258        mHandler.sendMessage(msg);
13259    }
13260
13261    @Override
13262    public boolean setInstallLocation(int loc) {
13263        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13264                null);
13265        if (getInstallLocation() == loc) {
13266            return true;
13267        }
13268        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13269                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13270            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13271                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13272            return true;
13273        }
13274        return false;
13275   }
13276
13277    @Override
13278    public int getInstallLocation() {
13279        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13280                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13281                PackageHelper.APP_INSTALL_AUTO);
13282    }
13283
13284    /** Called by UserManagerService */
13285    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13286        mDirtyUsers.remove(userHandle);
13287        mSettings.removeUserLPw(userHandle);
13288        mPendingBroadcasts.remove(userHandle);
13289        if (mInstaller != null) {
13290            // Technically, we shouldn't be doing this with the package lock
13291            // held.  However, this is very rare, and there is already so much
13292            // other disk I/O going on, that we'll let it slide for now.
13293            mInstaller.removeUserDataDirs(userHandle);
13294        }
13295        mUserNeedsBadging.delete(userHandle);
13296        removeUnusedPackagesLILPw(userManager, userHandle);
13297    }
13298
13299    /**
13300     * We're removing userHandle and would like to remove any downloaded packages
13301     * that are no longer in use by any other user.
13302     * @param userHandle the user being removed
13303     */
13304    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13305        final boolean DEBUG_CLEAN_APKS = false;
13306        int [] users = userManager.getUserIdsLPr();
13307        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13308        while (psit.hasNext()) {
13309            PackageSetting ps = psit.next();
13310            if (ps.pkg == null) {
13311                continue;
13312            }
13313            final String packageName = ps.pkg.packageName;
13314            // Skip over if system app
13315            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13316                continue;
13317            }
13318            if (DEBUG_CLEAN_APKS) {
13319                Slog.i(TAG, "Checking package " + packageName);
13320            }
13321            boolean keep = false;
13322            for (int i = 0; i < users.length; i++) {
13323                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13324                    keep = true;
13325                    if (DEBUG_CLEAN_APKS) {
13326                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13327                                + users[i]);
13328                    }
13329                    break;
13330                }
13331            }
13332            if (!keep) {
13333                if (DEBUG_CLEAN_APKS) {
13334                    Slog.i(TAG, "  Removing package " + packageName);
13335                }
13336                mHandler.post(new Runnable() {
13337                    public void run() {
13338                        deletePackageX(packageName, userHandle, 0);
13339                    } //end run
13340                });
13341            }
13342        }
13343    }
13344
13345    /** Called by UserManagerService */
13346    void createNewUserLILPw(int userHandle, File path) {
13347        if (mInstaller != null) {
13348            mInstaller.createUserConfig(userHandle);
13349            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13350        }
13351    }
13352
13353    @Override
13354    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13355        mContext.enforceCallingOrSelfPermission(
13356                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13357                "Only package verification agents can read the verifier device identity");
13358
13359        synchronized (mPackages) {
13360            return mSettings.getVerifierDeviceIdentityLPw();
13361        }
13362    }
13363
13364    @Override
13365    public void setPermissionEnforced(String permission, boolean enforced) {
13366        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13367        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13368            synchronized (mPackages) {
13369                if (mSettings.mReadExternalStorageEnforced == null
13370                        || mSettings.mReadExternalStorageEnforced != enforced) {
13371                    mSettings.mReadExternalStorageEnforced = enforced;
13372                    mSettings.writeLPr();
13373                }
13374            }
13375            // kill any non-foreground processes so we restart them and
13376            // grant/revoke the GID.
13377            final IActivityManager am = ActivityManagerNative.getDefault();
13378            if (am != null) {
13379                final long token = Binder.clearCallingIdentity();
13380                try {
13381                    am.killProcessesBelowForeground("setPermissionEnforcement");
13382                } catch (RemoteException e) {
13383                } finally {
13384                    Binder.restoreCallingIdentity(token);
13385                }
13386            }
13387        } else {
13388            throw new IllegalArgumentException("No selective enforcement for " + permission);
13389        }
13390    }
13391
13392    @Override
13393    @Deprecated
13394    public boolean isPermissionEnforced(String permission) {
13395        return true;
13396    }
13397
13398    @Override
13399    public boolean isStorageLow() {
13400        final long token = Binder.clearCallingIdentity();
13401        try {
13402            final DeviceStorageMonitorInternal
13403                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13404            if (dsm != null) {
13405                return dsm.isMemoryLow();
13406            } else {
13407                return false;
13408            }
13409        } finally {
13410            Binder.restoreCallingIdentity(token);
13411        }
13412    }
13413
13414    @Override
13415    public IPackageInstaller getPackageInstaller() {
13416        return mInstallerService;
13417    }
13418
13419    private boolean userNeedsBadging(int userId) {
13420        int index = mUserNeedsBadging.indexOfKey(userId);
13421        if (index < 0) {
13422            final UserInfo userInfo;
13423            final long token = Binder.clearCallingIdentity();
13424            try {
13425                userInfo = sUserManager.getUserInfo(userId);
13426            } finally {
13427                Binder.restoreCallingIdentity(token);
13428            }
13429            final boolean b;
13430            if (userInfo != null && userInfo.isManagedProfile()) {
13431                b = true;
13432            } else {
13433                b = false;
13434            }
13435            mUserNeedsBadging.put(userId, b);
13436            return b;
13437        }
13438        return mUserNeedsBadging.valueAt(index);
13439    }
13440
13441    @Override
13442    public KeySet getKeySetByAlias(String packageName, String alias) {
13443        if (packageName == null || alias == null) {
13444            return null;
13445        }
13446        synchronized(mPackages) {
13447            final PackageParser.Package pkg = mPackages.get(packageName);
13448            if (pkg == null) {
13449                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13450                throw new IllegalArgumentException("Unknown package: " + packageName);
13451            }
13452            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13453            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13454        }
13455    }
13456
13457    @Override
13458    public KeySet getSigningKeySet(String packageName) {
13459        if (packageName == null) {
13460            return null;
13461        }
13462        synchronized(mPackages) {
13463            final PackageParser.Package pkg = mPackages.get(packageName);
13464            if (pkg == null) {
13465                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13466                throw new IllegalArgumentException("Unknown package: " + packageName);
13467            }
13468            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13469                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13470                throw new SecurityException("May not access signing KeySet of other apps.");
13471            }
13472            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13473            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13474        }
13475    }
13476
13477    @Override
13478    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13479        if (packageName == null || ks == null) {
13480            return false;
13481        }
13482        synchronized(mPackages) {
13483            final PackageParser.Package pkg = mPackages.get(packageName);
13484            if (pkg == null) {
13485                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13486                throw new IllegalArgumentException("Unknown package: " + packageName);
13487            }
13488            IBinder ksh = ks.getToken();
13489            if (ksh instanceof KeySetHandle) {
13490                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13491                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13492            }
13493            return false;
13494        }
13495    }
13496
13497    @Override
13498    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13499        if (packageName == null || ks == null) {
13500            return false;
13501        }
13502        synchronized(mPackages) {
13503            final PackageParser.Package pkg = mPackages.get(packageName);
13504            if (pkg == null) {
13505                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13506                throw new IllegalArgumentException("Unknown package: " + packageName);
13507            }
13508            IBinder ksh = ks.getToken();
13509            if (ksh instanceof KeySetHandle) {
13510                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13511                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13512            }
13513            return false;
13514        }
13515    }
13516
13517    public void getUsageStatsIfNoPackageUsageInfo() {
13518        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13519            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13520            if (usm == null) {
13521                throw new IllegalStateException("UsageStatsManager must be initialized");
13522            }
13523            long now = System.currentTimeMillis();
13524            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13525            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13526                String packageName = entry.getKey();
13527                PackageParser.Package pkg = mPackages.get(packageName);
13528                if (pkg == null) {
13529                    continue;
13530                }
13531                UsageStats usage = entry.getValue();
13532                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13533                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13534            }
13535        }
13536    }
13537
13538    /**
13539     * Check and throw if the given before/after packages would be considered a
13540     * downgrade.
13541     */
13542    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13543            throws PackageManagerException {
13544        if (after.versionCode < before.mVersionCode) {
13545            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13546                    "Update version code " + after.versionCode + " is older than current "
13547                    + before.mVersionCode);
13548        } else if (after.versionCode == before.mVersionCode) {
13549            if (after.baseRevisionCode < before.baseRevisionCode) {
13550                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13551                        "Update base revision code " + after.baseRevisionCode
13552                        + " is older than current " + before.baseRevisionCode);
13553            }
13554
13555            if (!ArrayUtils.isEmpty(after.splitNames)) {
13556                for (int i = 0; i < after.splitNames.length; i++) {
13557                    final String splitName = after.splitNames[i];
13558                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13559                    if (j != -1) {
13560                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13561                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13562                                    "Update split " + splitName + " revision code "
13563                                    + after.splitRevisionCodes[i] + " is older than current "
13564                                    + before.splitRevisionCodes[j]);
13565                        }
13566                    }
13567                }
13568            }
13569        }
13570    }
13571}
13572