PackageManagerService.java revision 7f7b0c759e2970178ef68805b21f06a26e24eb76
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.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import android.util.ArrayMap;
40import com.android.internal.R;
41import com.android.internal.app.IMediaContainerService;
42import com.android.internal.app.ResolverActivity;
43import com.android.internal.content.NativeLibraryHelper;
44import com.android.internal.content.NativeLibraryHelper.ApkHandle;
45import com.android.internal.content.PackageHelper;
46import com.android.internal.util.ArrayUtils;
47import com.android.internal.util.FastPrintWriter;
48import com.android.internal.util.FastXmlSerializer;
49import com.android.internal.util.XmlUtils;
50import com.android.server.EventLogTags;
51import com.android.server.IntentResolver;
52import com.android.server.LocalServices;
53import com.android.server.ServiceThread;
54import com.android.server.SystemConfig;
55import com.android.server.Watchdog;
56import com.android.server.pm.Settings.DatabaseVersion;
57import com.android.server.storage.DeviceStorageMonitorInternal;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
63import android.app.ActivityManager;
64import android.app.ActivityManagerNative;
65import android.app.IActivityManager;
66import android.app.PackageInstallObserver;
67import android.app.admin.IDevicePolicyManager;
68import android.app.backup.IBackupManager;
69import android.content.BroadcastReceiver;
70import android.content.ComponentName;
71import android.content.Context;
72import android.content.IIntentReceiver;
73import android.content.Intent;
74import android.content.IntentFilter;
75import android.content.IntentSender;
76import android.content.IntentSender.SendIntentException;
77import android.content.ServiceConnection;
78import android.content.pm.ActivityInfo;
79import android.content.pm.ApplicationInfo;
80import android.content.pm.ContainerEncryptionParams;
81import android.content.pm.FeatureInfo;
82import android.content.pm.IPackageDataObserver;
83import android.content.pm.IPackageDeleteObserver;
84import android.content.pm.IPackageInstallObserver;
85import android.content.pm.IPackageInstallObserver2;
86import android.content.pm.IPackageInstaller;
87import android.content.pm.IPackageManager;
88import android.content.pm.IPackageMoveObserver;
89import android.content.pm.IPackageStatsObserver;
90import android.content.pm.InstrumentationInfo;
91import android.content.pm.ManifestDigest;
92import android.content.pm.PackageCleanItem;
93import android.content.pm.PackageInfo;
94import android.content.pm.PackageInfoLite;
95import android.content.pm.PackageManager;
96import android.content.pm.PackageParser.ActivityIntentInfo;
97import android.content.pm.PackageParser.PackageParserException;
98import android.content.pm.PackageParser;
99import android.content.pm.PackageStats;
100import android.content.pm.PackageUserState;
101import android.content.pm.ParceledListSlice;
102import android.content.pm.PermissionGroupInfo;
103import android.content.pm.PermissionInfo;
104import android.content.pm.ProviderInfo;
105import android.content.pm.ResolveInfo;
106import android.content.pm.ServiceInfo;
107import android.content.pm.Signature;
108import android.content.pm.UserInfo;
109import android.content.pm.VerificationParams;
110import android.content.pm.VerifierDeviceIdentity;
111import android.content.pm.VerifierInfo;
112import android.content.res.Resources;
113import android.hardware.display.DisplayManager;
114import android.net.Uri;
115import android.os.Binder;
116import android.os.Build;
117import android.os.Bundle;
118import android.os.Environment;
119import android.os.Environment.UserEnvironment;
120import android.os.FileObserver;
121import android.os.FileUtils;
122import android.os.Handler;
123import android.os.IBinder;
124import android.os.Looper;
125import android.os.Message;
126import android.os.Parcel;
127import android.os.ParcelFileDescriptor;
128import android.os.Process;
129import android.os.RemoteException;
130import android.os.SELinux;
131import android.os.ServiceManager;
132import android.os.SystemClock;
133import android.os.SystemProperties;
134import android.os.UserHandle;
135import android.os.UserManager;
136import android.security.KeyStore;
137import android.security.SystemKeyStore;
138import android.system.ErrnoException;
139import android.system.Os;
140import android.system.StructStat;
141import android.text.TextUtils;
142import android.util.ArraySet;
143import android.util.AtomicFile;
144import android.util.DisplayMetrics;
145import android.util.EventLog;
146import android.util.Log;
147import android.util.LogPrinter;
148import android.util.PrintStreamPrinter;
149import android.util.Slog;
150import android.util.SparseArray;
151import android.util.SparseBooleanArray;
152import android.util.Xml;
153import android.view.Display;
154
155import java.io.BufferedInputStream;
156import java.io.BufferedOutputStream;
157import java.io.File;
158import java.io.FileDescriptor;
159import java.io.FileInputStream;
160import java.io.FileNotFoundException;
161import java.io.FileOutputStream;
162import java.io.FileReader;
163import java.io.FilenameFilter;
164import java.io.IOException;
165import java.io.InputStream;
166import java.io.PrintWriter;
167import java.nio.charset.StandardCharsets;
168import java.security.NoSuchAlgorithmException;
169import java.security.PublicKey;
170import java.security.cert.CertificateEncodingException;
171import java.security.cert.CertificateException;
172import java.text.SimpleDateFormat;
173import java.util.ArrayList;
174import java.util.Arrays;
175import java.util.Collection;
176import java.util.Collections;
177import java.util.Comparator;
178import java.util.Date;
179import java.util.HashMap;
180import java.util.HashSet;
181import java.util.Iterator;
182import java.util.List;
183import java.util.Map;
184import java.util.Set;
185import java.util.concurrent.atomic.AtomicBoolean;
186import java.util.concurrent.atomic.AtomicLong;
187
188import dalvik.system.DexFile;
189import dalvik.system.StaleDexCacheError;
190import dalvik.system.VMRuntime;
191
192import libcore.io.IoUtils;
193
194/**
195 * Keep track of all those .apks everywhere.
196 *
197 * This is very central to the platform's security; please run the unit
198 * tests whenever making modifications here:
199 *
200mmm frameworks/base/tests/AndroidTests
201adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
202adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
203 *
204 * {@hide}
205 */
206public class PackageManagerService extends IPackageManager.Stub {
207    static final String TAG = "PackageManager";
208    static final boolean DEBUG_SETTINGS = false;
209    static final boolean DEBUG_PREFERRED = false;
210    static final boolean DEBUG_UPGRADE = false;
211    private static final boolean DEBUG_INSTALL = false;
212    private static final boolean DEBUG_REMOVE = false;
213    private static final boolean DEBUG_BROADCASTS = false;
214    private static final boolean DEBUG_SHOW_INFO = false;
215    private static final boolean DEBUG_PACKAGE_INFO = false;
216    private static final boolean DEBUG_INTENT_MATCHING = false;
217    private static final boolean DEBUG_PACKAGE_SCANNING = false;
218    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
219    private static final boolean DEBUG_VERIFY = false;
220    private static final boolean DEBUG_DEXOPT = false;
221
222    private static final int RADIO_UID = Process.PHONE_UID;
223    private static final int LOG_UID = Process.LOG_UID;
224    private static final int NFC_UID = Process.NFC_UID;
225    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
226    private static final int SHELL_UID = Process.SHELL_UID;
227
228    // Cap the size of permission trees that 3rd party apps can define
229    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
230
231    private static final int REMOVE_EVENTS =
232        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
233    private static final int ADD_EVENTS =
234        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
235
236    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
237    // Suffix used during package installation when copying/moving
238    // package apks to install directory.
239    private static final String INSTALL_PACKAGE_SUFFIX = "-";
240
241    static final int SCAN_MONITOR = 1<<0;
242    static final int SCAN_NO_DEX = 1<<1;
243    static final int SCAN_FORCE_DEX = 1<<2;
244    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
245    static final int SCAN_NEW_INSTALL = 1<<4;
246    static final int SCAN_NO_PATHS = 1<<5;
247    static final int SCAN_UPDATE_TIME = 1<<6;
248    static final int SCAN_DEFER_DEX = 1<<7;
249    static final int SCAN_BOOTING = 1<<8;
250    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
251    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
252
253    static final int REMOVE_CHATTY = 1<<16;
254
255    /**
256     * Timeout (in milliseconds) after which the watchdog should declare that
257     * our handler thread is wedged.  The usual default for such things is one
258     * minute but we sometimes do very lengthy I/O operations on this thread,
259     * such as installing multi-gigabyte applications, so ours needs to be longer.
260     */
261    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
262
263    /**
264     * Whether verification is enabled by default.
265     */
266    private static final boolean DEFAULT_VERIFY_ENABLE = true;
267
268    /**
269     * The default maximum time to wait for the verification agent to return in
270     * milliseconds.
271     */
272    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
273
274    /**
275     * The default response for package verification timeout.
276     *
277     * This can be either PackageManager.VERIFICATION_ALLOW or
278     * PackageManager.VERIFICATION_REJECT.
279     */
280    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
281
282    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
283
284    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
285            DEFAULT_CONTAINER_PACKAGE,
286            "com.android.defcontainer.DefaultContainerService");
287
288    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
289
290    private static final String LIB_DIR_NAME = "lib";
291    private static final String LIB64_DIR_NAME = "lib64";
292
293    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
294
295    static final String mTempContainerPrefix = "smdl2tmp";
296
297    private static String sPreferredInstructionSet;
298
299    final ServiceThread mHandlerThread;
300
301    private static final String IDMAP_PREFIX = "/data/resource-cache/";
302    private static final String IDMAP_SUFFIX = "@idmap";
303
304    final PackageHandler mHandler;
305
306    final int mSdkVersion = Build.VERSION.SDK_INT;
307
308    final Context mContext;
309    final boolean mFactoryTest;
310    final boolean mOnlyCore;
311    final DisplayMetrics mMetrics;
312    final int mDefParseFlags;
313    final String[] mSeparateProcesses;
314
315    // This is where all application persistent data goes.
316    final File mAppDataDir;
317
318    // This is where all application persistent data goes for secondary users.
319    final File mUserAppDataDir;
320
321    /** The location for ASEC container files on internal storage. */
322    final String mAsecInternalPath;
323
324    // This is the object monitoring the framework dir.
325    final FileObserver mFrameworkInstallObserver;
326
327    // This is the object monitoring the system app dir.
328    final FileObserver mSystemInstallObserver;
329
330    // This is the object monitoring the privileged system app dir.
331    final FileObserver mPrivilegedInstallObserver;
332
333    // This is the object monitoring the vendor app dir.
334    final FileObserver mVendorInstallObserver;
335
336    // This is the object monitoring the vendor overlay package dir.
337    final FileObserver mVendorOverlayInstallObserver;
338
339    // This is the object monitoring the OEM app dir.
340    final FileObserver mOemInstallObserver;
341
342    // This is the object monitoring mAppInstallDir.
343    final FileObserver mAppInstallObserver;
344
345    // This is the object monitoring mDrmAppPrivateInstallDir.
346    final FileObserver mDrmAppInstallObserver;
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    final File mAppInstallDir;
353
354    /**
355     * Directory to which applications installed internally have native
356     * libraries copied.
357     */
358    private File mAppLibInstallDir;
359
360    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
361    // apps.
362    final File mDrmAppPrivateInstallDir;
363
364    final File mAppStagingDir;
365
366    // ----------------------------------------------------------------
367
368    // Lock for state used when installing and doing other long running
369    // operations.  Methods that must be called with this lock held have
370    // the suffix "LI".
371    final Object mInstallLock = new Object();
372
373    // These are the directories in the 3rd party applications installed dir
374    // that we have currently loaded packages from.  Keys are the application's
375    // installed zip file (absolute codePath), and values are Package.
376    final HashMap<String, PackageParser.Package> mAppDirs =
377            new HashMap<String, PackageParser.Package>();
378
379    // Information for the parser to write more useful error messages.
380    int mLastScanError;
381
382    // ----------------------------------------------------------------
383
384    // Keys are String (package name), values are Package.  This also serves
385    // as the lock for the global state.  Methods that must be called with
386    // this lock held have the prefix "LP".
387    final HashMap<String, PackageParser.Package> mPackages =
388            new HashMap<String, PackageParser.Package>();
389
390    // Tracks available target package names -> overlay package paths.
391    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
392        new HashMap<String, HashMap<String, PackageParser.Package>>();
393
394    final Settings mSettings;
395    boolean mRestoredSettings;
396
397    // System configuration read by SystemConfig.
398    final int[] mGlobalGids;
399    final SparseArray<HashSet<String>> mSystemPermissions;
400    final HashMap<String, FeatureInfo> mAvailableFeatures;
401
402    // If mac_permissions.xml was found for seinfo labeling.
403    boolean mFoundPolicyFile;
404
405    // If a recursive restorecon of /data/data/<pkg> is needed.
406    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
407
408    public static final class SharedLibraryEntry {
409        public final String path;
410        public final String apk;
411
412        SharedLibraryEntry(String _path, String _apk) {
413            path = _path;
414            apk = _apk;
415        }
416    }
417
418    // Currently known shared libraries.
419    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
420            new HashMap<String, SharedLibraryEntry>();
421
422    // All available activities, for your resolving pleasure.
423    final ActivityIntentResolver mActivities =
424            new ActivityIntentResolver();
425
426    // All available receivers, for your resolving pleasure.
427    final ActivityIntentResolver mReceivers =
428            new ActivityIntentResolver();
429
430    // All available services, for your resolving pleasure.
431    final ServiceIntentResolver mServices = new ServiceIntentResolver();
432
433    // All available providers, for your resolving pleasure.
434    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
435
436    // Mapping from provider base names (first directory in content URI codePath)
437    // to the provider information.
438    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
439            new HashMap<String, PackageParser.Provider>();
440
441    // Mapping from instrumentation class names to info about them.
442    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
443            new HashMap<ComponentName, PackageParser.Instrumentation>();
444
445    // Mapping from permission names to info about them.
446    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
447            new HashMap<String, PackageParser.PermissionGroup>();
448
449    // Packages whose data we have transfered into another package, thus
450    // should no longer exist.
451    final HashSet<String> mTransferedPackages = new HashSet<String>();
452
453    // Broadcast actions that are only available to the system.
454    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
455
456    /** List of packages waiting for verification. */
457    final SparseArray<PackageVerificationState> mPendingVerification
458            = new SparseArray<PackageVerificationState>();
459
460    final PackageInstallerService mInstallerService;
461
462    HashSet<PackageParser.Package> mDeferredDexOpt = null;
463
464    // Cache of users who need badging.
465    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
466
467    /** Token for keys in mPendingVerification. */
468    private int mPendingVerificationToken = 0;
469
470    boolean mSystemReady;
471    boolean mSafeMode;
472    boolean mHasSystemUidErrors;
473
474    ApplicationInfo mAndroidApplication;
475    final ActivityInfo mResolveActivity = new ActivityInfo();
476    final ResolveInfo mResolveInfo = new ResolveInfo();
477    ComponentName mResolveComponentName;
478    PackageParser.Package mPlatformPackage;
479    ComponentName mCustomResolverComponentName;
480
481    boolean mResolverReplaced = false;
482
483    // Set of pending broadcasts for aggregating enable/disable of components.
484    static class PendingPackageBroadcasts {
485        // for each user id, a map of <package name -> components within that package>
486        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
487
488        public PendingPackageBroadcasts() {
489            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
490        }
491
492        public ArrayList<String> get(int userId, String packageName) {
493            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
494            return packages.get(packageName);
495        }
496
497        public void put(int userId, String packageName, ArrayList<String> components) {
498            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
499            packages.put(packageName, components);
500        }
501
502        public void remove(int userId, String packageName) {
503            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
504            if (packages != null) {
505                packages.remove(packageName);
506            }
507        }
508
509        public void remove(int userId) {
510            mUidMap.remove(userId);
511        }
512
513        public int userIdCount() {
514            return mUidMap.size();
515        }
516
517        public int userIdAt(int n) {
518            return mUidMap.keyAt(n);
519        }
520
521        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
522            return mUidMap.get(userId);
523        }
524
525        public int size() {
526            // total number of pending broadcast entries across all userIds
527            int num = 0;
528            for (int i = 0; i< mUidMap.size(); i++) {
529                num += mUidMap.valueAt(i).size();
530            }
531            return num;
532        }
533
534        public void clear() {
535            mUidMap.clear();
536        }
537
538        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
539            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
540            if (map == null) {
541                map = new HashMap<String, ArrayList<String>>();
542                mUidMap.put(userId, map);
543            }
544            return map;
545        }
546    }
547    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
548
549    // Service Connection to remote media container service to copy
550    // package uri's from external media onto secure containers
551    // or internal storage.
552    private IMediaContainerService mContainerService = null;
553
554    static final int SEND_PENDING_BROADCAST = 1;
555    static final int MCS_BOUND = 3;
556    static final int END_COPY = 4;
557    static final int INIT_COPY = 5;
558    static final int MCS_UNBIND = 6;
559    static final int START_CLEANING_PACKAGE = 7;
560    static final int FIND_INSTALL_LOC = 8;
561    static final int POST_INSTALL = 9;
562    static final int MCS_RECONNECT = 10;
563    static final int MCS_GIVE_UP = 11;
564    static final int UPDATED_MEDIA_STATUS = 12;
565    static final int WRITE_SETTINGS = 13;
566    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
567    static final int PACKAGE_VERIFIED = 15;
568    static final int CHECK_PENDING_VERIFICATION = 16;
569
570    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
571
572    // Delay time in millisecs
573    static final int BROADCAST_DELAY = 10 * 1000;
574
575    static UserManagerService sUserManager;
576
577    // Stores a list of users whose package restrictions file needs to be updated
578    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
579
580    final private DefaultContainerConnection mDefContainerConn =
581            new DefaultContainerConnection();
582    class DefaultContainerConnection implements ServiceConnection {
583        public void onServiceConnected(ComponentName name, IBinder service) {
584            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
585            IMediaContainerService imcs =
586                IMediaContainerService.Stub.asInterface(service);
587            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
588        }
589
590        public void onServiceDisconnected(ComponentName name) {
591            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
592        }
593    };
594
595    // Recordkeeping of restore-after-install operations that are currently in flight
596    // between the Package Manager and the Backup Manager
597    class PostInstallData {
598        public InstallArgs args;
599        public PackageInstalledInfo res;
600
601        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
602            args = _a;
603            res = _r;
604        }
605    };
606    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
607    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
608
609    private final String mRequiredVerifierPackage;
610
611    private final PackageUsage mPackageUsage = new PackageUsage();
612
613    private class PackageUsage {
614        private static final int WRITE_INTERVAL
615            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
616
617        private final Object mFileLock = new Object();
618        private final AtomicLong mLastWritten = new AtomicLong(0);
619        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
620
621        private boolean mIsHistoricalPackageUsageAvailable = true;
622
623        boolean isHistoricalPackageUsageAvailable() {
624            return mIsHistoricalPackageUsageAvailable;
625        }
626
627        void write(boolean force) {
628            if (force) {
629                writeInternal();
630                return;
631            }
632            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
633                && !DEBUG_DEXOPT) {
634                return;
635            }
636            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
637                new Thread("PackageUsage_DiskWriter") {
638                    @Override
639                    public void run() {
640                        try {
641                            writeInternal();
642                        } finally {
643                            mBackgroundWriteRunning.set(false);
644                        }
645                    }
646                }.start();
647            }
648        }
649
650        private void writeInternal() {
651            synchronized (mPackages) {
652                synchronized (mFileLock) {
653                    AtomicFile file = getFile();
654                    FileOutputStream f = null;
655                    try {
656                        f = file.startWrite();
657                        BufferedOutputStream out = new BufferedOutputStream(f);
658                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
659                        StringBuilder sb = new StringBuilder();
660                        for (PackageParser.Package pkg : mPackages.values()) {
661                            if (pkg.mLastPackageUsageTimeInMills == 0) {
662                                continue;
663                            }
664                            sb.setLength(0);
665                            sb.append(pkg.packageName);
666                            sb.append(' ');
667                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
668                            sb.append('\n');
669                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
670                        }
671                        out.flush();
672                        file.finishWrite(f);
673                    } catch (IOException e) {
674                        if (f != null) {
675                            file.failWrite(f);
676                        }
677                        Log.e(TAG, "Failed to write package usage times", e);
678                    }
679                }
680            }
681            mLastWritten.set(SystemClock.elapsedRealtime());
682        }
683
684        void readLP() {
685            synchronized (mFileLock) {
686                AtomicFile file = getFile();
687                BufferedInputStream in = null;
688                try {
689                    in = new BufferedInputStream(file.openRead());
690                    StringBuffer sb = new StringBuffer();
691                    while (true) {
692                        String packageName = readToken(in, sb, ' ');
693                        if (packageName == null) {
694                            break;
695                        }
696                        String timeInMillisString = readToken(in, sb, '\n');
697                        if (timeInMillisString == null) {
698                            throw new IOException("Failed to find last usage time for package "
699                                                  + packageName);
700                        }
701                        PackageParser.Package pkg = mPackages.get(packageName);
702                        if (pkg == null) {
703                            continue;
704                        }
705                        long timeInMillis;
706                        try {
707                            timeInMillis = Long.parseLong(timeInMillisString.toString());
708                        } catch (NumberFormatException e) {
709                            throw new IOException("Failed to parse " + timeInMillisString
710                                                  + " as a long.", e);
711                        }
712                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
713                    }
714                } catch (FileNotFoundException expected) {
715                    mIsHistoricalPackageUsageAvailable = false;
716                } catch (IOException e) {
717                    Log.w(TAG, "Failed to read package usage times", e);
718                } finally {
719                    IoUtils.closeQuietly(in);
720                }
721            }
722            mLastWritten.set(SystemClock.elapsedRealtime());
723        }
724
725        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
726                throws IOException {
727            sb.setLength(0);
728            while (true) {
729                int ch = in.read();
730                if (ch == -1) {
731                    if (sb.length() == 0) {
732                        return null;
733                    }
734                    throw new IOException("Unexpected EOF");
735                }
736                if (ch == endOfToken) {
737                    return sb.toString();
738                }
739                sb.append((char)ch);
740            }
741        }
742
743        private AtomicFile getFile() {
744            File dataDir = Environment.getDataDirectory();
745            File systemDir = new File(dataDir, "system");
746            File fname = new File(systemDir, "package-usage.list");
747            return new AtomicFile(fname);
748        }
749    }
750
751    class PackageHandler extends Handler {
752        private boolean mBound = false;
753        final ArrayList<HandlerParams> mPendingInstalls =
754            new ArrayList<HandlerParams>();
755
756        private boolean connectToService() {
757            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
758                    " DefaultContainerService");
759            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
760            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
761            if (mContext.bindServiceAsUser(service, mDefContainerConn,
762                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
763                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764                mBound = true;
765                return true;
766            }
767            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768            return false;
769        }
770
771        private void disconnectService() {
772            mContainerService = null;
773            mBound = false;
774            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
775            mContext.unbindService(mDefContainerConn);
776            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
777        }
778
779        PackageHandler(Looper looper) {
780            super(looper);
781        }
782
783        public void handleMessage(Message msg) {
784            try {
785                doHandleMessage(msg);
786            } finally {
787                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
788            }
789        }
790
791        void doHandleMessage(Message msg) {
792            switch (msg.what) {
793                case INIT_COPY: {
794                    HandlerParams params = (HandlerParams) msg.obj;
795                    int idx = mPendingInstalls.size();
796                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
797                    // If a bind was already initiated we dont really
798                    // need to do anything. The pending install
799                    // will be processed later on.
800                    if (!mBound) {
801                        // If this is the only one pending we might
802                        // have to bind to the service again.
803                        if (!connectToService()) {
804                            Slog.e(TAG, "Failed to bind to media container service");
805                            params.serviceError();
806                            return;
807                        } else {
808                            // Once we bind to the service, the first
809                            // pending request will be processed.
810                            mPendingInstalls.add(idx, params);
811                        }
812                    } else {
813                        mPendingInstalls.add(idx, params);
814                        // Already bound to the service. Just make
815                        // sure we trigger off processing the first request.
816                        if (idx == 0) {
817                            mHandler.sendEmptyMessage(MCS_BOUND);
818                        }
819                    }
820                    break;
821                }
822                case MCS_BOUND: {
823                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
824                    if (msg.obj != null) {
825                        mContainerService = (IMediaContainerService) msg.obj;
826                    }
827                    if (mContainerService == null) {
828                        // Something seriously wrong. Bail out
829                        Slog.e(TAG, "Cannot bind to media container service");
830                        for (HandlerParams params : mPendingInstalls) {
831                            // Indicate service bind error
832                            params.serviceError();
833                        }
834                        mPendingInstalls.clear();
835                    } else if (mPendingInstalls.size() > 0) {
836                        HandlerParams params = mPendingInstalls.get(0);
837                        if (params != null) {
838                            if (params.startCopy()) {
839                                // We are done...  look for more work or to
840                                // go idle.
841                                if (DEBUG_SD_INSTALL) Log.i(TAG,
842                                        "Checking for more work or unbind...");
843                                // Delete pending install
844                                if (mPendingInstalls.size() > 0) {
845                                    mPendingInstalls.remove(0);
846                                }
847                                if (mPendingInstalls.size() == 0) {
848                                    if (mBound) {
849                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
850                                                "Posting delayed MCS_UNBIND");
851                                        removeMessages(MCS_UNBIND);
852                                        Message ubmsg = obtainMessage(MCS_UNBIND);
853                                        // Unbind after a little delay, to avoid
854                                        // continual thrashing.
855                                        sendMessageDelayed(ubmsg, 10000);
856                                    }
857                                } else {
858                                    // There are more pending requests in queue.
859                                    // Just post MCS_BOUND message to trigger processing
860                                    // of next pending install.
861                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
862                                            "Posting MCS_BOUND for next work");
863                                    mHandler.sendEmptyMessage(MCS_BOUND);
864                                }
865                            }
866                        }
867                    } else {
868                        // Should never happen ideally.
869                        Slog.w(TAG, "Empty queue");
870                    }
871                    break;
872                }
873                case MCS_RECONNECT: {
874                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
875                    if (mPendingInstalls.size() > 0) {
876                        if (mBound) {
877                            disconnectService();
878                        }
879                        if (!connectToService()) {
880                            Slog.e(TAG, "Failed to bind to media container service");
881                            for (HandlerParams params : mPendingInstalls) {
882                                // Indicate service bind error
883                                params.serviceError();
884                            }
885                            mPendingInstalls.clear();
886                        }
887                    }
888                    break;
889                }
890                case MCS_UNBIND: {
891                    // If there is no actual work left, then time to unbind.
892                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
893
894                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
895                        if (mBound) {
896                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
897
898                            disconnectService();
899                        }
900                    } else if (mPendingInstalls.size() > 0) {
901                        // There are more pending requests in queue.
902                        // Just post MCS_BOUND message to trigger processing
903                        // of next pending install.
904                        mHandler.sendEmptyMessage(MCS_BOUND);
905                    }
906
907                    break;
908                }
909                case MCS_GIVE_UP: {
910                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
911                    mPendingInstalls.remove(0);
912                    break;
913                }
914                case SEND_PENDING_BROADCAST: {
915                    String packages[];
916                    ArrayList<String> components[];
917                    int size = 0;
918                    int uids[];
919                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
920                    synchronized (mPackages) {
921                        if (mPendingBroadcasts == null) {
922                            return;
923                        }
924                        size = mPendingBroadcasts.size();
925                        if (size <= 0) {
926                            // Nothing to be done. Just return
927                            return;
928                        }
929                        packages = new String[size];
930                        components = new ArrayList[size];
931                        uids = new int[size];
932                        int i = 0;  // filling out the above arrays
933
934                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
935                            int packageUserId = mPendingBroadcasts.userIdAt(n);
936                            Iterator<Map.Entry<String, ArrayList<String>>> it
937                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
938                                            .entrySet().iterator();
939                            while (it.hasNext() && i < size) {
940                                Map.Entry<String, ArrayList<String>> ent = it.next();
941                                packages[i] = ent.getKey();
942                                components[i] = ent.getValue();
943                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
944                                uids[i] = (ps != null)
945                                        ? UserHandle.getUid(packageUserId, ps.appId)
946                                        : -1;
947                                i++;
948                            }
949                        }
950                        size = i;
951                        mPendingBroadcasts.clear();
952                    }
953                    // Send broadcasts
954                    for (int i = 0; i < size; i++) {
955                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
956                    }
957                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
958                    break;
959                }
960                case START_CLEANING_PACKAGE: {
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
962                    final String packageName = (String)msg.obj;
963                    final int userId = msg.arg1;
964                    final boolean andCode = msg.arg2 != 0;
965                    synchronized (mPackages) {
966                        if (userId == UserHandle.USER_ALL) {
967                            int[] users = sUserManager.getUserIds();
968                            for (int user : users) {
969                                mSettings.addPackageToCleanLPw(
970                                        new PackageCleanItem(user, packageName, andCode));
971                            }
972                        } else {
973                            mSettings.addPackageToCleanLPw(
974                                    new PackageCleanItem(userId, packageName, andCode));
975                        }
976                    }
977                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
978                    startCleaningPackages();
979                } break;
980                case POST_INSTALL: {
981                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
982                    PostInstallData data = mRunningInstalls.get(msg.arg1);
983                    mRunningInstalls.delete(msg.arg1);
984                    boolean deleteOld = false;
985
986                    if (data != null) {
987                        InstallArgs args = data.args;
988                        PackageInstalledInfo res = data.res;
989
990                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
991                            res.removedInfo.sendBroadcast(false, true, false);
992                            Bundle extras = new Bundle(1);
993                            extras.putInt(Intent.EXTRA_UID, res.uid);
994                            // Determine the set of users who are adding this
995                            // package for the first time vs. those who are seeing
996                            // an update.
997                            int[] firstUsers;
998                            int[] updateUsers = new int[0];
999                            if (res.origUsers == null || res.origUsers.length == 0) {
1000                                firstUsers = res.newUsers;
1001                            } else {
1002                                firstUsers = new int[0];
1003                                for (int i=0; i<res.newUsers.length; i++) {
1004                                    int user = res.newUsers[i];
1005                                    boolean isNew = true;
1006                                    for (int j=0; j<res.origUsers.length; j++) {
1007                                        if (res.origUsers[j] == user) {
1008                                            isNew = false;
1009                                            break;
1010                                        }
1011                                    }
1012                                    if (isNew) {
1013                                        int[] newFirst = new int[firstUsers.length+1];
1014                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1015                                                firstUsers.length);
1016                                        newFirst[firstUsers.length] = user;
1017                                        firstUsers = newFirst;
1018                                    } else {
1019                                        int[] newUpdate = new int[updateUsers.length+1];
1020                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1021                                                updateUsers.length);
1022                                        newUpdate[updateUsers.length] = user;
1023                                        updateUsers = newUpdate;
1024                                    }
1025                                }
1026                            }
1027                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1028                                    res.pkg.applicationInfo.packageName,
1029                                    extras, null, null, firstUsers);
1030                            final boolean update = res.removedInfo.removedPackage != null;
1031                            if (update) {
1032                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1033                            }
1034                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1035                                    res.pkg.applicationInfo.packageName,
1036                                    extras, null, null, updateUsers);
1037                            if (update) {
1038                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1039                                        res.pkg.applicationInfo.packageName,
1040                                        extras, null, null, updateUsers);
1041                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1042                                        null, null,
1043                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1044
1045                                // treat asec-hosted packages like removable media on upgrade
1046                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1047                                    if (DEBUG_INSTALL) {
1048                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1049                                                + " is ASEC-hosted -> AVAILABLE");
1050                                    }
1051                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1052                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1053                                    pkgList.add(res.pkg.applicationInfo.packageName);
1054                                    sendResourcesChangedBroadcast(true, true,
1055                                            pkgList,uidArray, null);
1056                                }
1057                            }
1058                            if (res.removedInfo.args != null) {
1059                                // Remove the replaced package's older resources safely now
1060                                deleteOld = true;
1061                            }
1062
1063                            // Log current value of "unknown sources" setting
1064                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1065                                getUnknownSourcesSettings());
1066                        }
1067                        // Force a gc to clear up things
1068                        Runtime.getRuntime().gc();
1069                        // We delete after a gc for applications  on sdcard.
1070                        if (deleteOld) {
1071                            synchronized (mInstallLock) {
1072                                res.removedInfo.args.doPostDeleteLI(true);
1073                            }
1074                        }
1075                        if (args.observer != null) {
1076                            try {
1077                                args.observer.packageInstalled(res.name, res.returnCode);
1078                            } catch (RemoteException e) {
1079                                Slog.i(TAG, "Observer no longer exists.");
1080                            }
1081                        }
1082                        if (args.observer2 != null) {
1083                            try {
1084                                Bundle extras = extrasForInstallResult(res);
1085                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1086                            } catch (RemoteException e) {
1087                                Slog.i(TAG, "Observer no longer exists.");
1088                            }
1089                        }
1090                    } else {
1091                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1092                    }
1093                } break;
1094                case UPDATED_MEDIA_STATUS: {
1095                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1096                    boolean reportStatus = msg.arg1 == 1;
1097                    boolean doGc = msg.arg2 == 1;
1098                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1099                    if (doGc) {
1100                        // Force a gc to clear up stale containers.
1101                        Runtime.getRuntime().gc();
1102                    }
1103                    if (msg.obj != null) {
1104                        @SuppressWarnings("unchecked")
1105                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1106                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1107                        // Unload containers
1108                        unloadAllContainers(args);
1109                    }
1110                    if (reportStatus) {
1111                        try {
1112                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1113                            PackageHelper.getMountService().finishMediaUpdate();
1114                        } catch (RemoteException e) {
1115                            Log.e(TAG, "MountService not running?");
1116                        }
1117                    }
1118                } break;
1119                case WRITE_SETTINGS: {
1120                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1121                    synchronized (mPackages) {
1122                        removeMessages(WRITE_SETTINGS);
1123                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1124                        mSettings.writeLPr();
1125                        mDirtyUsers.clear();
1126                    }
1127                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1128                } break;
1129                case WRITE_PACKAGE_RESTRICTIONS: {
1130                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1131                    synchronized (mPackages) {
1132                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1133                        for (int userId : mDirtyUsers) {
1134                            mSettings.writePackageRestrictionsLPr(userId);
1135                        }
1136                        mDirtyUsers.clear();
1137                    }
1138                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139                } break;
1140                case CHECK_PENDING_VERIFICATION: {
1141                    final int verificationId = msg.arg1;
1142                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1143
1144                    if ((state != null) && !state.timeoutExtended()) {
1145                        final InstallArgs args = state.getInstallArgs();
1146                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1147                        mPendingVerification.remove(verificationId);
1148
1149                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1150
1151                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1152                            Slog.i(TAG, "Continuing with installation of "
1153                                    + args.packageURI.toString());
1154                            state.setVerifierResponse(Binder.getCallingUid(),
1155                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1156                            broadcastPackageVerified(verificationId, args.packageURI,
1157                                    PackageManager.VERIFICATION_ALLOW,
1158                                    state.getInstallArgs().getUser());
1159                            try {
1160                                ret = args.copyApk(mContainerService, true);
1161                            } catch (RemoteException e) {
1162                                Slog.e(TAG, "Could not contact the ContainerService");
1163                            }
1164                        } else {
1165                            broadcastPackageVerified(verificationId, args.packageURI,
1166                                    PackageManager.VERIFICATION_REJECT,
1167                                    state.getInstallArgs().getUser());
1168                        }
1169
1170                        processPendingInstall(args, ret);
1171                        mHandler.sendEmptyMessage(MCS_UNBIND);
1172                    }
1173                    break;
1174                }
1175                case PACKAGE_VERIFIED: {
1176                    final int verificationId = msg.arg1;
1177
1178                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1179                    if (state == null) {
1180                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1181                        break;
1182                    }
1183
1184                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1185
1186                    state.setVerifierResponse(response.callerUid, response.code);
1187
1188                    if (state.isVerificationComplete()) {
1189                        mPendingVerification.remove(verificationId);
1190
1191                        final InstallArgs args = state.getInstallArgs();
1192
1193                        int ret;
1194                        if (state.isInstallAllowed()) {
1195                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1196                            broadcastPackageVerified(verificationId, args.packageURI,
1197                                    response.code, state.getInstallArgs().getUser());
1198                            try {
1199                                ret = args.copyApk(mContainerService, true);
1200                            } catch (RemoteException e) {
1201                                Slog.e(TAG, "Could not contact the ContainerService");
1202                            }
1203                        } else {
1204                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1205                        }
1206
1207                        processPendingInstall(args, ret);
1208
1209                        mHandler.sendEmptyMessage(MCS_UNBIND);
1210                    }
1211
1212                    break;
1213                }
1214            }
1215        }
1216    }
1217
1218    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1219        Bundle extras = null;
1220        switch (res.returnCode) {
1221            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1222                extras = new Bundle();
1223                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1224                        res.origPermission);
1225                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1226                        res.origPackage);
1227                break;
1228            }
1229        }
1230        return extras;
1231    }
1232
1233    void scheduleWriteSettingsLocked() {
1234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1236        }
1237    }
1238
1239    void scheduleWritePackageRestrictionsLocked(int userId) {
1240        if (!sUserManager.exists(userId)) return;
1241        mDirtyUsers.add(userId);
1242        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1243            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1244        }
1245    }
1246
1247    public static final PackageManagerService main(Context context, Installer installer,
1248            boolean factoryTest, boolean onlyCore) {
1249        PackageManagerService m = new PackageManagerService(context, installer,
1250                factoryTest, onlyCore);
1251        ServiceManager.addService("package", m);
1252        return m;
1253    }
1254
1255    static String[] splitString(String str, char sep) {
1256        int count = 1;
1257        int i = 0;
1258        while ((i=str.indexOf(sep, i)) >= 0) {
1259            count++;
1260            i++;
1261        }
1262
1263        String[] res = new String[count];
1264        i=0;
1265        count = 0;
1266        int lastI=0;
1267        while ((i=str.indexOf(sep, i)) >= 0) {
1268            res[count] = str.substring(lastI, i);
1269            count++;
1270            i++;
1271            lastI = i;
1272        }
1273        res[count] = str.substring(lastI, str.length());
1274        return res;
1275    }
1276
1277    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1278        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1279                Context.DISPLAY_SERVICE);
1280        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1281    }
1282
1283    public PackageManagerService(Context context, Installer installer,
1284            boolean factoryTest, boolean onlyCore) {
1285        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1286                SystemClock.uptimeMillis());
1287
1288        if (mSdkVersion <= 0) {
1289            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1290        }
1291
1292        mContext = context;
1293        mFactoryTest = factoryTest;
1294        mOnlyCore = onlyCore;
1295        mMetrics = new DisplayMetrics();
1296        mSettings = new Settings(context);
1297        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1300                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309
1310        String separateProcesses = SystemProperties.get("debug.separate_processes");
1311        if (separateProcesses != null && separateProcesses.length() > 0) {
1312            if ("*".equals(separateProcesses)) {
1313                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1314                mSeparateProcesses = null;
1315                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1316            } else {
1317                mDefParseFlags = 0;
1318                mSeparateProcesses = separateProcesses.split(",");
1319                Slog.w(TAG, "Running with debug.separate_processes: "
1320                        + separateProcesses);
1321            }
1322        } else {
1323            mDefParseFlags = 0;
1324            mSeparateProcesses = null;
1325        }
1326
1327        mInstaller = installer;
1328
1329        getDefaultDisplayMetrics(context, mMetrics);
1330
1331        SystemConfig systemConfig = SystemConfig.getInstance();
1332        mGlobalGids = systemConfig.getGlobalGids();
1333        mSystemPermissions = systemConfig.getSystemPermissions();
1334        mAvailableFeatures = systemConfig.getAvailableFeatures();
1335
1336        synchronized (mInstallLock) {
1337        // writer
1338        synchronized (mPackages) {
1339            mHandlerThread = new ServiceThread(TAG,
1340                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1341            mHandlerThread.start();
1342            mHandler = new PackageHandler(mHandlerThread.getLooper());
1343            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1344
1345            File dataDir = Environment.getDataDirectory();
1346            mAppDataDir = new File(dataDir, "data");
1347            mAppInstallDir = new File(dataDir, "app");
1348            mAppLibInstallDir = new File(dataDir, "app-lib");
1349            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1350            mUserAppDataDir = new File(dataDir, "user");
1351            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1352            mAppStagingDir = new File(dataDir, "app-staging");
1353
1354            sUserManager = new UserManagerService(context, this,
1355                    mInstallLock, mPackages);
1356
1357            // Propagate permission configuration in to package manager.
1358            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1359                    = systemConfig.getPermissions();
1360            for (int i=0; i<permConfig.size(); i++) {
1361                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1362                BasePermission bp = mSettings.mPermissions.get(perm.name);
1363                if (bp == null) {
1364                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1365                    mSettings.mPermissions.put(perm.name, bp);
1366                }
1367                if (perm.gids != null) {
1368                    bp.gids = appendInts(bp.gids, perm.gids);
1369                }
1370            }
1371
1372            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1373            for (int i=0; i<libConfig.size(); i++) {
1374                mSharedLibraries.put(libConfig.keyAt(i),
1375                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1376            }
1377
1378            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1379
1380            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1381                    mSdkVersion, mOnlyCore);
1382
1383            String customResolverActivity = Resources.getSystem().getString(
1384                    R.string.config_customResolverActivity);
1385            if (TextUtils.isEmpty(customResolverActivity)) {
1386                customResolverActivity = null;
1387            } else {
1388                mCustomResolverComponentName = ComponentName.unflattenFromString(
1389                        customResolverActivity);
1390            }
1391
1392            long startTime = SystemClock.uptimeMillis();
1393
1394            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1395                    startTime);
1396
1397            // Set flag to monitor and not change apk file paths when
1398            // scanning install directories.
1399            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1400
1401            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1402
1403            /**
1404             * Add everything in the in the boot class path to the
1405             * list of process files because dexopt will have been run
1406             * if necessary during zygote startup.
1407             */
1408            String bootClassPath = System.getProperty("java.boot.class.path");
1409            if (bootClassPath != null) {
1410                String[] paths = splitString(bootClassPath, ':');
1411                for (int i=0; i<paths.length; i++) {
1412                    alreadyDexOpted.add(paths[i]);
1413                }
1414            } else {
1415                Slog.w(TAG, "No BOOTCLASSPATH found!");
1416            }
1417
1418            boolean didDexOptLibraryOrTool = false;
1419
1420            final List<String> instructionSets = getAllInstructionSets();
1421
1422            /**
1423             * Ensure all external libraries have had dexopt run on them.
1424             */
1425            if (mSharedLibraries.size() > 0) {
1426                // NOTE: For now, we're compiling these system "shared libraries"
1427                // (and framework jars) into all available architectures. It's possible
1428                // to compile them only when we come across an app that uses them (there's
1429                // already logic for that in scanPackageLI) but that adds some complexity.
1430                for (String instructionSet : instructionSets) {
1431                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1432                        final String lib = libEntry.path;
1433                        if (lib == null) {
1434                            continue;
1435                        }
1436
1437                        try {
1438                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1439                                alreadyDexOpted.add(lib);
1440
1441                                // The list of "shared libraries" we have at this point is
1442                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1443                                didDexOptLibraryOrTool = true;
1444                            }
1445                        } catch (FileNotFoundException e) {
1446                            Slog.w(TAG, "Library not found: " + lib);
1447                        } catch (IOException e) {
1448                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1449                                    + e.getMessage());
1450                        }
1451                    }
1452                }
1453            }
1454
1455            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1456
1457            // Gross hack for now: we know this file doesn't contain any
1458            // code, so don't dexopt it to avoid the resulting log spew.
1459            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1460
1461            // Gross hack for now: we know this file is only part of
1462            // the boot class path for art, so don't dexopt it to
1463            // avoid the resulting log spew.
1464            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1465
1466            /**
1467             * And there are a number of commands implemented in Java, which
1468             * we currently need to do the dexopt on so that they can be
1469             * run from a non-root shell.
1470             */
1471            String[] frameworkFiles = frameworkDir.list();
1472            if (frameworkFiles != null) {
1473                // TODO: We could compile these only for the most preferred ABI. We should
1474                // first double check that the dex files for these commands are not referenced
1475                // by other system apps.
1476                for (String instructionSet : instructionSets) {
1477                    for (int i=0; i<frameworkFiles.length; i++) {
1478                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1479                        String path = libPath.getPath();
1480                        // Skip the file if we already did it.
1481                        if (alreadyDexOpted.contains(path)) {
1482                            continue;
1483                        }
1484                        // Skip the file if it is not a type we want to dexopt.
1485                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1486                            continue;
1487                        }
1488                        try {
1489                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1490                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1491                                didDexOptLibraryOrTool = true;
1492                            }
1493                        } catch (FileNotFoundException e) {
1494                            Slog.w(TAG, "Jar not found: " + path);
1495                        } catch (IOException e) {
1496                            Slog.w(TAG, "Exception reading jar: " + path, e);
1497                        }
1498                    }
1499                }
1500            }
1501
1502            if (didDexOptLibraryOrTool) {
1503                // If we dexopted a library or tool, then something on the system has
1504                // changed. Consider this significant, and wipe away all other
1505                // existing dexopt files to ensure we don't leave any dangling around.
1506                //
1507                // TODO: This should be revisited because it isn't as good an indicator
1508                // as it used to be. It used to include the boot classpath but at some point
1509                // DexFile.isDexOptNeeded started returning false for the boot
1510                // class path files in all cases. It is very possible in a
1511                // small maintenance release update that the library and tool
1512                // jars may be unchanged but APK could be removed resulting in
1513                // unused dalvik-cache files.
1514                for (String instructionSet : instructionSets) {
1515                    mInstaller.pruneDexCache(instructionSet);
1516                }
1517
1518                // Additionally, delete all dex files from the root directory
1519                // since there shouldn't be any there anyway, unless we're upgrading
1520                // from an older OS version or a build that contained the "old" style
1521                // flat scheme.
1522                mInstaller.pruneDexCache(".");
1523            }
1524
1525            // Collect vendor overlay packages.
1526            // (Do this before scanning any apps.)
1527            // For security and version matching reason, only consider
1528            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1529            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1530            mVendorOverlayInstallObserver = new AppDirObserver(
1531                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1532            mVendorOverlayInstallObserver.startWatching();
1533            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1534                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1535
1536            // Find base frameworks (resource packages without code).
1537            mFrameworkInstallObserver = new AppDirObserver(
1538                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1539            mFrameworkInstallObserver.startWatching();
1540            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR
1542                    | PackageParser.PARSE_IS_PRIVILEGED,
1543                    scanMode | SCAN_NO_DEX, 0);
1544
1545            // Collected privileged system packages.
1546            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1547            mPrivilegedInstallObserver = new AppDirObserver(
1548                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1549            mPrivilegedInstallObserver.startWatching();
1550                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1551                        | PackageParser.PARSE_IS_SYSTEM_DIR
1552                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1553
1554            // Collect ordinary system packages.
1555            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1556            mSystemInstallObserver = new AppDirObserver(
1557                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1558            mSystemInstallObserver.startWatching();
1559            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1560                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1561
1562            // Collect all vendor packages.
1563            File vendorAppDir = new File("/vendor/app");
1564            try {
1565                vendorAppDir = vendorAppDir.getCanonicalFile();
1566            } catch (IOException e) {
1567                // failed to look up canonical path, continue with original one
1568            }
1569            mVendorInstallObserver = new AppDirObserver(
1570                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1571            mVendorInstallObserver.startWatching();
1572            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1574
1575            // Collect all OEM packages.
1576            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1577            mOemInstallObserver = new AppDirObserver(
1578                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1579            mOemInstallObserver.startWatching();
1580            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1581                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1582
1583            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1584            mInstaller.moveFiles();
1585
1586            // Prune any system packages that no longer exist.
1587            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1588            if (!mOnlyCore) {
1589                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1590                while (psit.hasNext()) {
1591                    PackageSetting ps = psit.next();
1592
1593                    /*
1594                     * If this is not a system app, it can't be a
1595                     * disable system app.
1596                     */
1597                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1598                        continue;
1599                    }
1600
1601                    /*
1602                     * If the package is scanned, it's not erased.
1603                     */
1604                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1605                    if (scannedPkg != null) {
1606                        /*
1607                         * If the system app is both scanned and in the
1608                         * disabled packages list, then it must have been
1609                         * added via OTA. Remove it from the currently
1610                         * scanned package so the previously user-installed
1611                         * application can be scanned.
1612                         */
1613                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1614                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1615                                    + "; removing system app");
1616                            removePackageLI(ps, true);
1617                        }
1618
1619                        continue;
1620                    }
1621
1622                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1623                        psit.remove();
1624                        String msg = "System package " + ps.name
1625                                + " no longer exists; wiping its data";
1626                        reportSettingsProblem(Log.WARN, msg);
1627                        removeDataDirsLI(ps.name);
1628                    } else {
1629                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1630                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1631                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1632                        }
1633                    }
1634                }
1635            }
1636
1637            //look for any incomplete package installations
1638            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1639            //clean up list
1640            for(int i = 0; i < deletePkgsList.size(); i++) {
1641                //clean up here
1642                cleanupInstallFailedPackage(deletePkgsList.get(i));
1643            }
1644            //delete tmp files
1645            deleteTempPackageFiles();
1646
1647            // Remove any shared userIDs that have no associated packages
1648            mSettings.pruneSharedUsersLPw();
1649
1650            if (!mOnlyCore) {
1651                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1652                        SystemClock.uptimeMillis());
1653                mAppInstallObserver = new AppDirObserver(
1654                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1655                mAppInstallObserver.startWatching();
1656                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1657
1658                mDrmAppInstallObserver = new AppDirObserver(
1659                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1660                mDrmAppInstallObserver.startWatching();
1661                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1662                        scanMode, 0);
1663
1664                /**
1665                 * Remove disable package settings for any updated system
1666                 * apps that were removed via an OTA. If they're not a
1667                 * previously-updated app, remove them completely.
1668                 * Otherwise, just revoke their system-level permissions.
1669                 */
1670                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1671                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1672                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1673
1674                    String msg;
1675                    if (deletedPkg == null) {
1676                        msg = "Updated system package " + deletedAppName
1677                                + " no longer exists; wiping its data";
1678                        removeDataDirsLI(deletedAppName);
1679                    } else {
1680                        msg = "Updated system app + " + deletedAppName
1681                                + " no longer present; removing system privileges for "
1682                                + deletedAppName;
1683
1684                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1685
1686                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1687                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1688                    }
1689                    reportSettingsProblem(Log.WARN, msg);
1690                }
1691            } else {
1692                mAppInstallObserver = null;
1693                mDrmAppInstallObserver = null;
1694            }
1695
1696            // Now that we know all of the shared libraries, update all clients to have
1697            // the correct library paths.
1698            updateAllSharedLibrariesLPw();
1699
1700            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1701                // NOTE: We ignore potential failures here during a system scan (like
1702                // the rest of the commands above) because there's precious little we
1703                // can do about it. A settings error is reported, though.
1704                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1705                        false /* force dexopt */, false /* defer dexopt */);
1706            }
1707
1708            // Now that we know all the packages we are keeping,
1709            // read and update their last usage times.
1710            mPackageUsage.readLP();
1711
1712            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1713                    SystemClock.uptimeMillis());
1714            Slog.i(TAG, "Time to scan packages: "
1715                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1716                    + " seconds");
1717
1718            // If the platform SDK has changed since the last time we booted,
1719            // we need to re-grant app permission to catch any new ones that
1720            // appear.  This is really a hack, and means that apps can in some
1721            // cases get permissions that the user didn't initially explicitly
1722            // allow...  it would be nice to have some better way to handle
1723            // this situation.
1724            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1725                    != mSdkVersion;
1726            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1727                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1728                    + "; regranting permissions for internal storage");
1729            mSettings.mInternalSdkPlatform = mSdkVersion;
1730
1731            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1732                    | (regrantPermissions
1733                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1734                            : 0));
1735
1736            // If this is the first boot, and it is a normal boot, then
1737            // we need to initialize the default preferred apps.
1738            if (!mRestoredSettings && !onlyCore) {
1739                mSettings.readDefaultPreferredAppsLPw(this, 0);
1740            }
1741
1742            // All the changes are done during package scanning.
1743            mSettings.updateInternalDatabaseVersion();
1744
1745            // can downgrade to reader
1746            mSettings.writeLPr();
1747
1748            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1749                    SystemClock.uptimeMillis());
1750
1751
1752            mRequiredVerifierPackage = getRequiredVerifierLPr();
1753        } // synchronized (mPackages)
1754        } // synchronized (mInstallLock)
1755
1756        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1757
1758        // Now after opening every single application zip, make sure they
1759        // are all flushed.  Not really needed, but keeps things nice and
1760        // tidy.
1761        Runtime.getRuntime().gc();
1762    }
1763
1764    @Override
1765    public boolean isFirstBoot() {
1766        return !mRestoredSettings;
1767    }
1768
1769    @Override
1770    public boolean isOnlyCoreApps() {
1771        return mOnlyCore;
1772    }
1773
1774    private String getRequiredVerifierLPr() {
1775        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1776        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1777                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1778
1779        String requiredVerifier = null;
1780
1781        final int N = receivers.size();
1782        for (int i = 0; i < N; i++) {
1783            final ResolveInfo info = receivers.get(i);
1784
1785            if (info.activityInfo == null) {
1786                continue;
1787            }
1788
1789            final String packageName = info.activityInfo.packageName;
1790
1791            final PackageSetting ps = mSettings.mPackages.get(packageName);
1792            if (ps == null) {
1793                continue;
1794            }
1795
1796            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1797            if (!gp.grantedPermissions
1798                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1799                continue;
1800            }
1801
1802            if (requiredVerifier != null) {
1803                throw new RuntimeException("There can be only one required verifier");
1804            }
1805
1806            requiredVerifier = packageName;
1807        }
1808
1809        return requiredVerifier;
1810    }
1811
1812    @Override
1813    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1814            throws RemoteException {
1815        try {
1816            return super.onTransact(code, data, reply, flags);
1817        } catch (RuntimeException e) {
1818            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1819                Slog.wtf(TAG, "Package Manager Crash", e);
1820            }
1821            throw e;
1822        }
1823    }
1824
1825    void cleanupInstallFailedPackage(PackageSetting ps) {
1826        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1827        removeDataDirsLI(ps.name);
1828        if (ps.codePath != null) {
1829            if (!ps.codePath.delete()) {
1830                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1831            }
1832        }
1833        if (ps.resourcePath != null) {
1834            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1835                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1836            }
1837        }
1838        mSettings.removePackageLPw(ps.name);
1839    }
1840
1841    static int[] appendInts(int[] cur, int[] add) {
1842        if (add == null) return cur;
1843        if (cur == null) return add;
1844        final int N = add.length;
1845        for (int i=0; i<N; i++) {
1846            cur = appendInt(cur, add[i]);
1847        }
1848        return cur;
1849    }
1850
1851    static int[] removeInts(int[] cur, int[] rem) {
1852        if (rem == null) return cur;
1853        if (cur == null) return cur;
1854        final int N = rem.length;
1855        for (int i=0; i<N; i++) {
1856            cur = removeInt(cur, rem[i]);
1857        }
1858        return cur;
1859    }
1860
1861    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1862        if (!sUserManager.exists(userId)) return null;
1863        final PackageSetting ps = (PackageSetting) p.mExtras;
1864        if (ps == null) {
1865            return null;
1866        }
1867        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1868        final PackageUserState state = ps.readUserState(userId);
1869        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1870                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1871                state, userId);
1872    }
1873
1874    @Override
1875    public boolean isPackageAvailable(String packageName, int userId) {
1876        if (!sUserManager.exists(userId)) return false;
1877        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1878        synchronized (mPackages) {
1879            PackageParser.Package p = mPackages.get(packageName);
1880            if (p != null) {
1881                final PackageSetting ps = (PackageSetting) p.mExtras;
1882                if (ps != null) {
1883                    final PackageUserState state = ps.readUserState(userId);
1884                    if (state != null) {
1885                        return PackageParser.isAvailable(state);
1886                    }
1887                }
1888            }
1889        }
1890        return false;
1891    }
1892
1893    @Override
1894    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1895        if (!sUserManager.exists(userId)) return null;
1896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1897        // reader
1898        synchronized (mPackages) {
1899            PackageParser.Package p = mPackages.get(packageName);
1900            if (DEBUG_PACKAGE_INFO)
1901                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1902            if (p != null) {
1903                return generatePackageInfo(p, flags, userId);
1904            }
1905            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1906                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1907            }
1908        }
1909        return null;
1910    }
1911
1912    @Override
1913    public String[] currentToCanonicalPackageNames(String[] names) {
1914        String[] out = new String[names.length];
1915        // reader
1916        synchronized (mPackages) {
1917            for (int i=names.length-1; i>=0; i--) {
1918                PackageSetting ps = mSettings.mPackages.get(names[i]);
1919                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1920            }
1921        }
1922        return out;
1923    }
1924
1925    @Override
1926    public String[] canonicalToCurrentPackageNames(String[] names) {
1927        String[] out = new String[names.length];
1928        // reader
1929        synchronized (mPackages) {
1930            for (int i=names.length-1; i>=0; i--) {
1931                String cur = mSettings.mRenamedPackages.get(names[i]);
1932                out[i] = cur != null ? cur : names[i];
1933            }
1934        }
1935        return out;
1936    }
1937
1938    @Override
1939    public int getPackageUid(String packageName, int userId) {
1940        if (!sUserManager.exists(userId)) return -1;
1941        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1942        // reader
1943        synchronized (mPackages) {
1944            PackageParser.Package p = mPackages.get(packageName);
1945            if(p != null) {
1946                return UserHandle.getUid(userId, p.applicationInfo.uid);
1947            }
1948            PackageSetting ps = mSettings.mPackages.get(packageName);
1949            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1950                return -1;
1951            }
1952            p = ps.pkg;
1953            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1954        }
1955    }
1956
1957    @Override
1958    public int[] getPackageGids(String packageName) {
1959        // reader
1960        synchronized (mPackages) {
1961            PackageParser.Package p = mPackages.get(packageName);
1962            if (DEBUG_PACKAGE_INFO)
1963                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1964            if (p != null) {
1965                final PackageSetting ps = (PackageSetting)p.mExtras;
1966                return ps.getGids();
1967            }
1968        }
1969        // stupid thing to indicate an error.
1970        return new int[0];
1971    }
1972
1973    static final PermissionInfo generatePermissionInfo(
1974            BasePermission bp, int flags) {
1975        if (bp.perm != null) {
1976            return PackageParser.generatePermissionInfo(bp.perm, flags);
1977        }
1978        PermissionInfo pi = new PermissionInfo();
1979        pi.name = bp.name;
1980        pi.packageName = bp.sourcePackage;
1981        pi.nonLocalizedLabel = bp.name;
1982        pi.protectionLevel = bp.protectionLevel;
1983        return pi;
1984    }
1985
1986    @Override
1987    public PermissionInfo getPermissionInfo(String name, int flags) {
1988        // reader
1989        synchronized (mPackages) {
1990            final BasePermission p = mSettings.mPermissions.get(name);
1991            if (p != null) {
1992                return generatePermissionInfo(p, flags);
1993            }
1994            return null;
1995        }
1996    }
1997
1998    @Override
1999    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2000        // reader
2001        synchronized (mPackages) {
2002            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2003            for (BasePermission p : mSettings.mPermissions.values()) {
2004                if (group == null) {
2005                    if (p.perm == null || p.perm.info.group == null) {
2006                        out.add(generatePermissionInfo(p, flags));
2007                    }
2008                } else {
2009                    if (p.perm != null && group.equals(p.perm.info.group)) {
2010                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2011                    }
2012                }
2013            }
2014
2015            if (out.size() > 0) {
2016                return out;
2017            }
2018            return mPermissionGroups.containsKey(group) ? out : null;
2019        }
2020    }
2021
2022    @Override
2023    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2024        // reader
2025        synchronized (mPackages) {
2026            return PackageParser.generatePermissionGroupInfo(
2027                    mPermissionGroups.get(name), flags);
2028        }
2029    }
2030
2031    @Override
2032    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2033        // reader
2034        synchronized (mPackages) {
2035            final int N = mPermissionGroups.size();
2036            ArrayList<PermissionGroupInfo> out
2037                    = new ArrayList<PermissionGroupInfo>(N);
2038            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2039                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2040            }
2041            return out;
2042        }
2043    }
2044
2045    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2046            int userId) {
2047        if (!sUserManager.exists(userId)) return null;
2048        PackageSetting ps = mSettings.mPackages.get(packageName);
2049        if (ps != null) {
2050            if (ps.pkg == null) {
2051                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2052                        flags, userId);
2053                if (pInfo != null) {
2054                    return pInfo.applicationInfo;
2055                }
2056                return null;
2057            }
2058            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2059                    ps.readUserState(userId), userId);
2060        }
2061        return null;
2062    }
2063
2064    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2065            int userId) {
2066        if (!sUserManager.exists(userId)) return null;
2067        PackageSetting ps = mSettings.mPackages.get(packageName);
2068        if (ps != null) {
2069            PackageParser.Package pkg = ps.pkg;
2070            if (pkg == null) {
2071                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2072                    return null;
2073                }
2074                // App code is gone, so we aren't worried about split paths
2075                pkg = new PackageParser.Package(packageName);
2076                pkg.applicationInfo.packageName = packageName;
2077                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2078                pkg.applicationInfo.sourceDir = ps.codePathString;
2079                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2080                pkg.applicationInfo.dataDir =
2081                        getDataPathForPackage(packageName, 0).getPath();
2082                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2083                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2084            }
2085            return generatePackageInfo(pkg, flags, userId);
2086        }
2087        return null;
2088    }
2089
2090    @Override
2091    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2092        if (!sUserManager.exists(userId)) return null;
2093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2094        // writer
2095        synchronized (mPackages) {
2096            PackageParser.Package p = mPackages.get(packageName);
2097            if (DEBUG_PACKAGE_INFO) Log.v(
2098                    TAG, "getApplicationInfo " + packageName
2099                    + ": " + p);
2100            if (p != null) {
2101                PackageSetting ps = mSettings.mPackages.get(packageName);
2102                if (ps == null) return null;
2103                // Note: isEnabledLP() does not apply here - always return info
2104                return PackageParser.generateApplicationInfo(
2105                        p, flags, ps.readUserState(userId), userId);
2106            }
2107            if ("android".equals(packageName)||"system".equals(packageName)) {
2108                return mAndroidApplication;
2109            }
2110            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2111                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2112            }
2113        }
2114        return null;
2115    }
2116
2117
2118    @Override
2119    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2120        mContext.enforceCallingOrSelfPermission(
2121                android.Manifest.permission.CLEAR_APP_CACHE, null);
2122        // Queue up an async operation since clearing cache may take a little while.
2123        mHandler.post(new Runnable() {
2124            public void run() {
2125                mHandler.removeCallbacks(this);
2126                int retCode = -1;
2127                synchronized (mInstallLock) {
2128                    retCode = mInstaller.freeCache(freeStorageSize);
2129                    if (retCode < 0) {
2130                        Slog.w(TAG, "Couldn't clear application caches");
2131                    }
2132                }
2133                if (observer != null) {
2134                    try {
2135                        observer.onRemoveCompleted(null, (retCode >= 0));
2136                    } catch (RemoteException e) {
2137                        Slog.w(TAG, "RemoveException when invoking call back");
2138                    }
2139                }
2140            }
2141        });
2142    }
2143
2144    @Override
2145    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2146        mContext.enforceCallingOrSelfPermission(
2147                android.Manifest.permission.CLEAR_APP_CACHE, null);
2148        // Queue up an async operation since clearing cache may take a little while.
2149        mHandler.post(new Runnable() {
2150            public void run() {
2151                mHandler.removeCallbacks(this);
2152                int retCode = -1;
2153                synchronized (mInstallLock) {
2154                    retCode = mInstaller.freeCache(freeStorageSize);
2155                    if (retCode < 0) {
2156                        Slog.w(TAG, "Couldn't clear application caches");
2157                    }
2158                }
2159                if(pi != null) {
2160                    try {
2161                        // Callback via pending intent
2162                        int code = (retCode >= 0) ? 1 : 0;
2163                        pi.sendIntent(null, code, null,
2164                                null, null);
2165                    } catch (SendIntentException e1) {
2166                        Slog.i(TAG, "Failed to send pending intent");
2167                    }
2168                }
2169            }
2170        });
2171    }
2172
2173    void freeStorage(long freeStorageSize) throws IOException {
2174        synchronized (mInstallLock) {
2175            if (mInstaller.freeCache(freeStorageSize) < 0) {
2176                throw new IOException("Failed to free enough space");
2177            }
2178        }
2179    }
2180
2181    @Override
2182    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2183        if (!sUserManager.exists(userId)) return null;
2184        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2185        synchronized (mPackages) {
2186            PackageParser.Activity a = mActivities.mActivities.get(component);
2187
2188            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2189            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2190                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2191                if (ps == null) return null;
2192                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2193                        userId);
2194            }
2195            if (mResolveComponentName.equals(component)) {
2196                return mResolveActivity;
2197            }
2198        }
2199        return null;
2200    }
2201
2202    @Override
2203    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2204            String resolvedType) {
2205        synchronized (mPackages) {
2206            PackageParser.Activity a = mActivities.mActivities.get(component);
2207            if (a == null) {
2208                return false;
2209            }
2210            for (int i=0; i<a.intents.size(); i++) {
2211                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2212                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2213                    return true;
2214                }
2215            }
2216            return false;
2217        }
2218    }
2219
2220    @Override
2221    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2222        if (!sUserManager.exists(userId)) return null;
2223        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2224        synchronized (mPackages) {
2225            PackageParser.Activity a = mReceivers.mActivities.get(component);
2226            if (DEBUG_PACKAGE_INFO) Log.v(
2227                TAG, "getReceiverInfo " + component + ": " + a);
2228            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2229                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2230                if (ps == null) return null;
2231                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2232                        userId);
2233            }
2234        }
2235        return null;
2236    }
2237
2238    @Override
2239    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2240        if (!sUserManager.exists(userId)) return null;
2241        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2242        synchronized (mPackages) {
2243            PackageParser.Service s = mServices.mServices.get(component);
2244            if (DEBUG_PACKAGE_INFO) Log.v(
2245                TAG, "getServiceInfo " + component + ": " + s);
2246            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2247                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2248                if (ps == null) return null;
2249                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2250                        userId);
2251            }
2252        }
2253        return null;
2254    }
2255
2256    @Override
2257    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2258        if (!sUserManager.exists(userId)) return null;
2259        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2260        synchronized (mPackages) {
2261            PackageParser.Provider p = mProviders.mProviders.get(component);
2262            if (DEBUG_PACKAGE_INFO) Log.v(
2263                TAG, "getProviderInfo " + component + ": " + p);
2264            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2265                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2266                if (ps == null) return null;
2267                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2268                        userId);
2269            }
2270        }
2271        return null;
2272    }
2273
2274    @Override
2275    public String[] getSystemSharedLibraryNames() {
2276        Set<String> libSet;
2277        synchronized (mPackages) {
2278            libSet = mSharedLibraries.keySet();
2279            int size = libSet.size();
2280            if (size > 0) {
2281                String[] libs = new String[size];
2282                libSet.toArray(libs);
2283                return libs;
2284            }
2285        }
2286        return null;
2287    }
2288
2289    @Override
2290    public FeatureInfo[] getSystemAvailableFeatures() {
2291        Collection<FeatureInfo> featSet;
2292        synchronized (mPackages) {
2293            featSet = mAvailableFeatures.values();
2294            int size = featSet.size();
2295            if (size > 0) {
2296                FeatureInfo[] features = new FeatureInfo[size+1];
2297                featSet.toArray(features);
2298                FeatureInfo fi = new FeatureInfo();
2299                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2300                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2301                features[size] = fi;
2302                return features;
2303            }
2304        }
2305        return null;
2306    }
2307
2308    @Override
2309    public boolean hasSystemFeature(String name) {
2310        synchronized (mPackages) {
2311            return mAvailableFeatures.containsKey(name);
2312        }
2313    }
2314
2315    private void checkValidCaller(int uid, int userId) {
2316        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2317            return;
2318
2319        throw new SecurityException("Caller uid=" + uid
2320                + " is not privileged to communicate with user=" + userId);
2321    }
2322
2323    @Override
2324    public int checkPermission(String permName, String pkgName) {
2325        synchronized (mPackages) {
2326            PackageParser.Package p = mPackages.get(pkgName);
2327            if (p != null && p.mExtras != null) {
2328                PackageSetting ps = (PackageSetting)p.mExtras;
2329                if (ps.sharedUser != null) {
2330                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2331                        return PackageManager.PERMISSION_GRANTED;
2332                    }
2333                } else if (ps.grantedPermissions.contains(permName)) {
2334                    return PackageManager.PERMISSION_GRANTED;
2335                }
2336            }
2337        }
2338        return PackageManager.PERMISSION_DENIED;
2339    }
2340
2341    @Override
2342    public int checkUidPermission(String permName, int uid) {
2343        synchronized (mPackages) {
2344            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2345            if (obj != null) {
2346                GrantedPermissions gp = (GrantedPermissions)obj;
2347                if (gp.grantedPermissions.contains(permName)) {
2348                    return PackageManager.PERMISSION_GRANTED;
2349                }
2350            } else {
2351                HashSet<String> perms = mSystemPermissions.get(uid);
2352                if (perms != null && perms.contains(permName)) {
2353                    return PackageManager.PERMISSION_GRANTED;
2354                }
2355            }
2356        }
2357        return PackageManager.PERMISSION_DENIED;
2358    }
2359
2360    /**
2361     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2362     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2363     * @param message the message to log on security exception
2364     */
2365    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2366            String message) {
2367        if (userId < 0) {
2368            throw new IllegalArgumentException("Invalid userId " + userId);
2369        }
2370        if (userId == UserHandle.getUserId(callingUid)) return;
2371        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2372            if (requireFullPermission) {
2373                mContext.enforceCallingOrSelfPermission(
2374                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2375            } else {
2376                try {
2377                    mContext.enforceCallingOrSelfPermission(
2378                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2379                } catch (SecurityException se) {
2380                    mContext.enforceCallingOrSelfPermission(
2381                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2382                }
2383            }
2384        }
2385    }
2386
2387    private BasePermission findPermissionTreeLP(String permName) {
2388        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2389            if (permName.startsWith(bp.name) &&
2390                    permName.length() > bp.name.length() &&
2391                    permName.charAt(bp.name.length()) == '.') {
2392                return bp;
2393            }
2394        }
2395        return null;
2396    }
2397
2398    private BasePermission checkPermissionTreeLP(String permName) {
2399        if (permName != null) {
2400            BasePermission bp = findPermissionTreeLP(permName);
2401            if (bp != null) {
2402                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2403                    return bp;
2404                }
2405                throw new SecurityException("Calling uid "
2406                        + Binder.getCallingUid()
2407                        + " is not allowed to add to permission tree "
2408                        + bp.name + " owned by uid " + bp.uid);
2409            }
2410        }
2411        throw new SecurityException("No permission tree found for " + permName);
2412    }
2413
2414    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2415        if (s1 == null) {
2416            return s2 == null;
2417        }
2418        if (s2 == null) {
2419            return false;
2420        }
2421        if (s1.getClass() != s2.getClass()) {
2422            return false;
2423        }
2424        return s1.equals(s2);
2425    }
2426
2427    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2428        if (pi1.icon != pi2.icon) return false;
2429        if (pi1.logo != pi2.logo) return false;
2430        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2431        if (!compareStrings(pi1.name, pi2.name)) return false;
2432        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2433        // We'll take care of setting this one.
2434        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2435        // These are not currently stored in settings.
2436        //if (!compareStrings(pi1.group, pi2.group)) return false;
2437        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2438        //if (pi1.labelRes != pi2.labelRes) return false;
2439        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2440        return true;
2441    }
2442
2443    int permissionInfoFootprint(PermissionInfo info) {
2444        int size = info.name.length();
2445        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2446        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2447        return size;
2448    }
2449
2450    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2451        int size = 0;
2452        for (BasePermission perm : mSettings.mPermissions.values()) {
2453            if (perm.uid == tree.uid) {
2454                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2455            }
2456        }
2457        return size;
2458    }
2459
2460    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2461        // We calculate the max size of permissions defined by this uid and throw
2462        // if that plus the size of 'info' would exceed our stated maximum.
2463        if (tree.uid != Process.SYSTEM_UID) {
2464            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2465            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2466                throw new SecurityException("Permission tree size cap exceeded");
2467            }
2468        }
2469    }
2470
2471    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2472        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2473            throw new SecurityException("Label must be specified in permission");
2474        }
2475        BasePermission tree = checkPermissionTreeLP(info.name);
2476        BasePermission bp = mSettings.mPermissions.get(info.name);
2477        boolean added = bp == null;
2478        boolean changed = true;
2479        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2480        if (added) {
2481            enforcePermissionCapLocked(info, tree);
2482            bp = new BasePermission(info.name, tree.sourcePackage,
2483                    BasePermission.TYPE_DYNAMIC);
2484        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2485            throw new SecurityException(
2486                    "Not allowed to modify non-dynamic permission "
2487                    + info.name);
2488        } else {
2489            if (bp.protectionLevel == fixedLevel
2490                    && bp.perm.owner.equals(tree.perm.owner)
2491                    && bp.uid == tree.uid
2492                    && comparePermissionInfos(bp.perm.info, info)) {
2493                changed = false;
2494            }
2495        }
2496        bp.protectionLevel = fixedLevel;
2497        info = new PermissionInfo(info);
2498        info.protectionLevel = fixedLevel;
2499        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2500        bp.perm.info.packageName = tree.perm.info.packageName;
2501        bp.uid = tree.uid;
2502        if (added) {
2503            mSettings.mPermissions.put(info.name, bp);
2504        }
2505        if (changed) {
2506            if (!async) {
2507                mSettings.writeLPr();
2508            } else {
2509                scheduleWriteSettingsLocked();
2510            }
2511        }
2512        return added;
2513    }
2514
2515    @Override
2516    public boolean addPermission(PermissionInfo info) {
2517        synchronized (mPackages) {
2518            return addPermissionLocked(info, false);
2519        }
2520    }
2521
2522    @Override
2523    public boolean addPermissionAsync(PermissionInfo info) {
2524        synchronized (mPackages) {
2525            return addPermissionLocked(info, true);
2526        }
2527    }
2528
2529    @Override
2530    public void removePermission(String name) {
2531        synchronized (mPackages) {
2532            checkPermissionTreeLP(name);
2533            BasePermission bp = mSettings.mPermissions.get(name);
2534            if (bp != null) {
2535                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2536                    throw new SecurityException(
2537                            "Not allowed to modify non-dynamic permission "
2538                            + name);
2539                }
2540                mSettings.mPermissions.remove(name);
2541                mSettings.writeLPr();
2542            }
2543        }
2544    }
2545
2546    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2547        int index = pkg.requestedPermissions.indexOf(bp.name);
2548        if (index == -1) {
2549            throw new SecurityException("Package " + pkg.packageName
2550                    + " has not requested permission " + bp.name);
2551        }
2552        boolean isNormal =
2553                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2554                        == PermissionInfo.PROTECTION_NORMAL);
2555        boolean isDangerous =
2556                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2557                        == PermissionInfo.PROTECTION_DANGEROUS);
2558        boolean isDevelopment =
2559                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2560
2561        if (!isNormal && !isDangerous && !isDevelopment) {
2562            throw new SecurityException("Permission " + bp.name
2563                    + " is not a changeable permission type");
2564        }
2565
2566        if (isNormal || isDangerous) {
2567            if (pkg.requestedPermissionsRequired.get(index)) {
2568                throw new SecurityException("Can't change " + bp.name
2569                        + ". It is required by the application");
2570            }
2571        }
2572    }
2573
2574    @Override
2575    public void grantPermission(String packageName, String permissionName) {
2576        mContext.enforceCallingOrSelfPermission(
2577                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2578        synchronized (mPackages) {
2579            final PackageParser.Package pkg = mPackages.get(packageName);
2580            if (pkg == null) {
2581                throw new IllegalArgumentException("Unknown package: " + packageName);
2582            }
2583            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2584            if (bp == null) {
2585                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2586            }
2587
2588            checkGrantRevokePermissions(pkg, bp);
2589
2590            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2591            if (ps == null) {
2592                return;
2593            }
2594            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2595            if (gp.grantedPermissions.add(permissionName)) {
2596                if (ps.haveGids) {
2597                    gp.gids = appendInts(gp.gids, bp.gids);
2598                }
2599                mSettings.writeLPr();
2600            }
2601        }
2602    }
2603
2604    @Override
2605    public void revokePermission(String packageName, String permissionName) {
2606        int changedAppId = -1;
2607
2608        synchronized (mPackages) {
2609            final PackageParser.Package pkg = mPackages.get(packageName);
2610            if (pkg == null) {
2611                throw new IllegalArgumentException("Unknown package: " + packageName);
2612            }
2613            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2614                mContext.enforceCallingOrSelfPermission(
2615                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2616            }
2617            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2618            if (bp == null) {
2619                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2620            }
2621
2622            checkGrantRevokePermissions(pkg, bp);
2623
2624            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2625            if (ps == null) {
2626                return;
2627            }
2628            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2629            if (gp.grantedPermissions.remove(permissionName)) {
2630                gp.grantedPermissions.remove(permissionName);
2631                if (ps.haveGids) {
2632                    gp.gids = removeInts(gp.gids, bp.gids);
2633                }
2634                mSettings.writeLPr();
2635                changedAppId = ps.appId;
2636            }
2637        }
2638
2639        if (changedAppId >= 0) {
2640            // We changed the perm on someone, kill its processes.
2641            IActivityManager am = ActivityManagerNative.getDefault();
2642            if (am != null) {
2643                final int callingUserId = UserHandle.getCallingUserId();
2644                final long ident = Binder.clearCallingIdentity();
2645                try {
2646                    //XXX we should only revoke for the calling user's app permissions,
2647                    // but for now we impact all users.
2648                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2649                    //        "revoke " + permissionName);
2650                    int[] users = sUserManager.getUserIds();
2651                    for (int user : users) {
2652                        am.killUid(UserHandle.getUid(user, changedAppId),
2653                                "revoke " + permissionName);
2654                    }
2655                } catch (RemoteException e) {
2656                } finally {
2657                    Binder.restoreCallingIdentity(ident);
2658                }
2659            }
2660        }
2661    }
2662
2663    @Override
2664    public boolean isProtectedBroadcast(String actionName) {
2665        synchronized (mPackages) {
2666            return mProtectedBroadcasts.contains(actionName);
2667        }
2668    }
2669
2670    @Override
2671    public int checkSignatures(String pkg1, String pkg2) {
2672        synchronized (mPackages) {
2673            final PackageParser.Package p1 = mPackages.get(pkg1);
2674            final PackageParser.Package p2 = mPackages.get(pkg2);
2675            if (p1 == null || p1.mExtras == null
2676                    || p2 == null || p2.mExtras == null) {
2677                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2678            }
2679            return compareSignatures(p1.mSignatures, p2.mSignatures);
2680        }
2681    }
2682
2683    @Override
2684    public int checkUidSignatures(int uid1, int uid2) {
2685        // Map to base uids.
2686        uid1 = UserHandle.getAppId(uid1);
2687        uid2 = UserHandle.getAppId(uid2);
2688        // reader
2689        synchronized (mPackages) {
2690            Signature[] s1;
2691            Signature[] s2;
2692            Object obj = mSettings.getUserIdLPr(uid1);
2693            if (obj != null) {
2694                if (obj instanceof SharedUserSetting) {
2695                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2696                } else if (obj instanceof PackageSetting) {
2697                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2698                } else {
2699                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2700                }
2701            } else {
2702                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2703            }
2704            obj = mSettings.getUserIdLPr(uid2);
2705            if (obj != null) {
2706                if (obj instanceof SharedUserSetting) {
2707                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2708                } else if (obj instanceof PackageSetting) {
2709                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2710                } else {
2711                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2712                }
2713            } else {
2714                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715            }
2716            return compareSignatures(s1, s2);
2717        }
2718    }
2719
2720    /**
2721     * Compares two sets of signatures. Returns:
2722     * <br />
2723     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2724     * <br />
2725     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2726     * <br />
2727     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2728     * <br />
2729     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2730     * <br />
2731     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2732     */
2733    static int compareSignatures(Signature[] s1, Signature[] s2) {
2734        if (s1 == null) {
2735            return s2 == null
2736                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2737                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2738        }
2739
2740        if (s2 == null) {
2741            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2742        }
2743
2744        if (s1.length != s2.length) {
2745            return PackageManager.SIGNATURE_NO_MATCH;
2746        }
2747
2748        // Since both signature sets are of size 1, we can compare without HashSets.
2749        if (s1.length == 1) {
2750            return s1[0].equals(s2[0]) ?
2751                    PackageManager.SIGNATURE_MATCH :
2752                    PackageManager.SIGNATURE_NO_MATCH;
2753        }
2754
2755        HashSet<Signature> set1 = new HashSet<Signature>();
2756        for (Signature sig : s1) {
2757            set1.add(sig);
2758        }
2759        HashSet<Signature> set2 = new HashSet<Signature>();
2760        for (Signature sig : s2) {
2761            set2.add(sig);
2762        }
2763        // Make sure s2 contains all signatures in s1.
2764        if (set1.equals(set2)) {
2765            return PackageManager.SIGNATURE_MATCH;
2766        }
2767        return PackageManager.SIGNATURE_NO_MATCH;
2768    }
2769
2770    /**
2771     * If the database version for this type of package (internal storage or
2772     * external storage) is less than the version where package signatures
2773     * were updated, return true.
2774     */
2775    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2776        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2777                DatabaseVersion.SIGNATURE_END_ENTITY))
2778                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2779                        DatabaseVersion.SIGNATURE_END_ENTITY));
2780    }
2781
2782    /**
2783     * Used for backward compatibility to make sure any packages with
2784     * certificate chains get upgraded to the new style. {@code existingSigs}
2785     * will be in the old format (since they were stored on disk from before the
2786     * system upgrade) and {@code scannedSigs} will be in the newer format.
2787     */
2788    private int compareSignaturesCompat(PackageSignatures existingSigs,
2789            PackageParser.Package scannedPkg) {
2790        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2791            return PackageManager.SIGNATURE_NO_MATCH;
2792        }
2793
2794        HashSet<Signature> existingSet = new HashSet<Signature>();
2795        for (Signature sig : existingSigs.mSignatures) {
2796            existingSet.add(sig);
2797        }
2798        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2799        for (Signature sig : scannedPkg.mSignatures) {
2800            try {
2801                Signature[] chainSignatures = sig.getChainSignatures();
2802                for (Signature chainSig : chainSignatures) {
2803                    scannedCompatSet.add(chainSig);
2804                }
2805            } catch (CertificateEncodingException e) {
2806                scannedCompatSet.add(sig);
2807            }
2808        }
2809        /*
2810         * Make sure the expanded scanned set contains all signatures in the
2811         * existing one.
2812         */
2813        if (scannedCompatSet.equals(existingSet)) {
2814            // Migrate the old signatures to the new scheme.
2815            existingSigs.assignSignatures(scannedPkg.mSignatures);
2816            // The new KeySets will be re-added later in the scanning process.
2817            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2818            return PackageManager.SIGNATURE_MATCH;
2819        }
2820        return PackageManager.SIGNATURE_NO_MATCH;
2821    }
2822
2823    @Override
2824    public String[] getPackagesForUid(int uid) {
2825        uid = UserHandle.getAppId(uid);
2826        // reader
2827        synchronized (mPackages) {
2828            Object obj = mSettings.getUserIdLPr(uid);
2829            if (obj instanceof SharedUserSetting) {
2830                final SharedUserSetting sus = (SharedUserSetting) obj;
2831                final int N = sus.packages.size();
2832                final String[] res = new String[N];
2833                final Iterator<PackageSetting> it = sus.packages.iterator();
2834                int i = 0;
2835                while (it.hasNext()) {
2836                    res[i++] = it.next().name;
2837                }
2838                return res;
2839            } else if (obj instanceof PackageSetting) {
2840                final PackageSetting ps = (PackageSetting) obj;
2841                return new String[] { ps.name };
2842            }
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public String getNameForUid(int uid) {
2849        // reader
2850        synchronized (mPackages) {
2851            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2852            if (obj instanceof SharedUserSetting) {
2853                final SharedUserSetting sus = (SharedUserSetting) obj;
2854                return sus.name + ":" + sus.userId;
2855            } else if (obj instanceof PackageSetting) {
2856                final PackageSetting ps = (PackageSetting) obj;
2857                return ps.name;
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public int getUidForSharedUser(String sharedUserName) {
2865        if(sharedUserName == null) {
2866            return -1;
2867        }
2868        // reader
2869        synchronized (mPackages) {
2870            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2871            if (suid == null) {
2872                return -1;
2873            }
2874            return suid.userId;
2875        }
2876    }
2877
2878    @Override
2879    public int getFlagsForUid(int uid) {
2880        synchronized (mPackages) {
2881            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2882            if (obj instanceof SharedUserSetting) {
2883                final SharedUserSetting sus = (SharedUserSetting) obj;
2884                return sus.pkgFlags;
2885            } else if (obj instanceof PackageSetting) {
2886                final PackageSetting ps = (PackageSetting) obj;
2887                return ps.pkgFlags;
2888            }
2889        }
2890        return 0;
2891    }
2892
2893    @Override
2894    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2895            int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2900    }
2901
2902    @Override
2903    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2904            IntentFilter filter, int match, ComponentName activity) {
2905        final int userId = UserHandle.getCallingUserId();
2906        if (DEBUG_PREFERRED) {
2907            Log.v(TAG, "setLastChosenActivity intent=" + intent
2908                + " resolvedType=" + resolvedType
2909                + " flags=" + flags
2910                + " filter=" + filter
2911                + " match=" + match
2912                + " activity=" + activity);
2913            filter.dump(new PrintStreamPrinter(System.out), "    ");
2914        }
2915        intent.setComponent(null);
2916        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2917        // Find any earlier preferred or last chosen entries and nuke them
2918        findPreferredActivity(intent, resolvedType,
2919                flags, query, 0, false, true, false, userId);
2920        // Add the new activity as the last chosen for this filter
2921        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2922    }
2923
2924    @Override
2925    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2926        final int userId = UserHandle.getCallingUserId();
2927        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2928        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2929        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2930                false, false, false, userId);
2931    }
2932
2933    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2934            int flags, List<ResolveInfo> query, int userId) {
2935        if (query != null) {
2936            final int N = query.size();
2937            if (N == 1) {
2938                return query.get(0);
2939            } else if (N > 1) {
2940                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2941                // If there is more than one activity with the same priority,
2942                // then let the user decide between them.
2943                ResolveInfo r0 = query.get(0);
2944                ResolveInfo r1 = query.get(1);
2945                if (DEBUG_INTENT_MATCHING || debug) {
2946                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2947                            + r1.activityInfo.name + "=" + r1.priority);
2948                }
2949                // If the first activity has a higher priority, or a different
2950                // default, then it is always desireable to pick it.
2951                if (r0.priority != r1.priority
2952                        || r0.preferredOrder != r1.preferredOrder
2953                        || r0.isDefault != r1.isDefault) {
2954                    return query.get(0);
2955                }
2956                // If we have saved a preference for a preferred activity for
2957                // this Intent, use that.
2958                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2959                        flags, query, r0.priority, true, false, debug, userId);
2960                if (ri != null) {
2961                    return ri;
2962                }
2963                if (userId != 0) {
2964                    ri = new ResolveInfo(mResolveInfo);
2965                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2966                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2967                            ri.activityInfo.applicationInfo);
2968                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2969                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2970                    return ri;
2971                }
2972                return mResolveInfo;
2973            }
2974        }
2975        return null;
2976    }
2977
2978    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2979            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2980        final int N = query.size();
2981        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2982                .get(userId);
2983        // Get the list of persistent preferred activities that handle the intent
2984        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2985        List<PersistentPreferredActivity> pprefs = ppir != null
2986                ? ppir.queryIntent(intent, resolvedType,
2987                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2988                : null;
2989        if (pprefs != null && pprefs.size() > 0) {
2990            final int M = pprefs.size();
2991            for (int i=0; i<M; i++) {
2992                final PersistentPreferredActivity ppa = pprefs.get(i);
2993                if (DEBUG_PREFERRED || debug) {
2994                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2995                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2996                            + "\n  component=" + ppa.mComponent);
2997                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2998                }
2999                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3000                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3001                if (DEBUG_PREFERRED || debug) {
3002                    Slog.v(TAG, "Found persistent preferred activity:");
3003                    if (ai != null) {
3004                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3005                    } else {
3006                        Slog.v(TAG, "  null");
3007                    }
3008                }
3009                if (ai == null) {
3010                    // This previously registered persistent preferred activity
3011                    // component is no longer known. Ignore it and do NOT remove it.
3012                    continue;
3013                }
3014                for (int j=0; j<N; j++) {
3015                    final ResolveInfo ri = query.get(j);
3016                    if (!ri.activityInfo.applicationInfo.packageName
3017                            .equals(ai.applicationInfo.packageName)) {
3018                        continue;
3019                    }
3020                    if (!ri.activityInfo.name.equals(ai.name)) {
3021                        continue;
3022                    }
3023                    //  Found a persistent preference that can handle the intent.
3024                    if (DEBUG_PREFERRED || debug) {
3025                        Slog.v(TAG, "Returning persistent preferred activity: " +
3026                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3027                    }
3028                    return ri;
3029                }
3030            }
3031        }
3032        return null;
3033    }
3034
3035    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3036            List<ResolveInfo> query, int priority, boolean always,
3037            boolean removeMatches, boolean debug, int userId) {
3038        if (!sUserManager.exists(userId)) return null;
3039        // writer
3040        synchronized (mPackages) {
3041            if (intent.getSelector() != null) {
3042                intent = intent.getSelector();
3043            }
3044            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3045
3046            // Try to find a matching persistent preferred activity.
3047            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3048                    debug, userId);
3049
3050            // If a persistent preferred activity matched, use it.
3051            if (pri != null) {
3052                return pri;
3053            }
3054
3055            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3056            // Get the list of preferred activities that handle the intent
3057            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3058            List<PreferredActivity> prefs = pir != null
3059                    ? pir.queryIntent(intent, resolvedType,
3060                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3061                    : null;
3062            if (prefs != null && prefs.size() > 0) {
3063                // First figure out how good the original match set is.
3064                // We will only allow preferred activities that came
3065                // from the same match quality.
3066                int match = 0;
3067
3068                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3069
3070                final int N = query.size();
3071                for (int j=0; j<N; j++) {
3072                    final ResolveInfo ri = query.get(j);
3073                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3074                            + ": 0x" + Integer.toHexString(match));
3075                    if (ri.match > match) {
3076                        match = ri.match;
3077                    }
3078                }
3079
3080                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3081                        + Integer.toHexString(match));
3082
3083                match &= IntentFilter.MATCH_CATEGORY_MASK;
3084                final int M = prefs.size();
3085                for (int i=0; i<M; i++) {
3086                    final PreferredActivity pa = prefs.get(i);
3087                    if (DEBUG_PREFERRED || debug) {
3088                        Slog.v(TAG, "Checking PreferredActivity ds="
3089                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3090                                + "\n  component=" + pa.mPref.mComponent);
3091                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3092                    }
3093                    if (pa.mPref.mMatch != match) {
3094                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3095                                + Integer.toHexString(pa.mPref.mMatch));
3096                        continue;
3097                    }
3098                    // If it's not an "always" type preferred activity and that's what we're
3099                    // looking for, skip it.
3100                    if (always && !pa.mPref.mAlways) {
3101                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3102                        continue;
3103                    }
3104                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3105                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3106                    if (DEBUG_PREFERRED || debug) {
3107                        Slog.v(TAG, "Found preferred activity:");
3108                        if (ai != null) {
3109                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3110                        } else {
3111                            Slog.v(TAG, "  null");
3112                        }
3113                    }
3114                    if (ai == null) {
3115                        // This previously registered preferred activity
3116                        // component is no longer known.  Most likely an update
3117                        // to the app was installed and in the new version this
3118                        // component no longer exists.  Clean it up by removing
3119                        // it from the preferred activities list, and skip it.
3120                        Slog.w(TAG, "Removing dangling preferred activity: "
3121                                + pa.mPref.mComponent);
3122                        pir.removeFilter(pa);
3123                        continue;
3124                    }
3125                    for (int j=0; j<N; j++) {
3126                        final ResolveInfo ri = query.get(j);
3127                        if (!ri.activityInfo.applicationInfo.packageName
3128                                .equals(ai.applicationInfo.packageName)) {
3129                            continue;
3130                        }
3131                        if (!ri.activityInfo.name.equals(ai.name)) {
3132                            continue;
3133                        }
3134
3135                        if (removeMatches) {
3136                            pir.removeFilter(pa);
3137                            if (DEBUG_PREFERRED) {
3138                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3139                            }
3140                            break;
3141                        }
3142
3143                        // Okay we found a previously set preferred or last chosen app.
3144                        // If the result set is different from when this
3145                        // was created, we need to clear it and re-ask the
3146                        // user their preference, if we're looking for an "always" type entry.
3147                        if (always && !pa.mPref.sameSet(query, priority)) {
3148                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3149                                    + intent + " type " + resolvedType);
3150                            if (DEBUG_PREFERRED) {
3151                                Slog.v(TAG, "Removing preferred activity since set changed "
3152                                        + pa.mPref.mComponent);
3153                            }
3154                            pir.removeFilter(pa);
3155                            // Re-add the filter as a "last chosen" entry (!always)
3156                            PreferredActivity lastChosen = new PreferredActivity(
3157                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3158                            pir.addFilter(lastChosen);
3159                            mSettings.writePackageRestrictionsLPr(userId);
3160                            return null;
3161                        }
3162
3163                        // Yay! Either the set matched or we're looking for the last chosen
3164                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3165                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3166                        mSettings.writePackageRestrictionsLPr(userId);
3167                        return ri;
3168                    }
3169                }
3170            }
3171            mSettings.writePackageRestrictionsLPr(userId);
3172        }
3173        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3174        return null;
3175    }
3176
3177    /*
3178     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3179     */
3180    @Override
3181    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3182            int targetUserId) {
3183        mContext.enforceCallingOrSelfPermission(
3184                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3185        List<CrossProfileIntentFilter> matches =
3186                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3187        if (matches != null) {
3188            int size = matches.size();
3189            for (int i = 0; i < size; i++) {
3190                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3191            }
3192        }
3193
3194        ArrayList<String> packageNames = null;
3195        SparseArray<ArrayList<String>> fromSource =
3196                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3197        if (fromSource != null) {
3198            packageNames = fromSource.get(targetUserId);
3199        }
3200        if (packageNames.contains(intent.getPackage())) {
3201            return true;
3202        }
3203        // We need the package name, so we try to resolve with the loosest flags possible
3204        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3205                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3206        int count = resolveInfos.size();
3207        for (int i = 0; i < count; i++) {
3208            ResolveInfo resolveInfo = resolveInfos.get(i);
3209            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3210                return true;
3211            }
3212        }
3213        return false;
3214    }
3215
3216    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3217            String resolvedType, int userId) {
3218        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3219        if (resolver != null) {
3220            return resolver.queryIntent(intent, resolvedType, false, userId);
3221        }
3222        return null;
3223    }
3224
3225    @Override
3226    public List<ResolveInfo> queryIntentActivities(Intent intent,
3227            String resolvedType, int flags, int userId) {
3228        if (!sUserManager.exists(userId)) return Collections.emptyList();
3229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3230        ComponentName comp = intent.getComponent();
3231        if (comp == null) {
3232            if (intent.getSelector() != null) {
3233                intent = intent.getSelector();
3234                comp = intent.getComponent();
3235            }
3236        }
3237
3238        if (comp != null) {
3239            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3240            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3241            if (ai != null) {
3242                final ResolveInfo ri = new ResolveInfo();
3243                ri.activityInfo = ai;
3244                list.add(ri);
3245            }
3246            return list;
3247        }
3248
3249        // reader
3250        synchronized (mPackages) {
3251            final String pkgName = intent.getPackage();
3252            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3253            if (pkgName == null) {
3254                ResolveInfo resolveInfo = null;
3255                if (queryCrossProfile) {
3256                    // Check if the intent needs to be forwarded to another user for this package
3257                    ArrayList<ResolveInfo> crossProfileResult =
3258                            queryIntentActivitiesCrossProfilePackage(
3259                                    intent, resolvedType, flags, userId);
3260                    if (!crossProfileResult.isEmpty()) {
3261                        // Skip the current profile
3262                        return crossProfileResult;
3263                    }
3264                    List<CrossProfileIntentFilter> matchingFilters =
3265                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3266                    // Check for results that need to skip the current profile.
3267                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3268                            resolvedType, flags, userId);
3269                    if (resolveInfo != null) {
3270                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3271                        result.add(resolveInfo);
3272                        return result;
3273                    }
3274                    // Check for cross profile results.
3275                    resolveInfo = queryCrossProfileIntents(
3276                            matchingFilters, intent, resolvedType, flags, userId);
3277                }
3278                // Check for results in the current profile.
3279                List<ResolveInfo> result = mActivities.queryIntent(
3280                        intent, resolvedType, flags, userId);
3281                if (resolveInfo != null) {
3282                    result.add(resolveInfo);
3283                }
3284                return result;
3285            }
3286            final PackageParser.Package pkg = mPackages.get(pkgName);
3287            if (pkg != null) {
3288                if (queryCrossProfile) {
3289                    ArrayList<ResolveInfo> crossProfileResult =
3290                            queryIntentActivitiesCrossProfilePackage(
3291                                    intent, resolvedType, flags, userId, pkg, pkgName);
3292                    if (!crossProfileResult.isEmpty()) {
3293                        // Skip the current profile
3294                        return crossProfileResult;
3295                    }
3296                }
3297                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3298                        pkg.activities, userId);
3299            }
3300            return new ArrayList<ResolveInfo>();
3301        }
3302    }
3303
3304    private ResolveInfo querySkipCurrentProfileIntents(
3305            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3306            int flags, int sourceUserId) {
3307        if (matchingFilters != null) {
3308            int size = matchingFilters.size();
3309            for (int i = 0; i < size; i ++) {
3310                CrossProfileIntentFilter filter = matchingFilters.get(i);
3311                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3312                    // Checking if there are activities in the target user that can handle the
3313                    // intent.
3314                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3315                            flags, sourceUserId);
3316                    if (resolveInfo != null) {
3317                        return resolveInfo;
3318                    }
3319                }
3320            }
3321        }
3322        return null;
3323    }
3324
3325    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3326            Intent intent, String resolvedType, int flags, int userId) {
3327        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3328        SparseArray<ArrayList<String>> sourceForwardingInfo =
3329                mSettings.mCrossProfilePackageInfo.get(userId);
3330        if (sourceForwardingInfo != null) {
3331            int NI = sourceForwardingInfo.size();
3332            for (int i = 0; i < NI; i++) {
3333                int targetUserId = sourceForwardingInfo.keyAt(i);
3334                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3335                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3336                        intent, resolvedType, flags, targetUserId);
3337                int NJ = resolveInfos.size();
3338                for (int j = 0; j < NJ; j++) {
3339                    ResolveInfo resolveInfo = resolveInfos.get(j);
3340                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3341                        matchingResolveInfos.add(createForwardingResolveInfo(
3342                                resolveInfo.filter, userId, targetUserId));
3343                    }
3344                }
3345            }
3346        }
3347        return matchingResolveInfos;
3348    }
3349
3350    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3351            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3352            String packageName) {
3353        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3354        SparseArray<ArrayList<String>> sourceForwardingInfo =
3355                mSettings.mCrossProfilePackageInfo.get(userId);
3356        if (sourceForwardingInfo != null) {
3357            int NI = sourceForwardingInfo.size();
3358            for (int i = 0; i < NI; i++) {
3359                int targetUserId = sourceForwardingInfo.keyAt(i);
3360                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3361                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3362                            intent, resolvedType, flags, pkg.activities, targetUserId);
3363                    int NJ = resolveInfos.size();
3364                    for (int j = 0; j < NJ; j++) {
3365                        ResolveInfo resolveInfo = resolveInfos.get(j);
3366                        matchingResolveInfos.add(createForwardingResolveInfo(
3367                                resolveInfo.filter, userId, targetUserId));
3368                    }
3369                }
3370            }
3371        }
3372        return matchingResolveInfos;
3373    }
3374
3375    // Return matching ResolveInfo if any for skip current profile intent filters.
3376    private ResolveInfo queryCrossProfileIntents(
3377            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3378            int flags, int sourceUserId) {
3379        if (matchingFilters != null) {
3380            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3381            // match the same intent. For performance reasons, it is better not to
3382            // run queryIntent twice for the same userId
3383            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3384            int size = matchingFilters.size();
3385            for (int i = 0; i < size; i++) {
3386                CrossProfileIntentFilter filter = matchingFilters.get(i);
3387                int targetUserId = filter.getTargetUserId();
3388                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3389                        && !alreadyTriedUserIds.get(targetUserId)) {
3390                    // Checking if there are activities in the target user that can handle the
3391                    // intent.
3392                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3393                            flags, sourceUserId);
3394                    if (resolveInfo != null) return resolveInfo;
3395                    alreadyTriedUserIds.put(targetUserId, true);
3396                }
3397            }
3398        }
3399        return null;
3400    }
3401
3402    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3403            String resolvedType, int flags, int sourceUserId) {
3404        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3405                resolvedType, flags, filter.getTargetUserId());
3406        if (resultTargetUser != null) {
3407            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3408        }
3409        return null;
3410    }
3411
3412    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3413            int sourceUserId, int targetUserId) {
3414        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3415        String className;
3416        if (targetUserId == UserHandle.USER_OWNER) {
3417            className = FORWARD_INTENT_TO_USER_OWNER;
3418        } else {
3419            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3420        }
3421        ComponentName forwardingActivityComponentName = new ComponentName(
3422                mAndroidApplication.packageName, className);
3423        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3424                sourceUserId);
3425        if (targetUserId == UserHandle.USER_OWNER) {
3426            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3427            forwardingResolveInfo.noResourceId = true;
3428        }
3429        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3430        forwardingResolveInfo.priority = 0;
3431        forwardingResolveInfo.preferredOrder = 0;
3432        forwardingResolveInfo.match = 0;
3433        forwardingResolveInfo.isDefault = true;
3434        forwardingResolveInfo.filter = filter;
3435        forwardingResolveInfo.targetUserId = targetUserId;
3436        return forwardingResolveInfo;
3437    }
3438
3439    @Override
3440    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3441            Intent[] specifics, String[] specificTypes, Intent intent,
3442            String resolvedType, int flags, int userId) {
3443        if (!sUserManager.exists(userId)) return Collections.emptyList();
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3445                "query intent activity options");
3446        final String resultsAction = intent.getAction();
3447
3448        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3449                | PackageManager.GET_RESOLVED_FILTER, userId);
3450
3451        if (DEBUG_INTENT_MATCHING) {
3452            Log.v(TAG, "Query " + intent + ": " + results);
3453        }
3454
3455        int specificsPos = 0;
3456        int N;
3457
3458        // todo: note that the algorithm used here is O(N^2).  This
3459        // isn't a problem in our current environment, but if we start running
3460        // into situations where we have more than 5 or 10 matches then this
3461        // should probably be changed to something smarter...
3462
3463        // First we go through and resolve each of the specific items
3464        // that were supplied, taking care of removing any corresponding
3465        // duplicate items in the generic resolve list.
3466        if (specifics != null) {
3467            for (int i=0; i<specifics.length; i++) {
3468                final Intent sintent = specifics[i];
3469                if (sintent == null) {
3470                    continue;
3471                }
3472
3473                if (DEBUG_INTENT_MATCHING) {
3474                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3475                }
3476
3477                String action = sintent.getAction();
3478                if (resultsAction != null && resultsAction.equals(action)) {
3479                    // If this action was explicitly requested, then don't
3480                    // remove things that have it.
3481                    action = null;
3482                }
3483
3484                ResolveInfo ri = null;
3485                ActivityInfo ai = null;
3486
3487                ComponentName comp = sintent.getComponent();
3488                if (comp == null) {
3489                    ri = resolveIntent(
3490                        sintent,
3491                        specificTypes != null ? specificTypes[i] : null,
3492                            flags, userId);
3493                    if (ri == null) {
3494                        continue;
3495                    }
3496                    if (ri == mResolveInfo) {
3497                        // ACK!  Must do something better with this.
3498                    }
3499                    ai = ri.activityInfo;
3500                    comp = new ComponentName(ai.applicationInfo.packageName,
3501                            ai.name);
3502                } else {
3503                    ai = getActivityInfo(comp, flags, userId);
3504                    if (ai == null) {
3505                        continue;
3506                    }
3507                }
3508
3509                // Look for any generic query activities that are duplicates
3510                // of this specific one, and remove them from the results.
3511                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3512                N = results.size();
3513                int j;
3514                for (j=specificsPos; j<N; j++) {
3515                    ResolveInfo sri = results.get(j);
3516                    if ((sri.activityInfo.name.equals(comp.getClassName())
3517                            && sri.activityInfo.applicationInfo.packageName.equals(
3518                                    comp.getPackageName()))
3519                        || (action != null && sri.filter.matchAction(action))) {
3520                        results.remove(j);
3521                        if (DEBUG_INTENT_MATCHING) Log.v(
3522                            TAG, "Removing duplicate item from " + j
3523                            + " due to specific " + specificsPos);
3524                        if (ri == null) {
3525                            ri = sri;
3526                        }
3527                        j--;
3528                        N--;
3529                    }
3530                }
3531
3532                // Add this specific item to its proper place.
3533                if (ri == null) {
3534                    ri = new ResolveInfo();
3535                    ri.activityInfo = ai;
3536                }
3537                results.add(specificsPos, ri);
3538                ri.specificIndex = i;
3539                specificsPos++;
3540            }
3541        }
3542
3543        // Now we go through the remaining generic results and remove any
3544        // duplicate actions that are found here.
3545        N = results.size();
3546        for (int i=specificsPos; i<N-1; i++) {
3547            final ResolveInfo rii = results.get(i);
3548            if (rii.filter == null) {
3549                continue;
3550            }
3551
3552            // Iterate over all of the actions of this result's intent
3553            // filter...  typically this should be just one.
3554            final Iterator<String> it = rii.filter.actionsIterator();
3555            if (it == null) {
3556                continue;
3557            }
3558            while (it.hasNext()) {
3559                final String action = it.next();
3560                if (resultsAction != null && resultsAction.equals(action)) {
3561                    // If this action was explicitly requested, then don't
3562                    // remove things that have it.
3563                    continue;
3564                }
3565                for (int j=i+1; j<N; j++) {
3566                    final ResolveInfo rij = results.get(j);
3567                    if (rij.filter != null && rij.filter.hasAction(action)) {
3568                        results.remove(j);
3569                        if (DEBUG_INTENT_MATCHING) Log.v(
3570                            TAG, "Removing duplicate item from " + j
3571                            + " due to action " + action + " at " + i);
3572                        j--;
3573                        N--;
3574                    }
3575                }
3576            }
3577
3578            // If the caller didn't request filter information, drop it now
3579            // so we don't have to marshall/unmarshall it.
3580            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3581                rii.filter = null;
3582            }
3583        }
3584
3585        // Filter out the caller activity if so requested.
3586        if (caller != null) {
3587            N = results.size();
3588            for (int i=0; i<N; i++) {
3589                ActivityInfo ainfo = results.get(i).activityInfo;
3590                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3591                        && caller.getClassName().equals(ainfo.name)) {
3592                    results.remove(i);
3593                    break;
3594                }
3595            }
3596        }
3597
3598        // If the caller didn't request filter information,
3599        // drop them now so we don't have to
3600        // marshall/unmarshall it.
3601        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3602            N = results.size();
3603            for (int i=0; i<N; i++) {
3604                results.get(i).filter = null;
3605            }
3606        }
3607
3608        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3609        return results;
3610    }
3611
3612    @Override
3613    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3614            int userId) {
3615        if (!sUserManager.exists(userId)) return Collections.emptyList();
3616        ComponentName comp = intent.getComponent();
3617        if (comp == null) {
3618            if (intent.getSelector() != null) {
3619                intent = intent.getSelector();
3620                comp = intent.getComponent();
3621            }
3622        }
3623        if (comp != null) {
3624            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3625            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3626            if (ai != null) {
3627                ResolveInfo ri = new ResolveInfo();
3628                ri.activityInfo = ai;
3629                list.add(ri);
3630            }
3631            return list;
3632        }
3633
3634        // reader
3635        synchronized (mPackages) {
3636            String pkgName = intent.getPackage();
3637            if (pkgName == null) {
3638                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3639            }
3640            final PackageParser.Package pkg = mPackages.get(pkgName);
3641            if (pkg != null) {
3642                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3643                        userId);
3644            }
3645            return null;
3646        }
3647    }
3648
3649    @Override
3650    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3651        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3652        if (!sUserManager.exists(userId)) return null;
3653        if (query != null) {
3654            if (query.size() >= 1) {
3655                // If there is more than one service with the same priority,
3656                // just arbitrarily pick the first one.
3657                return query.get(0);
3658            }
3659        }
3660        return null;
3661    }
3662
3663    @Override
3664    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3665            int userId) {
3666        if (!sUserManager.exists(userId)) return Collections.emptyList();
3667        ComponentName comp = intent.getComponent();
3668        if (comp == null) {
3669            if (intent.getSelector() != null) {
3670                intent = intent.getSelector();
3671                comp = intent.getComponent();
3672            }
3673        }
3674        if (comp != null) {
3675            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3676            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3677            if (si != null) {
3678                final ResolveInfo ri = new ResolveInfo();
3679                ri.serviceInfo = si;
3680                list.add(ri);
3681            }
3682            return list;
3683        }
3684
3685        // reader
3686        synchronized (mPackages) {
3687            String pkgName = intent.getPackage();
3688            if (pkgName == null) {
3689                return mServices.queryIntent(intent, resolvedType, flags, userId);
3690            }
3691            final PackageParser.Package pkg = mPackages.get(pkgName);
3692            if (pkg != null) {
3693                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3694                        userId);
3695            }
3696            return null;
3697        }
3698    }
3699
3700    @Override
3701    public List<ResolveInfo> queryIntentContentProviders(
3702            Intent intent, String resolvedType, int flags, int userId) {
3703        if (!sUserManager.exists(userId)) return Collections.emptyList();
3704        ComponentName comp = intent.getComponent();
3705        if (comp == null) {
3706            if (intent.getSelector() != null) {
3707                intent = intent.getSelector();
3708                comp = intent.getComponent();
3709            }
3710        }
3711        if (comp != null) {
3712            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3713            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3714            if (pi != null) {
3715                final ResolveInfo ri = new ResolveInfo();
3716                ri.providerInfo = pi;
3717                list.add(ri);
3718            }
3719            return list;
3720        }
3721
3722        // reader
3723        synchronized (mPackages) {
3724            String pkgName = intent.getPackage();
3725            if (pkgName == null) {
3726                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3727            }
3728            final PackageParser.Package pkg = mPackages.get(pkgName);
3729            if (pkg != null) {
3730                return mProviders.queryIntentForPackage(
3731                        intent, resolvedType, flags, pkg.providers, userId);
3732            }
3733            return null;
3734        }
3735    }
3736
3737    @Override
3738    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3739        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3740
3741        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3742
3743        // writer
3744        synchronized (mPackages) {
3745            ArrayList<PackageInfo> list;
3746            if (listUninstalled) {
3747                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3748                for (PackageSetting ps : mSettings.mPackages.values()) {
3749                    PackageInfo pi;
3750                    if (ps.pkg != null) {
3751                        pi = generatePackageInfo(ps.pkg, flags, userId);
3752                    } else {
3753                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3754                    }
3755                    if (pi != null) {
3756                        list.add(pi);
3757                    }
3758                }
3759            } else {
3760                list = new ArrayList<PackageInfo>(mPackages.size());
3761                for (PackageParser.Package p : mPackages.values()) {
3762                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3763                    if (pi != null) {
3764                        list.add(pi);
3765                    }
3766                }
3767            }
3768
3769            return new ParceledListSlice<PackageInfo>(list);
3770        }
3771    }
3772
3773    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3774            String[] permissions, boolean[] tmp, int flags, int userId) {
3775        int numMatch = 0;
3776        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3777        for (int i=0; i<permissions.length; i++) {
3778            if (gp.grantedPermissions.contains(permissions[i])) {
3779                tmp[i] = true;
3780                numMatch++;
3781            } else {
3782                tmp[i] = false;
3783            }
3784        }
3785        if (numMatch == 0) {
3786            return;
3787        }
3788        PackageInfo pi;
3789        if (ps.pkg != null) {
3790            pi = generatePackageInfo(ps.pkg, flags, userId);
3791        } else {
3792            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3793        }
3794        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3795            if (numMatch == permissions.length) {
3796                pi.requestedPermissions = permissions;
3797            } else {
3798                pi.requestedPermissions = new String[numMatch];
3799                numMatch = 0;
3800                for (int i=0; i<permissions.length; i++) {
3801                    if (tmp[i]) {
3802                        pi.requestedPermissions[numMatch] = permissions[i];
3803                        numMatch++;
3804                    }
3805                }
3806            }
3807        }
3808        list.add(pi);
3809    }
3810
3811    @Override
3812    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3813            String[] permissions, int flags, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3816
3817        // writer
3818        synchronized (mPackages) {
3819            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3820            boolean[] tmpBools = new boolean[permissions.length];
3821            if (listUninstalled) {
3822                for (PackageSetting ps : mSettings.mPackages.values()) {
3823                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3824                }
3825            } else {
3826                for (PackageParser.Package pkg : mPackages.values()) {
3827                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3828                    if (ps != null) {
3829                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3830                                userId);
3831                    }
3832                }
3833            }
3834
3835            return new ParceledListSlice<PackageInfo>(list);
3836        }
3837    }
3838
3839    @Override
3840    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3841        if (!sUserManager.exists(userId)) return null;
3842        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3843
3844        // writer
3845        synchronized (mPackages) {
3846            ArrayList<ApplicationInfo> list;
3847            if (listUninstalled) {
3848                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3849                for (PackageSetting ps : mSettings.mPackages.values()) {
3850                    ApplicationInfo ai;
3851                    if (ps.pkg != null) {
3852                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3853                                ps.readUserState(userId), userId);
3854                    } else {
3855                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3856                    }
3857                    if (ai != null) {
3858                        list.add(ai);
3859                    }
3860                }
3861            } else {
3862                list = new ArrayList<ApplicationInfo>(mPackages.size());
3863                for (PackageParser.Package p : mPackages.values()) {
3864                    if (p.mExtras != null) {
3865                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3866                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3867                        if (ai != null) {
3868                            list.add(ai);
3869                        }
3870                    }
3871                }
3872            }
3873
3874            return new ParceledListSlice<ApplicationInfo>(list);
3875        }
3876    }
3877
3878    public List<ApplicationInfo> getPersistentApplications(int flags) {
3879        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3880
3881        // reader
3882        synchronized (mPackages) {
3883            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3884            final int userId = UserHandle.getCallingUserId();
3885            while (i.hasNext()) {
3886                final PackageParser.Package p = i.next();
3887                if (p.applicationInfo != null
3888                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3889                        && (!mSafeMode || isSystemApp(p))) {
3890                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3891                    if (ps != null) {
3892                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3893                                ps.readUserState(userId), userId);
3894                        if (ai != null) {
3895                            finalList.add(ai);
3896                        }
3897                    }
3898                }
3899            }
3900        }
3901
3902        return finalList;
3903    }
3904
3905    @Override
3906    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3907        if (!sUserManager.exists(userId)) return null;
3908        // reader
3909        synchronized (mPackages) {
3910            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3911            PackageSetting ps = provider != null
3912                    ? mSettings.mPackages.get(provider.owner.packageName)
3913                    : null;
3914            return ps != null
3915                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3916                    && (!mSafeMode || (provider.info.applicationInfo.flags
3917                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3918                    ? PackageParser.generateProviderInfo(provider, flags,
3919                            ps.readUserState(userId), userId)
3920                    : null;
3921        }
3922    }
3923
3924    /**
3925     * @deprecated
3926     */
3927    @Deprecated
3928    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3929        // reader
3930        synchronized (mPackages) {
3931            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3932                    .entrySet().iterator();
3933            final int userId = UserHandle.getCallingUserId();
3934            while (i.hasNext()) {
3935                Map.Entry<String, PackageParser.Provider> entry = i.next();
3936                PackageParser.Provider p = entry.getValue();
3937                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3938
3939                if (ps != null && p.syncable
3940                        && (!mSafeMode || (p.info.applicationInfo.flags
3941                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3942                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3943                            ps.readUserState(userId), userId);
3944                    if (info != null) {
3945                        outNames.add(entry.getKey());
3946                        outInfo.add(info);
3947                    }
3948                }
3949            }
3950        }
3951    }
3952
3953    @Override
3954    public List<ProviderInfo> queryContentProviders(String processName,
3955            int uid, int flags) {
3956        ArrayList<ProviderInfo> finalList = null;
3957        // reader
3958        synchronized (mPackages) {
3959            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3960            final int userId = processName != null ?
3961                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3962            while (i.hasNext()) {
3963                final PackageParser.Provider p = i.next();
3964                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3965                if (ps != null && p.info.authority != null
3966                        && (processName == null
3967                                || (p.info.processName.equals(processName)
3968                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3969                        && mSettings.isEnabledLPr(p.info, flags, userId)
3970                        && (!mSafeMode
3971                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3972                    if (finalList == null) {
3973                        finalList = new ArrayList<ProviderInfo>(3);
3974                    }
3975                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3976                            ps.readUserState(userId), userId);
3977                    if (info != null) {
3978                        finalList.add(info);
3979                    }
3980                }
3981            }
3982        }
3983
3984        if (finalList != null) {
3985            Collections.sort(finalList, mProviderInitOrderSorter);
3986        }
3987
3988        return finalList;
3989    }
3990
3991    @Override
3992    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3993            int flags) {
3994        // reader
3995        synchronized (mPackages) {
3996            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3997            return PackageParser.generateInstrumentationInfo(i, flags);
3998        }
3999    }
4000
4001    @Override
4002    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4003            int flags) {
4004        ArrayList<InstrumentationInfo> finalList =
4005            new ArrayList<InstrumentationInfo>();
4006
4007        // reader
4008        synchronized (mPackages) {
4009            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4010            while (i.hasNext()) {
4011                final PackageParser.Instrumentation p = i.next();
4012                if (targetPackage == null
4013                        || targetPackage.equals(p.info.targetPackage)) {
4014                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4015                            flags);
4016                    if (ii != null) {
4017                        finalList.add(ii);
4018                    }
4019                }
4020            }
4021        }
4022
4023        return finalList;
4024    }
4025
4026    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4027        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4028        if (overlays == null) {
4029            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4030            return;
4031        }
4032        for (PackageParser.Package opkg : overlays.values()) {
4033            // Not much to do if idmap fails: we already logged the error
4034            // and we certainly don't want to abort installation of pkg simply
4035            // because an overlay didn't fit properly. For these reasons,
4036            // ignore the return value of createIdmapForPackagePairLI.
4037            createIdmapForPackagePairLI(pkg, opkg);
4038        }
4039    }
4040
4041    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4042            PackageParser.Package opkg) {
4043        if (!opkg.mTrustedOverlay) {
4044            Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " +
4045                    opkg.codePath + ": overlay not trusted");
4046            return false;
4047        }
4048        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4049        if (overlaySet == null) {
4050            Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " +
4051                    opkg.codePath + " but target package has no known overlays");
4052            return false;
4053        }
4054        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4055        // TODO: generate idmap for split APKs
4056        if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) {
4057            Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath);
4058            return false;
4059        }
4060        PackageParser.Package[] overlayArray =
4061            overlaySet.values().toArray(new PackageParser.Package[0]);
4062        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4063            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4064                return p1.mOverlayPriority - p2.mOverlayPriority;
4065            }
4066        };
4067        Arrays.sort(overlayArray, cmp);
4068
4069        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4070        int i = 0;
4071        for (PackageParser.Package p : overlayArray) {
4072            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4073        }
4074        return true;
4075    }
4076
4077    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4078        String[] files = dir.list();
4079        if (files == null) {
4080            Log.d(TAG, "No files in app dir " + dir);
4081            return;
4082        }
4083
4084        if (DEBUG_PACKAGE_SCANNING) {
4085            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4086                    + " flags=0x" + Integer.toHexString(flags));
4087        }
4088
4089        int i;
4090        for (i=0; i<files.length; i++) {
4091            File file = new File(dir, files[i]);
4092            if (!isPackageFilename(files[i])) {
4093                // Ignore entries which are not apk's
4094                continue;
4095            }
4096            PackageParser.Package pkg = scanPackageLI(file,
4097                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4098            // Don't mess around with apps in system partition.
4099            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4100                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4101                // Delete the apk
4102                Slog.w(TAG, "Cleaning up failed install of " + file);
4103                file.delete();
4104            }
4105        }
4106    }
4107
4108    private static File getSettingsProblemFile() {
4109        File dataDir = Environment.getDataDirectory();
4110        File systemDir = new File(dataDir, "system");
4111        File fname = new File(systemDir, "uiderrors.txt");
4112        return fname;
4113    }
4114
4115    static void reportSettingsProblem(int priority, String msg) {
4116        try {
4117            File fname = getSettingsProblemFile();
4118            FileOutputStream out = new FileOutputStream(fname, true);
4119            PrintWriter pw = new FastPrintWriter(out);
4120            SimpleDateFormat formatter = new SimpleDateFormat();
4121            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4122            pw.println(dateString + ": " + msg);
4123            pw.close();
4124            FileUtils.setPermissions(
4125                    fname.toString(),
4126                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4127                    -1, -1);
4128        } catch (java.io.IOException e) {
4129        }
4130        Slog.println(priority, TAG, msg);
4131    }
4132
4133    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4134            PackageParser.Package pkg, File srcFile, int parseFlags) {
4135        if (ps != null
4136                && ps.codePath.equals(srcFile)
4137                && ps.timeStamp == srcFile.lastModified()
4138                && !isCompatSignatureUpdateNeeded(pkg)) {
4139            if (ps.signatures.mSignatures != null
4140                    && ps.signatures.mSignatures.length != 0) {
4141                // Optimization: reuse the existing cached certificates
4142                // if the package appears to be unchanged.
4143                pkg.mSignatures = ps.signatures.mSignatures;
4144                return true;
4145            }
4146
4147            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4148        } else {
4149            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4150        }
4151
4152        try {
4153            pp.collectCertificates(pkg, parseFlags);
4154            pp.collectManifestDigest(pkg);
4155        } catch (PackageParserException e) {
4156            mLastScanError = e.error;
4157            return false;
4158        }
4159        return true;
4160    }
4161
4162    /*
4163     *  Scan a package and return the newly parsed package.
4164     *  Returns null in case of errors and the error code is stored in mLastScanError
4165     */
4166    private PackageParser.Package scanPackageLI(File scanFile,
4167            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4168        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4169        String scanPath = scanFile.getPath();
4170        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4171        parseFlags |= mDefParseFlags;
4172        PackageParser pp = new PackageParser();
4173        pp.setSeparateProcesses(mSeparateProcesses);
4174        pp.setOnlyCoreApps(mOnlyCore);
4175        pp.setDisplayMetrics(mMetrics);
4176
4177        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4178            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4179        }
4180
4181        final PackageParser.Package pkg;
4182        try {
4183            pkg = pp.parseMonolithicPackage(scanFile, parseFlags);
4184        } catch (PackageParserException e) {
4185            mLastScanError = e.error;
4186            return null;
4187        }
4188
4189        PackageSetting ps = null;
4190        PackageSetting updatedPkg;
4191        // reader
4192        synchronized (mPackages) {
4193            // Look to see if we already know about this package.
4194            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4195            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4196                // This package has been renamed to its original name.  Let's
4197                // use that.
4198                ps = mSettings.peekPackageLPr(oldName);
4199            }
4200            // If there was no original package, see one for the real package name.
4201            if (ps == null) {
4202                ps = mSettings.peekPackageLPr(pkg.packageName);
4203            }
4204            // Check to see if this package could be hiding/updating a system
4205            // package.  Must look for it either under the original or real
4206            // package name depending on our state.
4207            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4208            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4209        }
4210        boolean updatedPkgBetter = false;
4211        // First check if this is a system package that may involve an update
4212        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4213            if (ps != null && !ps.codePath.equals(scanFile)) {
4214                // The path has changed from what was last scanned...  check the
4215                // version of the new path against what we have stored to determine
4216                // what to do.
4217                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4218                if (pkg.mVersionCode < ps.versionCode) {
4219                    // The system package has been updated and the code path does not match
4220                    // Ignore entry. Skip it.
4221                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4222                            + " ignored: updated version " + ps.versionCode
4223                            + " better than this " + pkg.mVersionCode);
4224                    if (!updatedPkg.codePath.equals(scanFile)) {
4225                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4226                                + ps.name + " changing from " + updatedPkg.codePathString
4227                                + " to " + scanFile);
4228                        updatedPkg.codePath = scanFile;
4229                        updatedPkg.codePathString = scanFile.toString();
4230                        // This is the point at which we know that the system-disk APK
4231                        // for this package has moved during a reboot (e.g. due to an OTA),
4232                        // so we need to reevaluate it for privilege policy.
4233                        if (locationIsPrivileged(scanFile)) {
4234                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4235                        }
4236                    }
4237                    updatedPkg.pkg = pkg;
4238                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4239                    return null;
4240                } else {
4241                    // The current app on the system partition is better than
4242                    // what we have updated to on the data partition; switch
4243                    // back to the system partition version.
4244                    // At this point, its safely assumed that package installation for
4245                    // apps in system partition will go through. If not there won't be a working
4246                    // version of the app
4247                    // writer
4248                    synchronized (mPackages) {
4249                        // Just remove the loaded entries from package lists.
4250                        mPackages.remove(ps.name);
4251                    }
4252                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4253                            + "reverting from " + ps.codePathString
4254                            + ": new version " + pkg.mVersionCode
4255                            + " better than installed " + ps.versionCode);
4256
4257                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4258                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4259                            getAppInstructionSetFromSettings(ps));
4260                    synchronized (mInstallLock) {
4261                        args.cleanUpResourcesLI();
4262                    }
4263                    synchronized (mPackages) {
4264                        mSettings.enableSystemPackageLPw(ps.name);
4265                    }
4266                    updatedPkgBetter = true;
4267                }
4268            }
4269        }
4270
4271        if (updatedPkg != null) {
4272            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4273            // initially
4274            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4275
4276            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4277            // flag set initially
4278            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4279                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4280            }
4281        }
4282        // Verify certificates against what was last scanned
4283        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4284            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4285            return null;
4286        }
4287
4288        /*
4289         * A new system app appeared, but we already had a non-system one of the
4290         * same name installed earlier.
4291         */
4292        boolean shouldHideSystemApp = false;
4293        if (updatedPkg == null && ps != null
4294                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4295            /*
4296             * Check to make sure the signatures match first. If they don't,
4297             * wipe the installed application and its data.
4298             */
4299            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4300                    != PackageManager.SIGNATURE_MATCH) {
4301                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4302                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4303                ps = null;
4304            } else {
4305                /*
4306                 * If the newly-added system app is an older version than the
4307                 * already installed version, hide it. It will be scanned later
4308                 * and re-added like an update.
4309                 */
4310                if (pkg.mVersionCode < ps.versionCode) {
4311                    shouldHideSystemApp = true;
4312                } else {
4313                    /*
4314                     * The newly found system app is a newer version that the
4315                     * one previously installed. Simply remove the
4316                     * already-installed application and replace it with our own
4317                     * while keeping the application data.
4318                     */
4319                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4320                            + ps.codePathString + ": new version " + pkg.mVersionCode
4321                            + " better than installed " + ps.versionCode);
4322                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4323                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4324                            getAppInstructionSetFromSettings(ps));
4325                    synchronized (mInstallLock) {
4326                        args.cleanUpResourcesLI();
4327                    }
4328                }
4329            }
4330        }
4331
4332        // The apk is forward locked (not public) if its code and resources
4333        // are kept in different files. (except for app in either system or
4334        // vendor path).
4335        // TODO grab this value from PackageSettings
4336        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4337            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4338                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4339            }
4340        }
4341
4342        final String codePath = pkg.codePath;
4343        final String[] splitCodePaths = pkg.splitCodePaths;
4344
4345        String resPath = null;
4346        String[] splitResPaths = null;
4347        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4348            if (ps != null && ps.resourcePathString != null) {
4349                resPath = ps.resourcePathString;
4350                splitResPaths = deriveSplitResPaths(pkg.splitCodePaths);
4351            } else {
4352                // Should not happen at all. Just log an error.
4353                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4354            }
4355        } else {
4356            resPath = pkg.codePath;
4357            splitResPaths = pkg.splitCodePaths;
4358        }
4359
4360        // Set application objects path explicitly.
4361        pkg.applicationInfo.sourceDir = codePath;
4362        pkg.applicationInfo.publicSourceDir = resPath;
4363        pkg.applicationInfo.splitSourceDirs = splitCodePaths;
4364        pkg.applicationInfo.splitPublicSourceDirs = splitResPaths;
4365
4366        // Note that we invoke the following method only if we are about to unpack an application
4367        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4368                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4369
4370        /*
4371         * If the system app should be overridden by a previously installed
4372         * data, hide the system app now and let the /data/app scan pick it up
4373         * again.
4374         */
4375        if (shouldHideSystemApp) {
4376            synchronized (mPackages) {
4377                /*
4378                 * We have to grant systems permissions before we hide, because
4379                 * grantPermissions will assume the package update is trying to
4380                 * expand its permissions.
4381                 */
4382                grantPermissionsLPw(pkg, true);
4383                mSettings.disableSystemPackageLPw(pkg.packageName);
4384            }
4385        }
4386
4387        return scannedPkg;
4388    }
4389
4390    private static String fixProcessName(String defProcessName,
4391            String processName, int uid) {
4392        if (processName == null) {
4393            return defProcessName;
4394        }
4395        return processName;
4396    }
4397
4398    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4399        if (pkgSetting.signatures.mSignatures != null) {
4400            // Already existing package. Make sure signatures match
4401            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4402                    == PackageManager.SIGNATURE_MATCH;
4403            if (!match) {
4404                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4405                        == PackageManager.SIGNATURE_MATCH;
4406            }
4407            if (!match) {
4408                Slog.e(TAG, "Package " + pkg.packageName
4409                        + " signatures do not match the previously installed version; ignoring!");
4410                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4411                return false;
4412            }
4413        }
4414        // Check for shared user signatures
4415        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4416            // Already existing package. Make sure signatures match
4417            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4418                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4419            if (!match) {
4420                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4421                        == PackageManager.SIGNATURE_MATCH;
4422            }
4423            if (!match) {
4424                Slog.e(TAG, "Package " + pkg.packageName
4425                        + " has no signatures that match those in shared user "
4426                        + pkgSetting.sharedUser.name + "; ignoring!");
4427                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4428                return false;
4429            }
4430        }
4431        return true;
4432    }
4433
4434    /**
4435     * Enforces that only the system UID or root's UID can call a method exposed
4436     * via Binder.
4437     *
4438     * @param message used as message if SecurityException is thrown
4439     * @throws SecurityException if the caller is not system or root
4440     */
4441    private static final void enforceSystemOrRoot(String message) {
4442        final int uid = Binder.getCallingUid();
4443        if (uid != Process.SYSTEM_UID && uid != 0) {
4444            throw new SecurityException(message);
4445        }
4446    }
4447
4448    @Override
4449    public void performBootDexOpt() {
4450        enforceSystemOrRoot("Only the system can request dexopt be performed");
4451
4452        final HashSet<PackageParser.Package> pkgs;
4453        synchronized (mPackages) {
4454            pkgs = mDeferredDexOpt;
4455            mDeferredDexOpt = null;
4456        }
4457
4458        if (pkgs != null) {
4459            // Filter out packages that aren't recently used.
4460            //
4461            // The exception is first boot of a non-eng device, which
4462            // should do a full dexopt.
4463            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4464            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4465                // TODO: add a property to control this?
4466                long dexOptLRUThresholdInMinutes;
4467                if (eng) {
4468                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4469                } else {
4470                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4471                }
4472                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4473
4474                int total = pkgs.size();
4475                int skipped = 0;
4476                long now = System.currentTimeMillis();
4477                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4478                    PackageParser.Package pkg = i.next();
4479                    long then = pkg.mLastPackageUsageTimeInMills;
4480                    if (then + dexOptLRUThresholdInMills < now) {
4481                        if (DEBUG_DEXOPT) {
4482                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4483                                  ((then == 0) ? "never" : new Date(then)));
4484                        }
4485                        i.remove();
4486                        skipped++;
4487                    }
4488                }
4489                if (DEBUG_DEXOPT) {
4490                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4491                }
4492            }
4493
4494            int i = 0;
4495            for (PackageParser.Package pkg : pkgs) {
4496                i++;
4497                if (DEBUG_DEXOPT) {
4498                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4499                          + ": " + pkg.packageName);
4500                }
4501                if (!isFirstBoot()) {
4502                    try {
4503                        ActivityManagerNative.getDefault().showBootMessage(
4504                                mContext.getResources().getString(
4505                                        R.string.android_upgrading_apk,
4506                                        i, pkgs.size()), true);
4507                    } catch (RemoteException e) {
4508                    }
4509                }
4510                PackageParser.Package p = pkg;
4511                synchronized (mInstallLock) {
4512                    if (p.mDexOptNeeded) {
4513                        performDexOptLI(p, false /* force dex */, false /* defer */,
4514                                true /* include dependencies */);
4515                    }
4516                }
4517            }
4518        }
4519    }
4520
4521    @Override
4522    public boolean performDexOpt(String packageName) {
4523        enforceSystemOrRoot("Only the system can request dexopt be performed");
4524        return performDexOpt(packageName, true);
4525    }
4526
4527    public boolean performDexOpt(String packageName, boolean updateUsage) {
4528
4529        PackageParser.Package p;
4530        synchronized (mPackages) {
4531            p = mPackages.get(packageName);
4532            if (p == null) {
4533                return false;
4534            }
4535            if (updateUsage) {
4536                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4537            }
4538            mPackageUsage.write(false);
4539            if (!p.mDexOptNeeded) {
4540                return false;
4541            }
4542        }
4543
4544        synchronized (mInstallLock) {
4545            return performDexOptLI(p, false /* force dex */, false /* defer */,
4546                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4547        }
4548    }
4549
4550    public HashSet<String> getPackagesThatNeedDexOpt() {
4551        HashSet<String> pkgs = null;
4552        synchronized (mPackages) {
4553            for (PackageParser.Package p : mPackages.values()) {
4554                if (DEBUG_DEXOPT) {
4555                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4556                }
4557                if (!p.mDexOptNeeded) {
4558                    continue;
4559                }
4560                if (pkgs == null) {
4561                    pkgs = new HashSet<String>();
4562                }
4563                pkgs.add(p.packageName);
4564            }
4565        }
4566        return pkgs;
4567    }
4568
4569    public void shutdown() {
4570        mPackageUsage.write(true);
4571    }
4572
4573    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4574             boolean forceDex, boolean defer, HashSet<String> done) {
4575        for (int i=0; i<libs.size(); i++) {
4576            PackageParser.Package libPkg;
4577            String libName;
4578            synchronized (mPackages) {
4579                libName = libs.get(i);
4580                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4581                if (lib != null && lib.apk != null) {
4582                    libPkg = mPackages.get(lib.apk);
4583                } else {
4584                    libPkg = null;
4585                }
4586            }
4587            if (libPkg != null && !done.contains(libName)) {
4588                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4589            }
4590        }
4591    }
4592
4593    static final int DEX_OPT_SKIPPED = 0;
4594    static final int DEX_OPT_PERFORMED = 1;
4595    static final int DEX_OPT_DEFERRED = 2;
4596    static final int DEX_OPT_FAILED = -1;
4597
4598    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4599            boolean forceDex, boolean defer, HashSet<String> done) {
4600        final String instructionSet = instructionSetOverride != null ?
4601                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4602
4603        if (done != null) {
4604            done.add(pkg.packageName);
4605            if (pkg.usesLibraries != null) {
4606                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4607            }
4608            if (pkg.usesOptionalLibraries != null) {
4609                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4610            }
4611        }
4612
4613        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4614            final Collection<String> paths = pkg.getAllCodePaths();
4615            for (String path : paths) {
4616                try {
4617                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4618                            pkg.packageName, instructionSet, defer);
4619                    // There are three basic cases here:
4620                    // 1.) we need to dexopt, either because we are forced or it is needed
4621                    // 2.) we are defering a needed dexopt
4622                    // 3.) we are skipping an unneeded dexopt
4623                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4624                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4625                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4626                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4627                                                    pkg.packageName, instructionSet);
4628                        // Note that we ran dexopt, since rerunning will
4629                        // probably just result in an error again.
4630                        pkg.mDexOptNeeded = false;
4631                        if (ret < 0) {
4632                            return DEX_OPT_FAILED;
4633                        }
4634                        return DEX_OPT_PERFORMED;
4635                    }
4636                    if (defer && isDexOptNeededInternal) {
4637                        if (mDeferredDexOpt == null) {
4638                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4639                        }
4640                        mDeferredDexOpt.add(pkg);
4641                        return DEX_OPT_DEFERRED;
4642                    }
4643                    pkg.mDexOptNeeded = false;
4644                    return DEX_OPT_SKIPPED;
4645                } catch (FileNotFoundException e) {
4646                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4647                    return DEX_OPT_FAILED;
4648                } catch (IOException e) {
4649                    Slog.w(TAG, "IOException reading apk: " + path, e);
4650                    return DEX_OPT_FAILED;
4651                } catch (StaleDexCacheError e) {
4652                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4653                    return DEX_OPT_FAILED;
4654                } catch (Exception e) {
4655                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4656                    return DEX_OPT_FAILED;
4657                }
4658            }
4659        }
4660        return DEX_OPT_SKIPPED;
4661    }
4662
4663    private String getAppInstructionSet(ApplicationInfo info) {
4664        String instructionSet = getPreferredInstructionSet();
4665
4666        if (info.cpuAbi != null) {
4667            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4668        }
4669
4670        return instructionSet;
4671    }
4672
4673    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4674        String instructionSet = getPreferredInstructionSet();
4675
4676        if (ps.cpuAbiString != null) {
4677            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4678        }
4679
4680        return instructionSet;
4681    }
4682
4683    private static String getPreferredInstructionSet() {
4684        if (sPreferredInstructionSet == null) {
4685            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4686        }
4687
4688        return sPreferredInstructionSet;
4689    }
4690
4691    private static List<String> getAllInstructionSets() {
4692        final String[] allAbis = Build.SUPPORTED_ABIS;
4693        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4694
4695        for (String abi : allAbis) {
4696            final String instructionSet = VMRuntime.getInstructionSet(abi);
4697            if (!allInstructionSets.contains(instructionSet)) {
4698                allInstructionSets.add(instructionSet);
4699            }
4700        }
4701
4702        return allInstructionSets;
4703    }
4704
4705    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4706            boolean inclDependencies) {
4707        HashSet<String> done;
4708        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4709            done = new HashSet<String>();
4710            done.add(pkg.packageName);
4711        } else {
4712            done = null;
4713        }
4714        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4715    }
4716
4717    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4718        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4719            Slog.w(TAG, "Unable to update from " + oldPkg.name
4720                    + " to " + newPkg.packageName
4721                    + ": old package not in system partition");
4722            return false;
4723        } else if (mPackages.get(oldPkg.name) != null) {
4724            Slog.w(TAG, "Unable to update from " + oldPkg.name
4725                    + " to " + newPkg.packageName
4726                    + ": old package still exists");
4727            return false;
4728        }
4729        return true;
4730    }
4731
4732    File getDataPathForUser(int userId) {
4733        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4734    }
4735
4736    private File getDataPathForPackage(String packageName, int userId) {
4737        /*
4738         * Until we fully support multiple users, return the directory we
4739         * previously would have. The PackageManagerTests will need to be
4740         * revised when this is changed back..
4741         */
4742        if (userId == 0) {
4743            return new File(mAppDataDir, packageName);
4744        } else {
4745            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4746                + File.separator + packageName);
4747        }
4748    }
4749
4750    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4751        int[] users = sUserManager.getUserIds();
4752        int res = mInstaller.install(packageName, uid, uid, seinfo);
4753        if (res < 0) {
4754            return res;
4755        }
4756        for (int user : users) {
4757            if (user != 0) {
4758                res = mInstaller.createUserData(packageName,
4759                        UserHandle.getUid(user, uid), user, seinfo);
4760                if (res < 0) {
4761                    return res;
4762                }
4763            }
4764        }
4765        return res;
4766    }
4767
4768    private int removeDataDirsLI(String packageName) {
4769        int[] users = sUserManager.getUserIds();
4770        int res = 0;
4771        for (int user : users) {
4772            int resInner = mInstaller.remove(packageName, user);
4773            if (resInner < 0) {
4774                res = resInner;
4775            }
4776        }
4777
4778        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4779        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4780        if (!nativeLibraryFile.delete()) {
4781            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4782        }
4783
4784        return res;
4785    }
4786
4787    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4788            PackageParser.Package changingLib) {
4789        if (file.path != null) {
4790            usesLibraryFiles.add(file.path);
4791            return;
4792        }
4793        PackageParser.Package p = mPackages.get(file.apk);
4794        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4795            // If we are doing this while in the middle of updating a library apk,
4796            // then we need to make sure to use that new apk for determining the
4797            // dependencies here.  (We haven't yet finished committing the new apk
4798            // to the package manager state.)
4799            if (p == null || p.packageName.equals(changingLib.packageName)) {
4800                p = changingLib;
4801            }
4802        }
4803        if (p != null) {
4804            usesLibraryFiles.addAll(p.getAllCodePaths());
4805        }
4806    }
4807
4808    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4809            PackageParser.Package changingLib) {
4810        // We might be upgrading from a version of the platform that did not
4811        // provide per-package native library directories for system apps.
4812        // Fix that up here.
4813        if (isSystemApp(pkg)) {
4814            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4815            setInternalAppNativeLibraryPath(pkg, ps);
4816        }
4817
4818        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4819            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4820            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4821            for (int i=0; i<N; i++) {
4822                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4823                if (file == null) {
4824                    Slog.e(TAG, "Package " + pkg.packageName
4825                            + " requires unavailable shared library "
4826                            + pkg.usesLibraries.get(i) + "; failing!");
4827                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4828                    return false;
4829                }
4830                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4831            }
4832            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4833            for (int i=0; i<N; i++) {
4834                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4835                if (file == null) {
4836                    Slog.w(TAG, "Package " + pkg.packageName
4837                            + " desires unavailable shared library "
4838                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4839                } else {
4840                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4841                }
4842            }
4843            N = usesLibraryFiles.size();
4844            if (N > 0) {
4845                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4846            } else {
4847                pkg.usesLibraryFiles = null;
4848            }
4849        }
4850        return true;
4851    }
4852
4853    private static boolean hasString(List<String> list, List<String> which) {
4854        if (list == null) {
4855            return false;
4856        }
4857        for (int i=list.size()-1; i>=0; i--) {
4858            for (int j=which.size()-1; j>=0; j--) {
4859                if (which.get(j).equals(list.get(i))) {
4860                    return true;
4861                }
4862            }
4863        }
4864        return false;
4865    }
4866
4867    private void updateAllSharedLibrariesLPw() {
4868        for (PackageParser.Package pkg : mPackages.values()) {
4869            updateSharedLibrariesLPw(pkg, null);
4870        }
4871    }
4872
4873    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4874            PackageParser.Package changingPkg) {
4875        ArrayList<PackageParser.Package> res = null;
4876        for (PackageParser.Package pkg : mPackages.values()) {
4877            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4878                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4879                if (res == null) {
4880                    res = new ArrayList<PackageParser.Package>();
4881                }
4882                res.add(pkg);
4883                updateSharedLibrariesLPw(pkg, changingPkg);
4884            }
4885        }
4886        return res;
4887    }
4888
4889    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4890            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4891        final File scanFile = new File(pkg.codePath);
4892        if (pkg.applicationInfo.sourceDir == null ||
4893                pkg.applicationInfo.publicSourceDir == null) {
4894            // Bail out. The resource and code paths haven't been set.
4895            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4896            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4897            return null;
4898        }
4899
4900        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4901            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4902        }
4903
4904        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4905            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4906        }
4907
4908        if (mCustomResolverComponentName != null &&
4909                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4910            setUpCustomResolverActivity(pkg);
4911        }
4912
4913        if (pkg.packageName.equals("android")) {
4914            synchronized (mPackages) {
4915                if (mAndroidApplication != null) {
4916                    Slog.w(TAG, "*************************************************");
4917                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4918                    Slog.w(TAG, " file=" + scanFile);
4919                    Slog.w(TAG, "*************************************************");
4920                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4921                    return null;
4922                }
4923
4924                // Set up information for our fall-back user intent resolution activity.
4925                mPlatformPackage = pkg;
4926                pkg.mVersionCode = mSdkVersion;
4927                mAndroidApplication = pkg.applicationInfo;
4928
4929                if (!mResolverReplaced) {
4930                    mResolveActivity.applicationInfo = mAndroidApplication;
4931                    mResolveActivity.name = ResolverActivity.class.getName();
4932                    mResolveActivity.packageName = mAndroidApplication.packageName;
4933                    mResolveActivity.processName = "system:ui";
4934                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4935                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4936                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4937                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4938                    mResolveActivity.exported = true;
4939                    mResolveActivity.enabled = true;
4940                    mResolveInfo.activityInfo = mResolveActivity;
4941                    mResolveInfo.priority = 0;
4942                    mResolveInfo.preferredOrder = 0;
4943                    mResolveInfo.match = 0;
4944                    mResolveComponentName = new ComponentName(
4945                            mAndroidApplication.packageName, mResolveActivity.name);
4946                }
4947            }
4948        }
4949
4950        if (DEBUG_PACKAGE_SCANNING) {
4951            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4952                Log.d(TAG, "Scanning package " + pkg.packageName);
4953        }
4954
4955        if (mPackages.containsKey(pkg.packageName)
4956                || mSharedLibraries.containsKey(pkg.packageName)) {
4957            Slog.w(TAG, "Application package " + pkg.packageName
4958                    + " already installed.  Skipping duplicate.");
4959            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4960            return null;
4961        }
4962
4963        // Initialize package source and resource directories
4964        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4965        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4966
4967        SharedUserSetting suid = null;
4968        PackageSetting pkgSetting = null;
4969
4970        if (!isSystemApp(pkg)) {
4971            // Only system apps can use these features.
4972            pkg.mOriginalPackages = null;
4973            pkg.mRealPackage = null;
4974            pkg.mAdoptPermissions = null;
4975        }
4976
4977        // writer
4978        synchronized (mPackages) {
4979            if (pkg.mSharedUserId != null) {
4980                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4981                if (suid == null) {
4982                    Slog.w(TAG, "Creating application package " + pkg.packageName
4983                            + " for shared user failed");
4984                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4985                    return null;
4986                }
4987                if (DEBUG_PACKAGE_SCANNING) {
4988                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4989                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4990                                + "): packages=" + suid.packages);
4991                }
4992            }
4993
4994            // Check if we are renaming from an original package name.
4995            PackageSetting origPackage = null;
4996            String realName = null;
4997            if (pkg.mOriginalPackages != null) {
4998                // This package may need to be renamed to a previously
4999                // installed name.  Let's check on that...
5000                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5001                if (pkg.mOriginalPackages.contains(renamed)) {
5002                    // This package had originally been installed as the
5003                    // original name, and we have already taken care of
5004                    // transitioning to the new one.  Just update the new
5005                    // one to continue using the old name.
5006                    realName = pkg.mRealPackage;
5007                    if (!pkg.packageName.equals(renamed)) {
5008                        // Callers into this function may have already taken
5009                        // care of renaming the package; only do it here if
5010                        // it is not already done.
5011                        pkg.setPackageName(renamed);
5012                    }
5013
5014                } else {
5015                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5016                        if ((origPackage = mSettings.peekPackageLPr(
5017                                pkg.mOriginalPackages.get(i))) != null) {
5018                            // We do have the package already installed under its
5019                            // original name...  should we use it?
5020                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5021                                // New package is not compatible with original.
5022                                origPackage = null;
5023                                continue;
5024                            } else if (origPackage.sharedUser != null) {
5025                                // Make sure uid is compatible between packages.
5026                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5027                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5028                                            + " to " + pkg.packageName + ": old uid "
5029                                            + origPackage.sharedUser.name
5030                                            + " differs from " + pkg.mSharedUserId);
5031                                    origPackage = null;
5032                                    continue;
5033                                }
5034                            } else {
5035                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5036                                        + pkg.packageName + " to old name " + origPackage.name);
5037                            }
5038                            break;
5039                        }
5040                    }
5041                }
5042            }
5043
5044            if (mTransferedPackages.contains(pkg.packageName)) {
5045                Slog.w(TAG, "Package " + pkg.packageName
5046                        + " was transferred to another, but its .apk remains");
5047            }
5048
5049            // Just create the setting, don't add it yet. For already existing packages
5050            // the PkgSetting exists already and doesn't have to be created.
5051            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5052                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5053                    pkg.applicationInfo.cpuAbi,
5054                    pkg.applicationInfo.flags, user, false);
5055            if (pkgSetting == null) {
5056                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5057                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5058                return null;
5059            }
5060
5061            if (pkgSetting.origPackage != null) {
5062                // If we are first transitioning from an original package,
5063                // fix up the new package's name now.  We need to do this after
5064                // looking up the package under its new name, so getPackageLP
5065                // can take care of fiddling things correctly.
5066                pkg.setPackageName(origPackage.name);
5067
5068                // File a report about this.
5069                String msg = "New package " + pkgSetting.realName
5070                        + " renamed to replace old package " + pkgSetting.name;
5071                reportSettingsProblem(Log.WARN, msg);
5072
5073                // Make a note of it.
5074                mTransferedPackages.add(origPackage.name);
5075
5076                // No longer need to retain this.
5077                pkgSetting.origPackage = null;
5078            }
5079
5080            if (realName != null) {
5081                // Make a note of it.
5082                mTransferedPackages.add(pkg.packageName);
5083            }
5084
5085            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5086                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5087            }
5088
5089            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5090                // Check all shared libraries and map to their actual file path.
5091                // We only do this here for apps not on a system dir, because those
5092                // are the only ones that can fail an install due to this.  We
5093                // will take care of the system apps by updating all of their
5094                // library paths after the scan is done.
5095                if (!updateSharedLibrariesLPw(pkg, null)) {
5096                    return null;
5097                }
5098            }
5099
5100            if (mFoundPolicyFile) {
5101                SELinuxMMAC.assignSeinfoValue(pkg);
5102            }
5103
5104            pkg.applicationInfo.uid = pkgSetting.appId;
5105            pkg.mExtras = pkgSetting;
5106
5107            if (!verifySignaturesLP(pkgSetting, pkg)) {
5108                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5109                    return null;
5110                }
5111                // The signature has changed, but this package is in the system
5112                // image...  let's recover!
5113                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5114                // However...  if this package is part of a shared user, but it
5115                // doesn't match the signature of the shared user, let's fail.
5116                // What this means is that you can't change the signatures
5117                // associated with an overall shared user, which doesn't seem all
5118                // that unreasonable.
5119                if (pkgSetting.sharedUser != null) {
5120                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5121                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5122                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5123                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5124                        return null;
5125                    }
5126                }
5127                // File a report about this.
5128                String msg = "System package " + pkg.packageName
5129                        + " signature changed; retaining data.";
5130                reportSettingsProblem(Log.WARN, msg);
5131            }
5132
5133            // Verify that this new package doesn't have any content providers
5134            // that conflict with existing packages.  Only do this if the
5135            // package isn't already installed, since we don't want to break
5136            // things that are installed.
5137            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5138                final int N = pkg.providers.size();
5139                int i;
5140                for (i=0; i<N; i++) {
5141                    PackageParser.Provider p = pkg.providers.get(i);
5142                    if (p.info.authority != null) {
5143                        String names[] = p.info.authority.split(";");
5144                        for (int j = 0; j < names.length; j++) {
5145                            if (mProvidersByAuthority.containsKey(names[j])) {
5146                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5147                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5148                                        " (in package " + pkg.applicationInfo.packageName +
5149                                        ") is already used by "
5150                                        + ((other != null && other.getComponentName() != null)
5151                                                ? other.getComponentName().getPackageName() : "?"));
5152                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5153                                return null;
5154                            }
5155                        }
5156                    }
5157                }
5158            }
5159
5160            if (pkg.mAdoptPermissions != null) {
5161                // This package wants to adopt ownership of permissions from
5162                // another package.
5163                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5164                    final String origName = pkg.mAdoptPermissions.get(i);
5165                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5166                    if (orig != null) {
5167                        if (verifyPackageUpdateLPr(orig, pkg)) {
5168                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5169                                    + pkg.packageName);
5170                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5171                        }
5172                    }
5173                }
5174            }
5175        }
5176
5177        final String pkgName = pkg.packageName;
5178
5179        final long scanFileTime = scanFile.lastModified();
5180        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5181        pkg.applicationInfo.processName = fixProcessName(
5182                pkg.applicationInfo.packageName,
5183                pkg.applicationInfo.processName,
5184                pkg.applicationInfo.uid);
5185
5186        File dataPath;
5187        if (mPlatformPackage == pkg) {
5188            // The system package is special.
5189            dataPath = new File (Environment.getDataDirectory(), "system");
5190            pkg.applicationInfo.dataDir = dataPath.getPath();
5191        } else {
5192            // This is a normal package, need to make its data directory.
5193            dataPath = getDataPathForPackage(pkg.packageName, 0);
5194
5195            boolean uidError = false;
5196
5197            if (dataPath.exists()) {
5198                int currentUid = 0;
5199                try {
5200                    StructStat stat = Os.stat(dataPath.getPath());
5201                    currentUid = stat.st_uid;
5202                } catch (ErrnoException e) {
5203                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5204                }
5205
5206                // If we have mismatched owners for the data path, we have a problem.
5207                if (currentUid != pkg.applicationInfo.uid) {
5208                    boolean recovered = false;
5209                    if (currentUid == 0) {
5210                        // The directory somehow became owned by root.  Wow.
5211                        // This is probably because the system was stopped while
5212                        // installd was in the middle of messing with its libs
5213                        // directory.  Ask installd to fix that.
5214                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5215                                pkg.applicationInfo.uid);
5216                        if (ret >= 0) {
5217                            recovered = true;
5218                            String msg = "Package " + pkg.packageName
5219                                    + " unexpectedly changed to uid 0; recovered to " +
5220                                    + pkg.applicationInfo.uid;
5221                            reportSettingsProblem(Log.WARN, msg);
5222                        }
5223                    }
5224                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5225                            || (scanMode&SCAN_BOOTING) != 0)) {
5226                        // If this is a system app, we can at least delete its
5227                        // current data so the application will still work.
5228                        int ret = removeDataDirsLI(pkgName);
5229                        if (ret >= 0) {
5230                            // TODO: Kill the processes first
5231                            // Old data gone!
5232                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5233                                    ? "System package " : "Third party package ";
5234                            String msg = prefix + pkg.packageName
5235                                    + " has changed from uid: "
5236                                    + currentUid + " to "
5237                                    + pkg.applicationInfo.uid + "; old data erased";
5238                            reportSettingsProblem(Log.WARN, msg);
5239                            recovered = true;
5240
5241                            // And now re-install the app.
5242                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5243                                                   pkg.applicationInfo.seinfo);
5244                            if (ret == -1) {
5245                                // Ack should not happen!
5246                                msg = prefix + pkg.packageName
5247                                        + " could not have data directory re-created after delete.";
5248                                reportSettingsProblem(Log.WARN, msg);
5249                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5250                                return null;
5251                            }
5252                        }
5253                        if (!recovered) {
5254                            mHasSystemUidErrors = true;
5255                        }
5256                    } else if (!recovered) {
5257                        // If we allow this install to proceed, we will be broken.
5258                        // Abort, abort!
5259                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5260                        return null;
5261                    }
5262                    if (!recovered) {
5263                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5264                            + pkg.applicationInfo.uid + "/fs_"
5265                            + currentUid;
5266                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5267                        String msg = "Package " + pkg.packageName
5268                                + " has mismatched uid: "
5269                                + currentUid + " on disk, "
5270                                + pkg.applicationInfo.uid + " in settings";
5271                        // writer
5272                        synchronized (mPackages) {
5273                            mSettings.mReadMessages.append(msg);
5274                            mSettings.mReadMessages.append('\n');
5275                            uidError = true;
5276                            if (!pkgSetting.uidError) {
5277                                reportSettingsProblem(Log.ERROR, msg);
5278                            }
5279                        }
5280                    }
5281                }
5282                pkg.applicationInfo.dataDir = dataPath.getPath();
5283                if (mShouldRestoreconData) {
5284                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5285                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5286                                pkg.applicationInfo.uid);
5287                }
5288            } else {
5289                if (DEBUG_PACKAGE_SCANNING) {
5290                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5291                        Log.v(TAG, "Want this data dir: " + dataPath);
5292                }
5293                //invoke installer to do the actual installation
5294                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5295                                           pkg.applicationInfo.seinfo);
5296                if (ret < 0) {
5297                    // Error from installer
5298                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5299                    return null;
5300                }
5301
5302                if (dataPath.exists()) {
5303                    pkg.applicationInfo.dataDir = dataPath.getPath();
5304                } else {
5305                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5306                    pkg.applicationInfo.dataDir = null;
5307                }
5308            }
5309
5310            /*
5311             * Set the data dir to the default "/data/data/<package name>/lib"
5312             * if we got here without anyone telling us different (e.g., apps
5313             * stored on SD card have their native libraries stored in the ASEC
5314             * container with the APK).
5315             *
5316             * This happens during an upgrade from a package settings file that
5317             * doesn't have a native library path attribute at all.
5318             */
5319            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5320                if (pkgSetting.nativeLibraryPathString == null) {
5321                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5322                } else {
5323                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5324                }
5325            }
5326            pkgSetting.uidError = uidError;
5327        }
5328
5329        final String path = scanFile.getPath();
5330        /* Note: We don't want to unpack the native binaries for
5331         *        system applications, unless they have been updated
5332         *        (the binaries are already under /system/lib).
5333         *        Also, don't unpack libs for apps on the external card
5334         *        since they should have their libraries in the ASEC
5335         *        container already.
5336         *
5337         *        In other words, we're going to unpack the binaries
5338         *        only for non-system apps and system app upgrades.
5339         */
5340        if (pkg.applicationInfo.nativeLibraryDir != null) {
5341            // TODO: extend to extract native code from split APKs
5342            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5343            try {
5344                // Enable gross and lame hacks for apps that are built with old
5345                // SDK tools. We must scan their APKs for renderscript bitcode and
5346                // not launch them if it's present. Don't bother checking on devices
5347                // that don't have 64 bit support.
5348                String[] abiList = Build.SUPPORTED_ABIS;
5349                boolean hasLegacyRenderscriptBitcode = false;
5350                if (abiOverride != null) {
5351                    abiList = new String[] { abiOverride };
5352                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5353                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5354                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5355                    hasLegacyRenderscriptBitcode = true;
5356                }
5357
5358                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5359                final String dataPathString = dataPath.getCanonicalPath();
5360
5361                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5362                    /*
5363                     * Upgrading from a previous version of the OS sometimes
5364                     * leaves native libraries in the /data/data/<app>/lib
5365                     * directory for system apps even when they shouldn't be.
5366                     * Recent changes in the JNI library search path
5367                     * necessitates we remove those to match previous behavior.
5368                     */
5369                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5370                        Log.i(TAG, "removed obsolete native libraries for system package "
5371                                + path);
5372                    }
5373                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5374                        pkg.applicationInfo.cpuAbi = abiList[0];
5375                        pkgSetting.cpuAbiString = abiList[0];
5376                    } else {
5377                        setInternalAppAbi(pkg, pkgSetting);
5378                    }
5379                } else {
5380                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5381                        /*
5382                        * Update native library dir if it starts with
5383                        * /data/data
5384                        */
5385                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5386                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5387                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5388                        }
5389
5390                        try {
5391                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5392                                    nativeLibraryDir, abiList);
5393                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5394                                Slog.e(TAG, "Unable to copy native libraries");
5395                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5396                                return null;
5397                            }
5398
5399                            // We've successfully copied native libraries across, so we make a
5400                            // note of what ABI we're using
5401                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5402                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5403                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5404                                pkg.applicationInfo.cpuAbi = abiList[0];
5405                            } else {
5406                                pkg.applicationInfo.cpuAbi = null;
5407                            }
5408                        } catch (IOException e) {
5409                            Slog.e(TAG, "Unable to copy native libraries", e);
5410                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5411                            return null;
5412                        }
5413                    } else {
5414                        // We don't have to copy the shared libraries if we're in the ASEC container
5415                        // but we still need to scan the file to figure out what ABI the app needs.
5416                        //
5417                        // TODO: This duplicates work done in the default container service. It's possible
5418                        // to clean this up but we'll need to change the interface between this service
5419                        // and IMediaContainerService (but doing so will spread this logic out, rather
5420                        // than centralizing it).
5421                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5422                        if (abi >= 0) {
5423                            pkg.applicationInfo.cpuAbi = abiList[abi];
5424                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5425                            // Note that (non upgraded) system apps will not have any native
5426                            // libraries bundled in their APK, but we're guaranteed not to be
5427                            // such an app at this point.
5428                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5429                                pkg.applicationInfo.cpuAbi = abiList[0];
5430                            } else {
5431                                pkg.applicationInfo.cpuAbi = null;
5432                            }
5433                        } else {
5434                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5435                            return null;
5436                        }
5437                    }
5438
5439                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5440                    final int[] userIds = sUserManager.getUserIds();
5441                    synchronized (mInstallLock) {
5442                        for (int userId : userIds) {
5443                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5444                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5445                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5446                                        + ")");
5447                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5448                                return null;
5449                            }
5450                        }
5451                    }
5452                }
5453
5454                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5455            } catch (IOException ioe) {
5456                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5457            } finally {
5458                handle.close();
5459            }
5460        }
5461
5462        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5463            // We don't do this here during boot because we can do it all
5464            // at once after scanning all existing packages.
5465            //
5466            // We also do this *before* we perform dexopt on this package, so that
5467            // we can avoid redundant dexopts, and also to make sure we've got the
5468            // code and package path correct.
5469            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5470                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5471                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5472                return null;
5473            }
5474        }
5475
5476        if ((scanMode&SCAN_NO_DEX) == 0) {
5477            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5478                    == DEX_OPT_FAILED) {
5479                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5480                    removeDataDirsLI(pkg.packageName);
5481                }
5482
5483                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5484                return null;
5485            }
5486        }
5487
5488        if (mFactoryTest && pkg.requestedPermissions.contains(
5489                android.Manifest.permission.FACTORY_TEST)) {
5490            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5491        }
5492
5493        ArrayList<PackageParser.Package> clientLibPkgs = null;
5494
5495        // writer
5496        synchronized (mPackages) {
5497            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5498                // Only system apps can add new shared libraries.
5499                if (pkg.libraryNames != null) {
5500                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5501                        String name = pkg.libraryNames.get(i);
5502                        boolean allowed = false;
5503                        if (isUpdatedSystemApp(pkg)) {
5504                            // New library entries can only be added through the
5505                            // system image.  This is important to get rid of a lot
5506                            // of nasty edge cases: for example if we allowed a non-
5507                            // system update of the app to add a library, then uninstalling
5508                            // the update would make the library go away, and assumptions
5509                            // we made such as through app install filtering would now
5510                            // have allowed apps on the device which aren't compatible
5511                            // with it.  Better to just have the restriction here, be
5512                            // conservative, and create many fewer cases that can negatively
5513                            // impact the user experience.
5514                            final PackageSetting sysPs = mSettings
5515                                    .getDisabledSystemPkgLPr(pkg.packageName);
5516                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5517                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5518                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5519                                        allowed = true;
5520                                        allowed = true;
5521                                        break;
5522                                    }
5523                                }
5524                            }
5525                        } else {
5526                            allowed = true;
5527                        }
5528                        if (allowed) {
5529                            if (!mSharedLibraries.containsKey(name)) {
5530                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5531                            } else if (!name.equals(pkg.packageName)) {
5532                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5533                                        + name + " already exists; skipping");
5534                            }
5535                        } else {
5536                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5537                                    + name + " that is not declared on system image; skipping");
5538                        }
5539                    }
5540                    if ((scanMode&SCAN_BOOTING) == 0) {
5541                        // If we are not booting, we need to update any applications
5542                        // that are clients of our shared library.  If we are booting,
5543                        // this will all be done once the scan is complete.
5544                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5545                    }
5546                }
5547            }
5548        }
5549
5550        // We also need to dexopt any apps that are dependent on this library.  Note that
5551        // if these fail, we should abort the install since installing the library will
5552        // result in some apps being broken.
5553        if (clientLibPkgs != null) {
5554            if ((scanMode&SCAN_NO_DEX) == 0) {
5555                for (int i=0; i<clientLibPkgs.size(); i++) {
5556                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5557                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5558                            == DEX_OPT_FAILED) {
5559                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5560                            removeDataDirsLI(pkg.packageName);
5561                        }
5562
5563                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5564                        return null;
5565                    }
5566                }
5567            }
5568        }
5569
5570        // Request the ActivityManager to kill the process(only for existing packages)
5571        // so that we do not end up in a confused state while the user is still using the older
5572        // version of the application while the new one gets installed.
5573        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5574            // If the package lives in an asec, tell everyone that the container is going
5575            // away so they can clean up any references to its resources (which would prevent
5576            // vold from being able to unmount the asec)
5577            if (isForwardLocked(pkg) || isExternal(pkg)) {
5578                if (DEBUG_INSTALL) {
5579                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5580                }
5581                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5582                final ArrayList<String> pkgList = new ArrayList<String>(1);
5583                pkgList.add(pkg.applicationInfo.packageName);
5584                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5585            }
5586
5587            // Post the request that it be killed now that the going-away broadcast is en route
5588            killApplication(pkg.applicationInfo.packageName,
5589                        pkg.applicationInfo.uid, "update pkg");
5590        }
5591
5592        // Also need to kill any apps that are dependent on the library.
5593        if (clientLibPkgs != null) {
5594            for (int i=0; i<clientLibPkgs.size(); i++) {
5595                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5596                killApplication(clientPkg.applicationInfo.packageName,
5597                        clientPkg.applicationInfo.uid, "update lib");
5598            }
5599        }
5600
5601        // writer
5602        synchronized (mPackages) {
5603            // We don't expect installation to fail beyond this point,
5604            if ((scanMode&SCAN_MONITOR) != 0) {
5605                mAppDirs.put(pkg.codePath, pkg);
5606            }
5607            // Add the new setting to mSettings
5608            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5609            // Add the new setting to mPackages
5610            mPackages.put(pkg.applicationInfo.packageName, pkg);
5611            // Make sure we don't accidentally delete its data.
5612            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5613            while (iter.hasNext()) {
5614                PackageCleanItem item = iter.next();
5615                if (pkgName.equals(item.packageName)) {
5616                    iter.remove();
5617                }
5618            }
5619
5620            // Take care of first install / last update times.
5621            if (currentTime != 0) {
5622                if (pkgSetting.firstInstallTime == 0) {
5623                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5624                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5625                    pkgSetting.lastUpdateTime = currentTime;
5626                }
5627            } else if (pkgSetting.firstInstallTime == 0) {
5628                // We need *something*.  Take time time stamp of the file.
5629                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5630            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5631                if (scanFileTime != pkgSetting.timeStamp) {
5632                    // A package on the system image has changed; consider this
5633                    // to be an update.
5634                    pkgSetting.lastUpdateTime = scanFileTime;
5635                }
5636            }
5637
5638            // Add the package's KeySets to the global KeySetManager
5639            KeySetManager ksm = mSettings.mKeySetManager;
5640            try {
5641                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5642                if (pkg.mKeySetMapping != null) {
5643                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5644                            pkg.mKeySetMapping.entrySet()) {
5645                        if (entry.getValue() != null) {
5646                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5647                                entry.getValue(), entry.getKey());
5648                        }
5649                    }
5650                }
5651            } catch (NullPointerException e) {
5652                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5653            } catch (IllegalArgumentException e) {
5654                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5655            }
5656
5657            int N = pkg.providers.size();
5658            StringBuilder r = null;
5659            int i;
5660            for (i=0; i<N; i++) {
5661                PackageParser.Provider p = pkg.providers.get(i);
5662                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5663                        p.info.processName, pkg.applicationInfo.uid);
5664                mProviders.addProvider(p);
5665                p.syncable = p.info.isSyncable;
5666                if (p.info.authority != null) {
5667                    String names[] = p.info.authority.split(";");
5668                    p.info.authority = null;
5669                    for (int j = 0; j < names.length; j++) {
5670                        if (j == 1 && p.syncable) {
5671                            // We only want the first authority for a provider to possibly be
5672                            // syncable, so if we already added this provider using a different
5673                            // authority clear the syncable flag. We copy the provider before
5674                            // changing it because the mProviders object contains a reference
5675                            // to a provider that we don't want to change.
5676                            // Only do this for the second authority since the resulting provider
5677                            // object can be the same for all future authorities for this provider.
5678                            p = new PackageParser.Provider(p);
5679                            p.syncable = false;
5680                        }
5681                        if (!mProvidersByAuthority.containsKey(names[j])) {
5682                            mProvidersByAuthority.put(names[j], p);
5683                            if (p.info.authority == null) {
5684                                p.info.authority = names[j];
5685                            } else {
5686                                p.info.authority = p.info.authority + ";" + names[j];
5687                            }
5688                            if (DEBUG_PACKAGE_SCANNING) {
5689                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5690                                    Log.d(TAG, "Registered content provider: " + names[j]
5691                                            + ", className = " + p.info.name + ", isSyncable = "
5692                                            + p.info.isSyncable);
5693                            }
5694                        } else {
5695                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5696                            Slog.w(TAG, "Skipping provider name " + names[j] +
5697                                    " (in package " + pkg.applicationInfo.packageName +
5698                                    "): name already used by "
5699                                    + ((other != null && other.getComponentName() != null)
5700                                            ? other.getComponentName().getPackageName() : "?"));
5701                        }
5702                    }
5703                }
5704                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5705                    if (r == null) {
5706                        r = new StringBuilder(256);
5707                    } else {
5708                        r.append(' ');
5709                    }
5710                    r.append(p.info.name);
5711                }
5712            }
5713            if (r != null) {
5714                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5715            }
5716
5717            N = pkg.services.size();
5718            r = null;
5719            for (i=0; i<N; i++) {
5720                PackageParser.Service s = pkg.services.get(i);
5721                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5722                        s.info.processName, pkg.applicationInfo.uid);
5723                mServices.addService(s);
5724                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5725                    if (r == null) {
5726                        r = new StringBuilder(256);
5727                    } else {
5728                        r.append(' ');
5729                    }
5730                    r.append(s.info.name);
5731                }
5732            }
5733            if (r != null) {
5734                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5735            }
5736
5737            N = pkg.receivers.size();
5738            r = null;
5739            for (i=0; i<N; i++) {
5740                PackageParser.Activity a = pkg.receivers.get(i);
5741                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5742                        a.info.processName, pkg.applicationInfo.uid);
5743                mReceivers.addActivity(a, "receiver");
5744                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5745                    if (r == null) {
5746                        r = new StringBuilder(256);
5747                    } else {
5748                        r.append(' ');
5749                    }
5750                    r.append(a.info.name);
5751                }
5752            }
5753            if (r != null) {
5754                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5755            }
5756
5757            N = pkg.activities.size();
5758            r = null;
5759            for (i=0; i<N; i++) {
5760                PackageParser.Activity a = pkg.activities.get(i);
5761                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5762                        a.info.processName, pkg.applicationInfo.uid);
5763                mActivities.addActivity(a, "activity");
5764                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5765                    if (r == null) {
5766                        r = new StringBuilder(256);
5767                    } else {
5768                        r.append(' ');
5769                    }
5770                    r.append(a.info.name);
5771                }
5772            }
5773            if (r != null) {
5774                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5775            }
5776
5777            N = pkg.permissionGroups.size();
5778            r = null;
5779            for (i=0; i<N; i++) {
5780                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5781                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5782                if (cur == null) {
5783                    mPermissionGroups.put(pg.info.name, pg);
5784                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5785                        if (r == null) {
5786                            r = new StringBuilder(256);
5787                        } else {
5788                            r.append(' ');
5789                        }
5790                        r.append(pg.info.name);
5791                    }
5792                } else {
5793                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5794                            + pg.info.packageName + " ignored: original from "
5795                            + cur.info.packageName);
5796                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5797                        if (r == null) {
5798                            r = new StringBuilder(256);
5799                        } else {
5800                            r.append(' ');
5801                        }
5802                        r.append("DUP:");
5803                        r.append(pg.info.name);
5804                    }
5805                }
5806            }
5807            if (r != null) {
5808                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5809            }
5810
5811            N = pkg.permissions.size();
5812            r = null;
5813            for (i=0; i<N; i++) {
5814                PackageParser.Permission p = pkg.permissions.get(i);
5815                HashMap<String, BasePermission> permissionMap =
5816                        p.tree ? mSettings.mPermissionTrees
5817                        : mSettings.mPermissions;
5818                p.group = mPermissionGroups.get(p.info.group);
5819                if (p.info.group == null || p.group != null) {
5820                    BasePermission bp = permissionMap.get(p.info.name);
5821                    if (bp == null) {
5822                        bp = new BasePermission(p.info.name, p.info.packageName,
5823                                BasePermission.TYPE_NORMAL);
5824                        permissionMap.put(p.info.name, bp);
5825                    }
5826                    if (bp.perm == null) {
5827                        if (bp.sourcePackage != null
5828                                && !bp.sourcePackage.equals(p.info.packageName)) {
5829                            // If this is a permission that was formerly defined by a non-system
5830                            // app, but is now defined by a system app (following an upgrade),
5831                            // discard the previous declaration and consider the system's to be
5832                            // canonical.
5833                            if (isSystemApp(p.owner)) {
5834                                String msg = "New decl " + p.owner + " of permission  "
5835                                        + p.info.name + " is system";
5836                                reportSettingsProblem(Log.WARN, msg);
5837                                bp.sourcePackage = null;
5838                            }
5839                        }
5840                        if (bp.sourcePackage == null
5841                                || bp.sourcePackage.equals(p.info.packageName)) {
5842                            BasePermission tree = findPermissionTreeLP(p.info.name);
5843                            if (tree == null
5844                                    || tree.sourcePackage.equals(p.info.packageName)) {
5845                                bp.packageSetting = pkgSetting;
5846                                bp.perm = p;
5847                                bp.uid = pkg.applicationInfo.uid;
5848                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5849                                    if (r == null) {
5850                                        r = new StringBuilder(256);
5851                                    } else {
5852                                        r.append(' ');
5853                                    }
5854                                    r.append(p.info.name);
5855                                }
5856                            } else {
5857                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5858                                        + p.info.packageName + " ignored: base tree "
5859                                        + tree.name + " is from package "
5860                                        + tree.sourcePackage);
5861                            }
5862                        } else {
5863                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5864                                    + p.info.packageName + " ignored: original from "
5865                                    + bp.sourcePackage);
5866                        }
5867                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5868                        if (r == null) {
5869                            r = new StringBuilder(256);
5870                        } else {
5871                            r.append(' ');
5872                        }
5873                        r.append("DUP:");
5874                        r.append(p.info.name);
5875                    }
5876                    if (bp.perm == p) {
5877                        bp.protectionLevel = p.info.protectionLevel;
5878                    }
5879                } else {
5880                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5881                            + p.info.packageName + " ignored: no group "
5882                            + p.group);
5883                }
5884            }
5885            if (r != null) {
5886                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5887            }
5888
5889            N = pkg.instrumentation.size();
5890            r = null;
5891            for (i=0; i<N; i++) {
5892                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5893                a.info.packageName = pkg.applicationInfo.packageName;
5894                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5895                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5896                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5897                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5898                a.info.dataDir = pkg.applicationInfo.dataDir;
5899                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5900                mInstrumentation.put(a.getComponentName(), a);
5901                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5902                    if (r == null) {
5903                        r = new StringBuilder(256);
5904                    } else {
5905                        r.append(' ');
5906                    }
5907                    r.append(a.info.name);
5908                }
5909            }
5910            if (r != null) {
5911                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5912            }
5913
5914            if (pkg.protectedBroadcasts != null) {
5915                N = pkg.protectedBroadcasts.size();
5916                for (i=0; i<N; i++) {
5917                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5918                }
5919            }
5920
5921            pkgSetting.setTimeStamp(scanFileTime);
5922
5923            // Create idmap files for pairs of (packages, overlay packages).
5924            // Note: "android", ie framework-res.apk, is handled by native layers.
5925            if (pkg.mOverlayTarget != null) {
5926                // This is an overlay package.
5927                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5928                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5929                        mOverlays.put(pkg.mOverlayTarget,
5930                                new HashMap<String, PackageParser.Package>());
5931                    }
5932                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5933                    map.put(pkg.packageName, pkg);
5934                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5935                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5936                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5937                        return null;
5938                    }
5939                }
5940            } else if (mOverlays.containsKey(pkg.packageName) &&
5941                    !pkg.packageName.equals("android")) {
5942                // This is a regular package, with one or more known overlay packages.
5943                createIdmapsForPackageLI(pkg);
5944            }
5945        }
5946
5947        return pkg;
5948    }
5949
5950    /**
5951     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5952     * i.e, so that all packages can be run inside a single process if required.
5953     *
5954     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5955     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5956     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5957     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5958     * updating a package that belongs to a shared user.
5959     */
5960    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5961            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5962        String requiredInstructionSet = null;
5963        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5964            requiredInstructionSet = VMRuntime.getInstructionSet(
5965                     scannedPackage.applicationInfo.cpuAbi);
5966        }
5967
5968        PackageSetting requirer = null;
5969        for (PackageSetting ps : packagesForUser) {
5970            // If packagesForUser contains scannedPackage, we skip it. This will happen
5971            // when scannedPackage is an update of an existing package. Without this check,
5972            // we will never be able to change the ABI of any package belonging to a shared
5973            // user, even if it's compatible with other packages.
5974            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
5975                if (ps.cpuAbiString == null) {
5976                    continue;
5977                }
5978
5979                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5980                if (requiredInstructionSet != null) {
5981                    if (!instructionSet.equals(requiredInstructionSet)) {
5982                        // We have a mismatch between instruction sets (say arm vs arm64).
5983                        // bail out.
5984                        String errorMessage = "Instruction set mismatch, "
5985                                + ((requirer == null) ? "[caller]" : requirer)
5986                                + " requires " + requiredInstructionSet + " whereas " + ps
5987                                + " requires " + instructionSet;
5988                        Slog.e(TAG, errorMessage);
5989
5990                        reportSettingsProblem(Log.WARN, errorMessage);
5991                        // Give up, don't bother making any other changes to the package settings.
5992                        return false;
5993                    }
5994                } else {
5995                    requiredInstructionSet = instructionSet;
5996                    requirer = ps;
5997                }
5998            }
5999        }
6000
6001        if (requiredInstructionSet != null) {
6002            String adjustedAbi;
6003            if (requirer != null) {
6004                // requirer != null implies that either scannedPackage was null or that scannedPackage
6005                // did not require an ABI, in which case we have to adjust scannedPackage to match
6006                // the ABI of the set (which is the same as requirer's ABI)
6007                adjustedAbi = requirer.cpuAbiString;
6008                if (scannedPackage != null) {
6009                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6010                }
6011            } else {
6012                // requirer == null implies that we're updating all ABIs in the set to
6013                // match scannedPackage.
6014                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6015            }
6016
6017            for (PackageSetting ps : packagesForUser) {
6018                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6019                    if (ps.cpuAbiString != null) {
6020                        continue;
6021                    }
6022
6023                    ps.cpuAbiString = adjustedAbi;
6024                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6025                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6026                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6027
6028                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6029                            ps.cpuAbiString = null;
6030                            ps.pkg.applicationInfo.cpuAbi = null;
6031                            return false;
6032                        } else {
6033                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6034                        }
6035                    }
6036                }
6037            }
6038        }
6039
6040        return true;
6041    }
6042
6043    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6044        synchronized (mPackages) {
6045            mResolverReplaced = true;
6046            // Set up information for custom user intent resolution activity.
6047            mResolveActivity.applicationInfo = pkg.applicationInfo;
6048            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6049            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6050            mResolveActivity.processName = null;
6051            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6052            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6053                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6054            mResolveActivity.theme = 0;
6055            mResolveActivity.exported = true;
6056            mResolveActivity.enabled = true;
6057            mResolveInfo.activityInfo = mResolveActivity;
6058            mResolveInfo.priority = 0;
6059            mResolveInfo.preferredOrder = 0;
6060            mResolveInfo.match = 0;
6061            mResolveComponentName = mCustomResolverComponentName;
6062            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6063                    mResolveComponentName);
6064        }
6065    }
6066
6067    private String calculateApkRoot(final String codePathString) {
6068        final File codePath = new File(codePathString);
6069        final File codeRoot;
6070        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6071            codeRoot = Environment.getRootDirectory();
6072        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6073            codeRoot = Environment.getOemDirectory();
6074        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6075            codeRoot = Environment.getVendorDirectory();
6076        } else {
6077            // Unrecognized code path; take its top real segment as the apk root:
6078            // e.g. /something/app/blah.apk => /something
6079            try {
6080                File f = codePath.getCanonicalFile();
6081                File parent = f.getParentFile();    // non-null because codePath is a file
6082                File tmp;
6083                while ((tmp = parent.getParentFile()) != null) {
6084                    f = parent;
6085                    parent = tmp;
6086                }
6087                codeRoot = f;
6088                Slog.w(TAG, "Unrecognized code path "
6089                        + codePath + " - using " + codeRoot);
6090            } catch (IOException e) {
6091                // Can't canonicalize the lib path -- shenanigans?
6092                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6093                return Environment.getRootDirectory().getPath();
6094            }
6095        }
6096        return codeRoot.getPath();
6097    }
6098
6099    // This is the initial scan-time determination of how to handle a given
6100    // package for purposes of native library location.
6101    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6102            PackageSetting pkgSetting) {
6103        // "bundled" here means system-installed with no overriding update
6104        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6105        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6106        final File libDir;
6107        if (bundledApk) {
6108            // If "/system/lib64/apkname" exists, assume that is the per-package
6109            // native library directory to use; otherwise use "/system/lib/apkname".
6110            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6111            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6112            File packLib64 = new File(lib64, apkName);
6113            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6114        } else {
6115            libDir = mAppLibInstallDir;
6116        }
6117        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6118        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6119        // pkgSetting might be null during rescan following uninstall of updates
6120        // to a bundled app, so accommodate that possibility.  The settings in
6121        // that case will be established later from the parsed package.
6122        if (pkgSetting != null) {
6123            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6124        }
6125    }
6126
6127    // Deduces the required ABI of an upgraded system app.
6128    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6129        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6130        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6131
6132        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6133        // or similar.
6134        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6135        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6136
6137        // Assume that the bundled native libraries always correspond to the
6138        // most preferred 32 or 64 bit ABI.
6139        if (lib64.exists()) {
6140            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6141            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6142        } else if (lib.exists()) {
6143            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6144            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6145        } else {
6146            // This is the case where the app has no native code.
6147            pkg.applicationInfo.cpuAbi = null;
6148            pkgSetting.cpuAbiString = null;
6149        }
6150    }
6151
6152    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6153            final File nativeLibraryDir, String[] abiList) throws IOException {
6154        if (!nativeLibraryDir.isDirectory()) {
6155            nativeLibraryDir.delete();
6156
6157            if (!nativeLibraryDir.mkdir()) {
6158                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6159            }
6160
6161            try {
6162                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6163            } catch (ErrnoException e) {
6164                throw new IOException("Cannot chmod native library directory "
6165                        + nativeLibraryDir.getPath(), e);
6166            }
6167        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6168            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6169        }
6170
6171        /*
6172         * If this is an internal application or our nativeLibraryPath points to
6173         * the app-lib directory, unpack the libraries if necessary.
6174         */
6175        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6176        if (abi >= 0) {
6177            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6178                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6179            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6180                return copyRet;
6181            }
6182        }
6183
6184        return abi;
6185    }
6186
6187    private void killApplication(String pkgName, int appId, String reason) {
6188        // Request the ActivityManager to kill the process(only for existing packages)
6189        // so that we do not end up in a confused state while the user is still using the older
6190        // version of the application while the new one gets installed.
6191        IActivityManager am = ActivityManagerNative.getDefault();
6192        if (am != null) {
6193            try {
6194                am.killApplicationWithAppId(pkgName, appId, reason);
6195            } catch (RemoteException e) {
6196            }
6197        }
6198    }
6199
6200    void removePackageLI(PackageSetting ps, boolean chatty) {
6201        if (DEBUG_INSTALL) {
6202            if (chatty)
6203                Log.d(TAG, "Removing package " + ps.name);
6204        }
6205
6206        // writer
6207        synchronized (mPackages) {
6208            mPackages.remove(ps.name);
6209            if (ps.codePathString != null) {
6210                mAppDirs.remove(ps.codePathString);
6211            }
6212
6213            final PackageParser.Package pkg = ps.pkg;
6214            if (pkg != null) {
6215                cleanPackageDataStructuresLILPw(pkg, chatty);
6216            }
6217        }
6218    }
6219
6220    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6221        if (DEBUG_INSTALL) {
6222            if (chatty)
6223                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6224        }
6225
6226        // writer
6227        synchronized (mPackages) {
6228            mPackages.remove(pkg.applicationInfo.packageName);
6229            if (pkg.codePath != null) {
6230                mAppDirs.remove(pkg.codePath);
6231            }
6232            cleanPackageDataStructuresLILPw(pkg, chatty);
6233        }
6234    }
6235
6236    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6237        int N = pkg.providers.size();
6238        StringBuilder r = null;
6239        int i;
6240        for (i=0; i<N; i++) {
6241            PackageParser.Provider p = pkg.providers.get(i);
6242            mProviders.removeProvider(p);
6243            if (p.info.authority == null) {
6244
6245                /* There was another ContentProvider with this authority when
6246                 * this app was installed so this authority is null,
6247                 * Ignore it as we don't have to unregister the provider.
6248                 */
6249                continue;
6250            }
6251            String names[] = p.info.authority.split(";");
6252            for (int j = 0; j < names.length; j++) {
6253                if (mProvidersByAuthority.get(names[j]) == p) {
6254                    mProvidersByAuthority.remove(names[j]);
6255                    if (DEBUG_REMOVE) {
6256                        if (chatty)
6257                            Log.d(TAG, "Unregistered content provider: " + names[j]
6258                                    + ", className = " + p.info.name + ", isSyncable = "
6259                                    + p.info.isSyncable);
6260                    }
6261                }
6262            }
6263            if (DEBUG_REMOVE && chatty) {
6264                if (r == null) {
6265                    r = new StringBuilder(256);
6266                } else {
6267                    r.append(' ');
6268                }
6269                r.append(p.info.name);
6270            }
6271        }
6272        if (r != null) {
6273            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6274        }
6275
6276        N = pkg.services.size();
6277        r = null;
6278        for (i=0; i<N; i++) {
6279            PackageParser.Service s = pkg.services.get(i);
6280            mServices.removeService(s);
6281            if (chatty) {
6282                if (r == null) {
6283                    r = new StringBuilder(256);
6284                } else {
6285                    r.append(' ');
6286                }
6287                r.append(s.info.name);
6288            }
6289        }
6290        if (r != null) {
6291            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6292        }
6293
6294        N = pkg.receivers.size();
6295        r = null;
6296        for (i=0; i<N; i++) {
6297            PackageParser.Activity a = pkg.receivers.get(i);
6298            mReceivers.removeActivity(a, "receiver");
6299            if (DEBUG_REMOVE && chatty) {
6300                if (r == null) {
6301                    r = new StringBuilder(256);
6302                } else {
6303                    r.append(' ');
6304                }
6305                r.append(a.info.name);
6306            }
6307        }
6308        if (r != null) {
6309            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6310        }
6311
6312        N = pkg.activities.size();
6313        r = null;
6314        for (i=0; i<N; i++) {
6315            PackageParser.Activity a = pkg.activities.get(i);
6316            mActivities.removeActivity(a, "activity");
6317            if (DEBUG_REMOVE && chatty) {
6318                if (r == null) {
6319                    r = new StringBuilder(256);
6320                } else {
6321                    r.append(' ');
6322                }
6323                r.append(a.info.name);
6324            }
6325        }
6326        if (r != null) {
6327            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6328        }
6329
6330        N = pkg.permissions.size();
6331        r = null;
6332        for (i=0; i<N; i++) {
6333            PackageParser.Permission p = pkg.permissions.get(i);
6334            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6335            if (bp == null) {
6336                bp = mSettings.mPermissionTrees.get(p.info.name);
6337            }
6338            if (bp != null && bp.perm == p) {
6339                bp.perm = null;
6340                if (DEBUG_REMOVE && chatty) {
6341                    if (r == null) {
6342                        r = new StringBuilder(256);
6343                    } else {
6344                        r.append(' ');
6345                    }
6346                    r.append(p.info.name);
6347                }
6348            }
6349        }
6350        if (r != null) {
6351            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6352        }
6353
6354        N = pkg.instrumentation.size();
6355        r = null;
6356        for (i=0; i<N; i++) {
6357            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6358            mInstrumentation.remove(a.getComponentName());
6359            if (DEBUG_REMOVE && chatty) {
6360                if (r == null) {
6361                    r = new StringBuilder(256);
6362                } else {
6363                    r.append(' ');
6364                }
6365                r.append(a.info.name);
6366            }
6367        }
6368        if (r != null) {
6369            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6370        }
6371
6372        r = null;
6373        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6374            // Only system apps can hold shared libraries.
6375            if (pkg.libraryNames != null) {
6376                for (i=0; i<pkg.libraryNames.size(); i++) {
6377                    String name = pkg.libraryNames.get(i);
6378                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6379                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6380                        mSharedLibraries.remove(name);
6381                        if (DEBUG_REMOVE && chatty) {
6382                            if (r == null) {
6383                                r = new StringBuilder(256);
6384                            } else {
6385                                r.append(' ');
6386                            }
6387                            r.append(name);
6388                        }
6389                    }
6390                }
6391            }
6392        }
6393        if (r != null) {
6394            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6395        }
6396    }
6397
6398    private static final boolean isPackageFilename(String name) {
6399        return name != null && name.endsWith(".apk");
6400    }
6401
6402    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6403        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6404            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6405                return true;
6406            }
6407        }
6408        return false;
6409    }
6410
6411    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6412    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6413    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6414
6415    private void updatePermissionsLPw(String changingPkg,
6416            PackageParser.Package pkgInfo, int flags) {
6417        // Make sure there are no dangling permission trees.
6418        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6419        while (it.hasNext()) {
6420            final BasePermission bp = it.next();
6421            if (bp.packageSetting == null) {
6422                // We may not yet have parsed the package, so just see if
6423                // we still know about its settings.
6424                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6425            }
6426            if (bp.packageSetting == null) {
6427                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6428                        + " from package " + bp.sourcePackage);
6429                it.remove();
6430            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6431                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6432                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6433                            + " from package " + bp.sourcePackage);
6434                    flags |= UPDATE_PERMISSIONS_ALL;
6435                    it.remove();
6436                }
6437            }
6438        }
6439
6440        // Make sure all dynamic permissions have been assigned to a package,
6441        // and make sure there are no dangling permissions.
6442        it = mSettings.mPermissions.values().iterator();
6443        while (it.hasNext()) {
6444            final BasePermission bp = it.next();
6445            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6446                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6447                        + bp.name + " pkg=" + bp.sourcePackage
6448                        + " info=" + bp.pendingInfo);
6449                if (bp.packageSetting == null && bp.pendingInfo != null) {
6450                    final BasePermission tree = findPermissionTreeLP(bp.name);
6451                    if (tree != null && tree.perm != null) {
6452                        bp.packageSetting = tree.packageSetting;
6453                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6454                                new PermissionInfo(bp.pendingInfo));
6455                        bp.perm.info.packageName = tree.perm.info.packageName;
6456                        bp.perm.info.name = bp.name;
6457                        bp.uid = tree.uid;
6458                    }
6459                }
6460            }
6461            if (bp.packageSetting == null) {
6462                // We may not yet have parsed the package, so just see if
6463                // we still know about its settings.
6464                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6465            }
6466            if (bp.packageSetting == null) {
6467                Slog.w(TAG, "Removing dangling permission: " + bp.name
6468                        + " from package " + bp.sourcePackage);
6469                it.remove();
6470            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6471                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6472                    Slog.i(TAG, "Removing old permission: " + bp.name
6473                            + " from package " + bp.sourcePackage);
6474                    flags |= UPDATE_PERMISSIONS_ALL;
6475                    it.remove();
6476                }
6477            }
6478        }
6479
6480        // Now update the permissions for all packages, in particular
6481        // replace the granted permissions of the system packages.
6482        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6483            for (PackageParser.Package pkg : mPackages.values()) {
6484                if (pkg != pkgInfo) {
6485                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6486                }
6487            }
6488        }
6489
6490        if (pkgInfo != null) {
6491            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6492        }
6493    }
6494
6495    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6496        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6497        if (ps == null) {
6498            return;
6499        }
6500        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6501        HashSet<String> origPermissions = gp.grantedPermissions;
6502        boolean changedPermission = false;
6503
6504        if (replace) {
6505            ps.permissionsFixed = false;
6506            if (gp == ps) {
6507                origPermissions = new HashSet<String>(gp.grantedPermissions);
6508                gp.grantedPermissions.clear();
6509                gp.gids = mGlobalGids;
6510            }
6511        }
6512
6513        if (gp.gids == null) {
6514            gp.gids = mGlobalGids;
6515        }
6516
6517        final int N = pkg.requestedPermissions.size();
6518        for (int i=0; i<N; i++) {
6519            final String name = pkg.requestedPermissions.get(i);
6520            final boolean required = pkg.requestedPermissionsRequired.get(i);
6521            final BasePermission bp = mSettings.mPermissions.get(name);
6522            if (DEBUG_INSTALL) {
6523                if (gp != ps) {
6524                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6525                }
6526            }
6527
6528            if (bp == null || bp.packageSetting == null) {
6529                Slog.w(TAG, "Unknown permission " + name
6530                        + " in package " + pkg.packageName);
6531                continue;
6532            }
6533
6534            final String perm = bp.name;
6535            boolean allowed;
6536            boolean allowedSig = false;
6537            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6538            if (level == PermissionInfo.PROTECTION_NORMAL
6539                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6540                // We grant a normal or dangerous permission if any of the following
6541                // are true:
6542                // 1) The permission is required
6543                // 2) The permission is optional, but was granted in the past
6544                // 3) The permission is optional, but was requested by an
6545                //    app in /system (not /data)
6546                //
6547                // Otherwise, reject the permission.
6548                allowed = (required || origPermissions.contains(perm)
6549                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6550            } else if (bp.packageSetting == null) {
6551                // This permission is invalid; skip it.
6552                allowed = false;
6553            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6554                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6555                if (allowed) {
6556                    allowedSig = true;
6557                }
6558            } else {
6559                allowed = false;
6560            }
6561            if (DEBUG_INSTALL) {
6562                if (gp != ps) {
6563                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6564                }
6565            }
6566            if (allowed) {
6567                if (!isSystemApp(ps) && ps.permissionsFixed) {
6568                    // If this is an existing, non-system package, then
6569                    // we can't add any new permissions to it.
6570                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6571                        // Except...  if this is a permission that was added
6572                        // to the platform (note: need to only do this when
6573                        // updating the platform).
6574                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6575                    }
6576                }
6577                if (allowed) {
6578                    if (!gp.grantedPermissions.contains(perm)) {
6579                        changedPermission = true;
6580                        gp.grantedPermissions.add(perm);
6581                        gp.gids = appendInts(gp.gids, bp.gids);
6582                    } else if (!ps.haveGids) {
6583                        gp.gids = appendInts(gp.gids, bp.gids);
6584                    }
6585                } else {
6586                    Slog.w(TAG, "Not granting permission " + perm
6587                            + " to package " + pkg.packageName
6588                            + " because it was previously installed without");
6589                }
6590            } else {
6591                if (gp.grantedPermissions.remove(perm)) {
6592                    changedPermission = true;
6593                    gp.gids = removeInts(gp.gids, bp.gids);
6594                    Slog.i(TAG, "Un-granting permission " + perm
6595                            + " from package " + pkg.packageName
6596                            + " (protectionLevel=" + bp.protectionLevel
6597                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6598                            + ")");
6599                } else {
6600                    Slog.w(TAG, "Not granting permission " + perm
6601                            + " to package " + pkg.packageName
6602                            + " (protectionLevel=" + bp.protectionLevel
6603                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6604                            + ")");
6605                }
6606            }
6607        }
6608
6609        if ((changedPermission || replace) && !ps.permissionsFixed &&
6610                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6611            // This is the first that we have heard about this package, so the
6612            // permissions we have now selected are fixed until explicitly
6613            // changed.
6614            ps.permissionsFixed = true;
6615        }
6616        ps.haveGids = true;
6617    }
6618
6619    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6620        boolean allowed = false;
6621        final int NP = PackageParser.NEW_PERMISSIONS.length;
6622        for (int ip=0; ip<NP; ip++) {
6623            final PackageParser.NewPermissionInfo npi
6624                    = PackageParser.NEW_PERMISSIONS[ip];
6625            if (npi.name.equals(perm)
6626                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6627                allowed = true;
6628                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6629                        + pkg.packageName);
6630                break;
6631            }
6632        }
6633        return allowed;
6634    }
6635
6636    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6637                                          BasePermission bp, HashSet<String> origPermissions) {
6638        boolean allowed;
6639        allowed = (compareSignatures(
6640                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6641                        == PackageManager.SIGNATURE_MATCH)
6642                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6643                        == PackageManager.SIGNATURE_MATCH);
6644        if (!allowed && (bp.protectionLevel
6645                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6646            if (isSystemApp(pkg)) {
6647                // For updated system applications, a system permission
6648                // is granted only if it had been defined by the original application.
6649                if (isUpdatedSystemApp(pkg)) {
6650                    final PackageSetting sysPs = mSettings
6651                            .getDisabledSystemPkgLPr(pkg.packageName);
6652                    final GrantedPermissions origGp = sysPs.sharedUser != null
6653                            ? sysPs.sharedUser : sysPs;
6654
6655                    if (origGp.grantedPermissions.contains(perm)) {
6656                        // If the original was granted this permission, we take
6657                        // that grant decision as read and propagate it to the
6658                        // update.
6659                        allowed = true;
6660                    } else {
6661                        // The system apk may have been updated with an older
6662                        // version of the one on the data partition, but which
6663                        // granted a new system permission that it didn't have
6664                        // before.  In this case we do want to allow the app to
6665                        // now get the new permission if the ancestral apk is
6666                        // privileged to get it.
6667                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6668                            for (int j=0;
6669                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6670                                if (perm.equals(
6671                                        sysPs.pkg.requestedPermissions.get(j))) {
6672                                    allowed = true;
6673                                    break;
6674                                }
6675                            }
6676                        }
6677                    }
6678                } else {
6679                    allowed = isPrivilegedApp(pkg);
6680                }
6681            }
6682        }
6683        if (!allowed && (bp.protectionLevel
6684                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6685            // For development permissions, a development permission
6686            // is granted only if it was already granted.
6687            allowed = origPermissions.contains(perm);
6688        }
6689        return allowed;
6690    }
6691
6692    final class ActivityIntentResolver
6693            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6694        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6695                boolean defaultOnly, int userId) {
6696            if (!sUserManager.exists(userId)) return null;
6697            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6698            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6699        }
6700
6701        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6702                int userId) {
6703            if (!sUserManager.exists(userId)) return null;
6704            mFlags = flags;
6705            return super.queryIntent(intent, resolvedType,
6706                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6707        }
6708
6709        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6710                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6711            if (!sUserManager.exists(userId)) return null;
6712            if (packageActivities == null) {
6713                return null;
6714            }
6715            mFlags = flags;
6716            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6717            final int N = packageActivities.size();
6718            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6719                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6720
6721            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6722            for (int i = 0; i < N; ++i) {
6723                intentFilters = packageActivities.get(i).intents;
6724                if (intentFilters != null && intentFilters.size() > 0) {
6725                    PackageParser.ActivityIntentInfo[] array =
6726                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6727                    intentFilters.toArray(array);
6728                    listCut.add(array);
6729                }
6730            }
6731            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6732        }
6733
6734        public final void addActivity(PackageParser.Activity a, String type) {
6735            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6736            mActivities.put(a.getComponentName(), a);
6737            if (DEBUG_SHOW_INFO)
6738                Log.v(
6739                TAG, "  " + type + " " +
6740                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6741            if (DEBUG_SHOW_INFO)
6742                Log.v(TAG, "    Class=" + a.info.name);
6743            final int NI = a.intents.size();
6744            for (int j=0; j<NI; j++) {
6745                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6746                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6747                    intent.setPriority(0);
6748                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6749                            + a.className + " with priority > 0, forcing to 0");
6750                }
6751                if (DEBUG_SHOW_INFO) {
6752                    Log.v(TAG, "    IntentFilter:");
6753                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6754                }
6755                if (!intent.debugCheck()) {
6756                    Log.w(TAG, "==> For Activity " + a.info.name);
6757                }
6758                addFilter(intent);
6759            }
6760        }
6761
6762        public final void removeActivity(PackageParser.Activity a, String type) {
6763            mActivities.remove(a.getComponentName());
6764            if (DEBUG_SHOW_INFO) {
6765                Log.v(TAG, "  " + type + " "
6766                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6767                                : a.info.name) + ":");
6768                Log.v(TAG, "    Class=" + a.info.name);
6769            }
6770            final int NI = a.intents.size();
6771            for (int j=0; j<NI; j++) {
6772                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6773                if (DEBUG_SHOW_INFO) {
6774                    Log.v(TAG, "    IntentFilter:");
6775                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6776                }
6777                removeFilter(intent);
6778            }
6779        }
6780
6781        @Override
6782        protected boolean allowFilterResult(
6783                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6784            ActivityInfo filterAi = filter.activity.info;
6785            for (int i=dest.size()-1; i>=0; i--) {
6786                ActivityInfo destAi = dest.get(i).activityInfo;
6787                if (destAi.name == filterAi.name
6788                        && destAi.packageName == filterAi.packageName) {
6789                    return false;
6790                }
6791            }
6792            return true;
6793        }
6794
6795        @Override
6796        protected ActivityIntentInfo[] newArray(int size) {
6797            return new ActivityIntentInfo[size];
6798        }
6799
6800        @Override
6801        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6802            if (!sUserManager.exists(userId)) return true;
6803            PackageParser.Package p = filter.activity.owner;
6804            if (p != null) {
6805                PackageSetting ps = (PackageSetting)p.mExtras;
6806                if (ps != null) {
6807                    // System apps are never considered stopped for purposes of
6808                    // filtering, because there may be no way for the user to
6809                    // actually re-launch them.
6810                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6811                            && ps.getStopped(userId);
6812                }
6813            }
6814            return false;
6815        }
6816
6817        @Override
6818        protected boolean isPackageForFilter(String packageName,
6819                PackageParser.ActivityIntentInfo info) {
6820            return packageName.equals(info.activity.owner.packageName);
6821        }
6822
6823        @Override
6824        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6825                int match, int userId) {
6826            if (!sUserManager.exists(userId)) return null;
6827            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6828                return null;
6829            }
6830            final PackageParser.Activity activity = info.activity;
6831            if (mSafeMode && (activity.info.applicationInfo.flags
6832                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6833                return null;
6834            }
6835            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6836            if (ps == null) {
6837                return null;
6838            }
6839            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6840                    ps.readUserState(userId), userId);
6841            if (ai == null) {
6842                return null;
6843            }
6844            final ResolveInfo res = new ResolveInfo();
6845            res.activityInfo = ai;
6846            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6847                res.filter = info;
6848            }
6849            res.priority = info.getPriority();
6850            res.preferredOrder = activity.owner.mPreferredOrder;
6851            //System.out.println("Result: " + res.activityInfo.className +
6852            //                   " = " + res.priority);
6853            res.match = match;
6854            res.isDefault = info.hasDefault;
6855            res.labelRes = info.labelRes;
6856            res.nonLocalizedLabel = info.nonLocalizedLabel;
6857            if (userNeedsBadging(userId)) {
6858                res.noResourceId = true;
6859            } else {
6860                res.icon = info.icon;
6861            }
6862            res.system = isSystemApp(res.activityInfo.applicationInfo);
6863            return res;
6864        }
6865
6866        @Override
6867        protected void sortResults(List<ResolveInfo> results) {
6868            Collections.sort(results, mResolvePrioritySorter);
6869        }
6870
6871        @Override
6872        protected void dumpFilter(PrintWriter out, String prefix,
6873                PackageParser.ActivityIntentInfo filter) {
6874            out.print(prefix); out.print(
6875                    Integer.toHexString(System.identityHashCode(filter.activity)));
6876                    out.print(' ');
6877                    filter.activity.printComponentShortName(out);
6878                    out.print(" filter ");
6879                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6880        }
6881
6882//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6883//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6884//            final List<ResolveInfo> retList = Lists.newArrayList();
6885//            while (i.hasNext()) {
6886//                final ResolveInfo resolveInfo = i.next();
6887//                if (isEnabledLP(resolveInfo.activityInfo)) {
6888//                    retList.add(resolveInfo);
6889//                }
6890//            }
6891//            return retList;
6892//        }
6893
6894        // Keys are String (activity class name), values are Activity.
6895        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6896                = new HashMap<ComponentName, PackageParser.Activity>();
6897        private int mFlags;
6898    }
6899
6900    private final class ServiceIntentResolver
6901            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6902        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6903                boolean defaultOnly, int userId) {
6904            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6905            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6906        }
6907
6908        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6909                int userId) {
6910            if (!sUserManager.exists(userId)) return null;
6911            mFlags = flags;
6912            return super.queryIntent(intent, resolvedType,
6913                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6914        }
6915
6916        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6917                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6918            if (!sUserManager.exists(userId)) return null;
6919            if (packageServices == null) {
6920                return null;
6921            }
6922            mFlags = flags;
6923            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6924            final int N = packageServices.size();
6925            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6926                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6927
6928            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6929            for (int i = 0; i < N; ++i) {
6930                intentFilters = packageServices.get(i).intents;
6931                if (intentFilters != null && intentFilters.size() > 0) {
6932                    PackageParser.ServiceIntentInfo[] array =
6933                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6934                    intentFilters.toArray(array);
6935                    listCut.add(array);
6936                }
6937            }
6938            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6939        }
6940
6941        public final void addService(PackageParser.Service s) {
6942            mServices.put(s.getComponentName(), s);
6943            if (DEBUG_SHOW_INFO) {
6944                Log.v(TAG, "  "
6945                        + (s.info.nonLocalizedLabel != null
6946                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6947                Log.v(TAG, "    Class=" + s.info.name);
6948            }
6949            final int NI = s.intents.size();
6950            int j;
6951            for (j=0; j<NI; j++) {
6952                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6953                if (DEBUG_SHOW_INFO) {
6954                    Log.v(TAG, "    IntentFilter:");
6955                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6956                }
6957                if (!intent.debugCheck()) {
6958                    Log.w(TAG, "==> For Service " + s.info.name);
6959                }
6960                addFilter(intent);
6961            }
6962        }
6963
6964        public final void removeService(PackageParser.Service s) {
6965            mServices.remove(s.getComponentName());
6966            if (DEBUG_SHOW_INFO) {
6967                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6968                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6969                Log.v(TAG, "    Class=" + s.info.name);
6970            }
6971            final int NI = s.intents.size();
6972            int j;
6973            for (j=0; j<NI; j++) {
6974                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6975                if (DEBUG_SHOW_INFO) {
6976                    Log.v(TAG, "    IntentFilter:");
6977                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6978                }
6979                removeFilter(intent);
6980            }
6981        }
6982
6983        @Override
6984        protected boolean allowFilterResult(
6985                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6986            ServiceInfo filterSi = filter.service.info;
6987            for (int i=dest.size()-1; i>=0; i--) {
6988                ServiceInfo destAi = dest.get(i).serviceInfo;
6989                if (destAi.name == filterSi.name
6990                        && destAi.packageName == filterSi.packageName) {
6991                    return false;
6992                }
6993            }
6994            return true;
6995        }
6996
6997        @Override
6998        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6999            return new PackageParser.ServiceIntentInfo[size];
7000        }
7001
7002        @Override
7003        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7004            if (!sUserManager.exists(userId)) return true;
7005            PackageParser.Package p = filter.service.owner;
7006            if (p != null) {
7007                PackageSetting ps = (PackageSetting)p.mExtras;
7008                if (ps != null) {
7009                    // System apps are never considered stopped for purposes of
7010                    // filtering, because there may be no way for the user to
7011                    // actually re-launch them.
7012                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7013                            && ps.getStopped(userId);
7014                }
7015            }
7016            return false;
7017        }
7018
7019        @Override
7020        protected boolean isPackageForFilter(String packageName,
7021                PackageParser.ServiceIntentInfo info) {
7022            return packageName.equals(info.service.owner.packageName);
7023        }
7024
7025        @Override
7026        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7027                int match, int userId) {
7028            if (!sUserManager.exists(userId)) return null;
7029            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7030            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7031                return null;
7032            }
7033            final PackageParser.Service service = info.service;
7034            if (mSafeMode && (service.info.applicationInfo.flags
7035                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7036                return null;
7037            }
7038            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7039            if (ps == null) {
7040                return null;
7041            }
7042            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7043                    ps.readUserState(userId), userId);
7044            if (si == null) {
7045                return null;
7046            }
7047            final ResolveInfo res = new ResolveInfo();
7048            res.serviceInfo = si;
7049            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7050                res.filter = filter;
7051            }
7052            res.priority = info.getPriority();
7053            res.preferredOrder = service.owner.mPreferredOrder;
7054            //System.out.println("Result: " + res.activityInfo.className +
7055            //                   " = " + res.priority);
7056            res.match = match;
7057            res.isDefault = info.hasDefault;
7058            res.labelRes = info.labelRes;
7059            res.nonLocalizedLabel = info.nonLocalizedLabel;
7060            res.icon = info.icon;
7061            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7062            return res;
7063        }
7064
7065        @Override
7066        protected void sortResults(List<ResolveInfo> results) {
7067            Collections.sort(results, mResolvePrioritySorter);
7068        }
7069
7070        @Override
7071        protected void dumpFilter(PrintWriter out, String prefix,
7072                PackageParser.ServiceIntentInfo filter) {
7073            out.print(prefix); out.print(
7074                    Integer.toHexString(System.identityHashCode(filter.service)));
7075                    out.print(' ');
7076                    filter.service.printComponentShortName(out);
7077                    out.print(" filter ");
7078                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7079        }
7080
7081//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7082//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7083//            final List<ResolveInfo> retList = Lists.newArrayList();
7084//            while (i.hasNext()) {
7085//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7086//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7087//                    retList.add(resolveInfo);
7088//                }
7089//            }
7090//            return retList;
7091//        }
7092
7093        // Keys are String (activity class name), values are Activity.
7094        private final HashMap<ComponentName, PackageParser.Service> mServices
7095                = new HashMap<ComponentName, PackageParser.Service>();
7096        private int mFlags;
7097    };
7098
7099    private final class ProviderIntentResolver
7100            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7102                boolean defaultOnly, int userId) {
7103            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7104            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7105        }
7106
7107        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7108                int userId) {
7109            if (!sUserManager.exists(userId))
7110                return null;
7111            mFlags = flags;
7112            return super.queryIntent(intent, resolvedType,
7113                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7114        }
7115
7116        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7117                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7118            if (!sUserManager.exists(userId))
7119                return null;
7120            if (packageProviders == null) {
7121                return null;
7122            }
7123            mFlags = flags;
7124            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7125            final int N = packageProviders.size();
7126            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7127                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7128
7129            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7130            for (int i = 0; i < N; ++i) {
7131                intentFilters = packageProviders.get(i).intents;
7132                if (intentFilters != null && intentFilters.size() > 0) {
7133                    PackageParser.ProviderIntentInfo[] array =
7134                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7135                    intentFilters.toArray(array);
7136                    listCut.add(array);
7137                }
7138            }
7139            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7140        }
7141
7142        public final void addProvider(PackageParser.Provider p) {
7143            if (mProviders.containsKey(p.getComponentName())) {
7144                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7145                return;
7146            }
7147
7148            mProviders.put(p.getComponentName(), p);
7149            if (DEBUG_SHOW_INFO) {
7150                Log.v(TAG, "  "
7151                        + (p.info.nonLocalizedLabel != null
7152                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7153                Log.v(TAG, "    Class=" + p.info.name);
7154            }
7155            final int NI = p.intents.size();
7156            int j;
7157            for (j = 0; j < NI; j++) {
7158                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7159                if (DEBUG_SHOW_INFO) {
7160                    Log.v(TAG, "    IntentFilter:");
7161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7162                }
7163                if (!intent.debugCheck()) {
7164                    Log.w(TAG, "==> For Provider " + p.info.name);
7165                }
7166                addFilter(intent);
7167            }
7168        }
7169
7170        public final void removeProvider(PackageParser.Provider p) {
7171            mProviders.remove(p.getComponentName());
7172            if (DEBUG_SHOW_INFO) {
7173                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7174                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7175                Log.v(TAG, "    Class=" + p.info.name);
7176            }
7177            final int NI = p.intents.size();
7178            int j;
7179            for (j = 0; j < NI; j++) {
7180                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7181                if (DEBUG_SHOW_INFO) {
7182                    Log.v(TAG, "    IntentFilter:");
7183                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7184                }
7185                removeFilter(intent);
7186            }
7187        }
7188
7189        @Override
7190        protected boolean allowFilterResult(
7191                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7192            ProviderInfo filterPi = filter.provider.info;
7193            for (int i = dest.size() - 1; i >= 0; i--) {
7194                ProviderInfo destPi = dest.get(i).providerInfo;
7195                if (destPi.name == filterPi.name
7196                        && destPi.packageName == filterPi.packageName) {
7197                    return false;
7198                }
7199            }
7200            return true;
7201        }
7202
7203        @Override
7204        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7205            return new PackageParser.ProviderIntentInfo[size];
7206        }
7207
7208        @Override
7209        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7210            if (!sUserManager.exists(userId))
7211                return true;
7212            PackageParser.Package p = filter.provider.owner;
7213            if (p != null) {
7214                PackageSetting ps = (PackageSetting) p.mExtras;
7215                if (ps != null) {
7216                    // System apps are never considered stopped for purposes of
7217                    // filtering, because there may be no way for the user to
7218                    // actually re-launch them.
7219                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7220                            && ps.getStopped(userId);
7221                }
7222            }
7223            return false;
7224        }
7225
7226        @Override
7227        protected boolean isPackageForFilter(String packageName,
7228                PackageParser.ProviderIntentInfo info) {
7229            return packageName.equals(info.provider.owner.packageName);
7230        }
7231
7232        @Override
7233        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7234                int match, int userId) {
7235            if (!sUserManager.exists(userId))
7236                return null;
7237            final PackageParser.ProviderIntentInfo info = filter;
7238            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7239                return null;
7240            }
7241            final PackageParser.Provider provider = info.provider;
7242            if (mSafeMode && (provider.info.applicationInfo.flags
7243                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7244                return null;
7245            }
7246            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7247            if (ps == null) {
7248                return null;
7249            }
7250            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7251                    ps.readUserState(userId), userId);
7252            if (pi == null) {
7253                return null;
7254            }
7255            final ResolveInfo res = new ResolveInfo();
7256            res.providerInfo = pi;
7257            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7258                res.filter = filter;
7259            }
7260            res.priority = info.getPriority();
7261            res.preferredOrder = provider.owner.mPreferredOrder;
7262            res.match = match;
7263            res.isDefault = info.hasDefault;
7264            res.labelRes = info.labelRes;
7265            res.nonLocalizedLabel = info.nonLocalizedLabel;
7266            res.icon = info.icon;
7267            res.system = isSystemApp(res.providerInfo.applicationInfo);
7268            return res;
7269        }
7270
7271        @Override
7272        protected void sortResults(List<ResolveInfo> results) {
7273            Collections.sort(results, mResolvePrioritySorter);
7274        }
7275
7276        @Override
7277        protected void dumpFilter(PrintWriter out, String prefix,
7278                PackageParser.ProviderIntentInfo filter) {
7279            out.print(prefix);
7280            out.print(
7281                    Integer.toHexString(System.identityHashCode(filter.provider)));
7282            out.print(' ');
7283            filter.provider.printComponentShortName(out);
7284            out.print(" filter ");
7285            out.println(Integer.toHexString(System.identityHashCode(filter)));
7286        }
7287
7288        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7289                = new HashMap<ComponentName, PackageParser.Provider>();
7290        private int mFlags;
7291    };
7292
7293    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7294            new Comparator<ResolveInfo>() {
7295        public int compare(ResolveInfo r1, ResolveInfo r2) {
7296            int v1 = r1.priority;
7297            int v2 = r2.priority;
7298            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7299            if (v1 != v2) {
7300                return (v1 > v2) ? -1 : 1;
7301            }
7302            v1 = r1.preferredOrder;
7303            v2 = r2.preferredOrder;
7304            if (v1 != v2) {
7305                return (v1 > v2) ? -1 : 1;
7306            }
7307            if (r1.isDefault != r2.isDefault) {
7308                return r1.isDefault ? -1 : 1;
7309            }
7310            v1 = r1.match;
7311            v2 = r2.match;
7312            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7313            if (v1 != v2) {
7314                return (v1 > v2) ? -1 : 1;
7315            }
7316            if (r1.system != r2.system) {
7317                return r1.system ? -1 : 1;
7318            }
7319            return 0;
7320        }
7321    };
7322
7323    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7324            new Comparator<ProviderInfo>() {
7325        public int compare(ProviderInfo p1, ProviderInfo p2) {
7326            final int v1 = p1.initOrder;
7327            final int v2 = p2.initOrder;
7328            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7329        }
7330    };
7331
7332    static final void sendPackageBroadcast(String action, String pkg,
7333            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7334            int[] userIds) {
7335        IActivityManager am = ActivityManagerNative.getDefault();
7336        if (am != null) {
7337            try {
7338                if (userIds == null) {
7339                    userIds = am.getRunningUserIds();
7340                }
7341                for (int id : userIds) {
7342                    final Intent intent = new Intent(action,
7343                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7344                    if (extras != null) {
7345                        intent.putExtras(extras);
7346                    }
7347                    if (targetPkg != null) {
7348                        intent.setPackage(targetPkg);
7349                    }
7350                    // Modify the UID when posting to other users
7351                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7352                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7353                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7354                        intent.putExtra(Intent.EXTRA_UID, uid);
7355                    }
7356                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7357                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7358                    if (DEBUG_BROADCASTS) {
7359                        RuntimeException here = new RuntimeException("here");
7360                        here.fillInStackTrace();
7361                        Slog.d(TAG, "Sending to user " + id + ": "
7362                                + intent.toShortString(false, true, false, false)
7363                                + " " + intent.getExtras(), here);
7364                    }
7365                    am.broadcastIntent(null, intent, null, finishedReceiver,
7366                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7367                            finishedReceiver != null, false, id);
7368                }
7369            } catch (RemoteException ex) {
7370            }
7371        }
7372    }
7373
7374    /**
7375     * Check if the external storage media is available. This is true if there
7376     * is a mounted external storage medium or if the external storage is
7377     * emulated.
7378     */
7379    private boolean isExternalMediaAvailable() {
7380        return mMediaMounted || Environment.isExternalStorageEmulated();
7381    }
7382
7383    @Override
7384    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7385        // writer
7386        synchronized (mPackages) {
7387            if (!isExternalMediaAvailable()) {
7388                // If the external storage is no longer mounted at this point,
7389                // the caller may not have been able to delete all of this
7390                // packages files and can not delete any more.  Bail.
7391                return null;
7392            }
7393            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7394            if (lastPackage != null) {
7395                pkgs.remove(lastPackage);
7396            }
7397            if (pkgs.size() > 0) {
7398                return pkgs.get(0);
7399            }
7400        }
7401        return null;
7402    }
7403
7404    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7405        if (false) {
7406            RuntimeException here = new RuntimeException("here");
7407            here.fillInStackTrace();
7408            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7409                    + " andCode=" + andCode, here);
7410        }
7411        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7412                userId, andCode ? 1 : 0, packageName));
7413    }
7414
7415    void startCleaningPackages() {
7416        // reader
7417        synchronized (mPackages) {
7418            if (!isExternalMediaAvailable()) {
7419                return;
7420            }
7421            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7422                return;
7423            }
7424        }
7425        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7426        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7427        IActivityManager am = ActivityManagerNative.getDefault();
7428        if (am != null) {
7429            try {
7430                am.startService(null, intent, null, UserHandle.USER_OWNER);
7431            } catch (RemoteException e) {
7432            }
7433        }
7434    }
7435
7436    private final class AppDirObserver extends FileObserver {
7437        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7438            super(path, mask);
7439            mRootDir = path;
7440            mIsRom = isrom;
7441            mIsPrivileged = isPrivileged;
7442        }
7443
7444        public void onEvent(int event, String path) {
7445            String removedPackage = null;
7446            int removedAppId = -1;
7447            int[] removedUsers = null;
7448            String addedPackage = null;
7449            int addedAppId = -1;
7450            int[] addedUsers = null;
7451
7452            // TODO post a message to the handler to obtain serial ordering
7453            synchronized (mInstallLock) {
7454                String fullPathStr = null;
7455                File fullPath = null;
7456                if (path != null) {
7457                    fullPath = new File(mRootDir, path);
7458                    fullPathStr = fullPath.getPath();
7459                }
7460
7461                if (DEBUG_APP_DIR_OBSERVER)
7462                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7463
7464                if (!isPackageFilename(path)) {
7465                    if (DEBUG_APP_DIR_OBSERVER)
7466                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7467                    return;
7468                }
7469
7470                // Ignore packages that are being installed or
7471                // have just been installed.
7472                if (ignoreCodePath(fullPathStr)) {
7473                    return;
7474                }
7475                PackageParser.Package p = null;
7476                PackageSetting ps = null;
7477                // reader
7478                synchronized (mPackages) {
7479                    p = mAppDirs.get(fullPathStr);
7480                    if (p != null) {
7481                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7482                        if (ps != null) {
7483                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7484                        } else {
7485                            removedUsers = sUserManager.getUserIds();
7486                        }
7487                    }
7488                    addedUsers = sUserManager.getUserIds();
7489                }
7490                if ((event&REMOVE_EVENTS) != 0) {
7491                    if (ps != null) {
7492                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7493                        removePackageLI(ps, true);
7494                        removedPackage = ps.name;
7495                        removedAppId = ps.appId;
7496                    }
7497                }
7498
7499                if ((event&ADD_EVENTS) != 0) {
7500                    if (p == null) {
7501                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7502                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7503                        if (mIsRom) {
7504                            flags |= PackageParser.PARSE_IS_SYSTEM
7505                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7506                            if (mIsPrivileged) {
7507                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7508                            }
7509                        }
7510                        p = scanPackageLI(fullPath, flags,
7511                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7512                                System.currentTimeMillis(), UserHandle.ALL, null);
7513                        if (p != null) {
7514                            /*
7515                             * TODO this seems dangerous as the package may have
7516                             * changed since we last acquired the mPackages
7517                             * lock.
7518                             */
7519                            // writer
7520                            synchronized (mPackages) {
7521                                updatePermissionsLPw(p.packageName, p,
7522                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7523                            }
7524                            addedPackage = p.applicationInfo.packageName;
7525                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7526                        }
7527                    }
7528                }
7529
7530                // reader
7531                synchronized (mPackages) {
7532                    mSettings.writeLPr();
7533                }
7534            }
7535
7536            if (removedPackage != null) {
7537                Bundle extras = new Bundle(1);
7538                extras.putInt(Intent.EXTRA_UID, removedAppId);
7539                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7540                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7541                        extras, null, null, removedUsers);
7542            }
7543            if (addedPackage != null) {
7544                Bundle extras = new Bundle(1);
7545                extras.putInt(Intent.EXTRA_UID, addedAppId);
7546                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7547                        extras, null, null, addedUsers);
7548            }
7549        }
7550
7551        private final String mRootDir;
7552        private final boolean mIsRom;
7553        private final boolean mIsPrivileged;
7554    }
7555
7556    /*
7557     * The old-style observer methods all just trampoline to the newer signature with
7558     * expanded install observer API.  The older API continues to work but does not
7559     * supply the additional details of the Observer2 API.
7560     */
7561
7562    /* Called when a downloaded package installation has been confirmed by the user */
7563    public void installPackage(
7564            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7565        installPackageEtc(packageURI, observer, null, flags, null);
7566    }
7567
7568    /* Called when a downloaded package installation has been confirmed by the user */
7569    @Override
7570    public void installPackage(
7571            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7572            final String installerPackageName) {
7573        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7574                installerPackageName, null, null, null);
7575    }
7576
7577    @Override
7578    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7579            int flags, String installerPackageName, Uri verificationURI,
7580            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7581        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7582                VerificationParams.NO_UID, manifestDigest);
7583        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7584                installerPackageName, verificationParams, encryptionParams);
7585    }
7586
7587    @Override
7588    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7589            IPackageInstallObserver observer, int flags, String installerPackageName,
7590            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7591        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7592                installerPackageName, verificationParams, encryptionParams);
7593    }
7594
7595    /*
7596     * And here are the "live" versions that take both observer arguments
7597     */
7598    public void installPackageEtc(
7599            final Uri packageURI, final IPackageInstallObserver observer,
7600            IPackageInstallObserver2 observer2, final int flags) {
7601        installPackageEtc(packageURI, observer, observer2, flags, null);
7602    }
7603
7604    public void installPackageEtc(
7605            final Uri packageURI, final IPackageInstallObserver observer,
7606            final IPackageInstallObserver2 observer2, final int flags,
7607            final String installerPackageName) {
7608        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7609                installerPackageName, null, null, null);
7610    }
7611
7612    @Override
7613    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7614            IPackageInstallObserver2 observer2,
7615            int flags, String installerPackageName, Uri verificationURI,
7616            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7617        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7618                VerificationParams.NO_UID, manifestDigest);
7619        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7620                installerPackageName, verificationParams, encryptionParams);
7621    }
7622
7623    /*
7624     * All of the installPackage...*() methods redirect to this one for the master implementation
7625     */
7626    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7627            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7628            int flags, String installerPackageName,
7629            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7630        if (observer == null && observer2 == null) {
7631            throw new IllegalArgumentException("No install observer supplied");
7632        }
7633        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7634                flags, installerPackageName, verificationParams, encryptionParams, null);
7635    }
7636
7637    @Override
7638    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7639            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7640            int flags, String installerPackageName,
7641            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7642            String packageAbiOverride) {
7643        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7644                null);
7645
7646        final int uid = Binder.getCallingUid();
7647        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7648            try {
7649                if (observer != null) {
7650                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7651                }
7652                if (observer2 != null) {
7653                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7654                }
7655            } catch (RemoteException re) {
7656            }
7657            return;
7658        }
7659
7660        UserHandle user;
7661        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7662            user = UserHandle.ALL;
7663        } else {
7664            user = new UserHandle(UserHandle.getUserId(uid));
7665        }
7666
7667        final int filteredFlags;
7668
7669        if (uid == Process.SHELL_UID || uid == 0) {
7670            if (DEBUG_INSTALL) {
7671                Slog.v(TAG, "Install from ADB");
7672            }
7673            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7674        } else {
7675            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7676        }
7677
7678        verificationParams.setInstallerUid(uid);
7679
7680        final Message msg = mHandler.obtainMessage(INIT_COPY);
7681        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7682                installerPackageName, verificationParams, encryptionParams, user,
7683                packageAbiOverride);
7684        mHandler.sendMessage(msg);
7685    }
7686
7687    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7688        Bundle extras = new Bundle(1);
7689        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7690
7691        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7692                packageName, extras, null, null, new int[] {userId});
7693        try {
7694            IActivityManager am = ActivityManagerNative.getDefault();
7695            final boolean isSystem =
7696                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7697            if (isSystem && am.isUserRunning(userId, false)) {
7698                // The just-installed/enabled app is bundled on the system, so presumed
7699                // to be able to run automatically without needing an explicit launch.
7700                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7701                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7702                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7703                        .setPackage(packageName);
7704                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7705                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7706            }
7707        } catch (RemoteException e) {
7708            // shouldn't happen
7709            Slog.w(TAG, "Unable to bootstrap installed package", e);
7710        }
7711    }
7712
7713    @Override
7714    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7715            int userId) {
7716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7717        PackageSetting pkgSetting;
7718        final int uid = Binder.getCallingUid();
7719        if (UserHandle.getUserId(uid) != userId) {
7720            mContext.enforceCallingOrSelfPermission(
7721                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7722                    "setApplicationBlockedSetting for user " + userId);
7723        }
7724
7725        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7726            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7727            return false;
7728        }
7729
7730        long callingId = Binder.clearCallingIdentity();
7731        try {
7732            boolean sendAdded = false;
7733            boolean sendRemoved = false;
7734            // writer
7735            synchronized (mPackages) {
7736                pkgSetting = mSettings.mPackages.get(packageName);
7737                if (pkgSetting == null) {
7738                    return false;
7739                }
7740                if (pkgSetting.getBlocked(userId) != blocked) {
7741                    pkgSetting.setBlocked(blocked, userId);
7742                    mSettings.writePackageRestrictionsLPr(userId);
7743                    if (blocked) {
7744                        sendRemoved = true;
7745                    } else {
7746                        sendAdded = true;
7747                    }
7748                }
7749            }
7750            if (sendAdded) {
7751                sendPackageAddedForUser(packageName, pkgSetting, userId);
7752                return true;
7753            }
7754            if (sendRemoved) {
7755                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7756                        "blocking pkg");
7757                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7758            }
7759        } finally {
7760            Binder.restoreCallingIdentity(callingId);
7761        }
7762        return false;
7763    }
7764
7765    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7766            int userId) {
7767        final PackageRemovedInfo info = new PackageRemovedInfo();
7768        info.removedPackage = packageName;
7769        info.removedUsers = new int[] {userId};
7770        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7771        info.sendBroadcast(false, false, false);
7772    }
7773
7774    /**
7775     * Returns true if application is not found or there was an error. Otherwise it returns
7776     * the blocked state of the package for the given user.
7777     */
7778    @Override
7779    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7781        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7782                "getApplicationBlocked for user " + userId);
7783        PackageSetting pkgSetting;
7784        long callingId = Binder.clearCallingIdentity();
7785        try {
7786            // writer
7787            synchronized (mPackages) {
7788                pkgSetting = mSettings.mPackages.get(packageName);
7789                if (pkgSetting == null) {
7790                    return true;
7791                }
7792                return pkgSetting.getBlocked(userId);
7793            }
7794        } finally {
7795            Binder.restoreCallingIdentity(callingId);
7796        }
7797    }
7798
7799    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7800            int flags) {
7801        // TODO: install stage!
7802        try {
7803            observer.packageInstalled(basePackageName, null,
7804                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7805        } catch (RemoteException ignored) {
7806        }
7807    }
7808
7809    /**
7810     * @hide
7811     */
7812    @Override
7813    public int installExistingPackageAsUser(String packageName, int userId) {
7814        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7815                null);
7816        PackageSetting pkgSetting;
7817        final int uid = Binder.getCallingUid();
7818        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7819        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7820            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7821        }
7822
7823        long callingId = Binder.clearCallingIdentity();
7824        try {
7825            boolean sendAdded = false;
7826            Bundle extras = new Bundle(1);
7827
7828            // writer
7829            synchronized (mPackages) {
7830                pkgSetting = mSettings.mPackages.get(packageName);
7831                if (pkgSetting == null) {
7832                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7833                }
7834                if (!pkgSetting.getInstalled(userId)) {
7835                    pkgSetting.setInstalled(true, userId);
7836                    pkgSetting.setBlocked(false, userId);
7837                    mSettings.writePackageRestrictionsLPr(userId);
7838                    sendAdded = true;
7839                }
7840            }
7841
7842            if (sendAdded) {
7843                sendPackageAddedForUser(packageName, pkgSetting, userId);
7844            }
7845        } finally {
7846            Binder.restoreCallingIdentity(callingId);
7847        }
7848
7849        return PackageManager.INSTALL_SUCCEEDED;
7850    }
7851
7852    boolean isUserRestricted(int userId, String restrictionKey) {
7853        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7854        if (restrictions.getBoolean(restrictionKey, false)) {
7855            Log.w(TAG, "User is restricted: " + restrictionKey);
7856            return true;
7857        }
7858        return false;
7859    }
7860
7861    @Override
7862    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7863        mContext.enforceCallingOrSelfPermission(
7864                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7865                "Only package verification agents can verify applications");
7866
7867        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7868        final PackageVerificationResponse response = new PackageVerificationResponse(
7869                verificationCode, Binder.getCallingUid());
7870        msg.arg1 = id;
7871        msg.obj = response;
7872        mHandler.sendMessage(msg);
7873    }
7874
7875    @Override
7876    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7877            long millisecondsToDelay) {
7878        mContext.enforceCallingOrSelfPermission(
7879                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7880                "Only package verification agents can extend verification timeouts");
7881
7882        final PackageVerificationState state = mPendingVerification.get(id);
7883        final PackageVerificationResponse response = new PackageVerificationResponse(
7884                verificationCodeAtTimeout, Binder.getCallingUid());
7885
7886        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7887            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7888        }
7889        if (millisecondsToDelay < 0) {
7890            millisecondsToDelay = 0;
7891        }
7892        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7893                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7894            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7895        }
7896
7897        if ((state != null) && !state.timeoutExtended()) {
7898            state.extendTimeout();
7899
7900            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7901            msg.arg1 = id;
7902            msg.obj = response;
7903            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7904        }
7905    }
7906
7907    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7908            int verificationCode, UserHandle user) {
7909        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7910        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7911        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7912        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7913        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7914
7915        mContext.sendBroadcastAsUser(intent, user,
7916                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7917    }
7918
7919    private ComponentName matchComponentForVerifier(String packageName,
7920            List<ResolveInfo> receivers) {
7921        ActivityInfo targetReceiver = null;
7922
7923        final int NR = receivers.size();
7924        for (int i = 0; i < NR; i++) {
7925            final ResolveInfo info = receivers.get(i);
7926            if (info.activityInfo == null) {
7927                continue;
7928            }
7929
7930            if (packageName.equals(info.activityInfo.packageName)) {
7931                targetReceiver = info.activityInfo;
7932                break;
7933            }
7934        }
7935
7936        if (targetReceiver == null) {
7937            return null;
7938        }
7939
7940        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7941    }
7942
7943    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7944            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7945        if (pkgInfo.verifiers.length == 0) {
7946            return null;
7947        }
7948
7949        final int N = pkgInfo.verifiers.length;
7950        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7951        for (int i = 0; i < N; i++) {
7952            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7953
7954            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7955                    receivers);
7956            if (comp == null) {
7957                continue;
7958            }
7959
7960            final int verifierUid = getUidForVerifier(verifierInfo);
7961            if (verifierUid == -1) {
7962                continue;
7963            }
7964
7965            if (DEBUG_VERIFY) {
7966                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7967                        + " with the correct signature");
7968            }
7969            sufficientVerifiers.add(comp);
7970            verificationState.addSufficientVerifier(verifierUid);
7971        }
7972
7973        return sufficientVerifiers;
7974    }
7975
7976    private int getUidForVerifier(VerifierInfo verifierInfo) {
7977        synchronized (mPackages) {
7978            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7979            if (pkg == null) {
7980                return -1;
7981            } else if (pkg.mSignatures.length != 1) {
7982                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7983                        + " has more than one signature; ignoring");
7984                return -1;
7985            }
7986
7987            /*
7988             * If the public key of the package's signature does not match
7989             * our expected public key, then this is a different package and
7990             * we should skip.
7991             */
7992
7993            final byte[] expectedPublicKey;
7994            try {
7995                final Signature verifierSig = pkg.mSignatures[0];
7996                final PublicKey publicKey = verifierSig.getPublicKey();
7997                expectedPublicKey = publicKey.getEncoded();
7998            } catch (CertificateException e) {
7999                return -1;
8000            }
8001
8002            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8003
8004            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8005                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8006                        + " does not have the expected public key; ignoring");
8007                return -1;
8008            }
8009
8010            return pkg.applicationInfo.uid;
8011        }
8012    }
8013
8014    @Override
8015    public void finishPackageInstall(int token) {
8016        enforceSystemOrRoot("Only the system is allowed to finish installs");
8017
8018        if (DEBUG_INSTALL) {
8019            Slog.v(TAG, "BM finishing package install for " + token);
8020        }
8021
8022        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8023        mHandler.sendMessage(msg);
8024    }
8025
8026    /**
8027     * Get the verification agent timeout.
8028     *
8029     * @return verification timeout in milliseconds
8030     */
8031    private long getVerificationTimeout() {
8032        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8033                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8034                DEFAULT_VERIFICATION_TIMEOUT);
8035    }
8036
8037    /**
8038     * Get the default verification agent response code.
8039     *
8040     * @return default verification response code
8041     */
8042    private int getDefaultVerificationResponse() {
8043        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8044                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8045                DEFAULT_VERIFICATION_RESPONSE);
8046    }
8047
8048    /**
8049     * Check whether or not package verification has been enabled.
8050     *
8051     * @return true if verification should be performed
8052     */
8053    private boolean isVerificationEnabled(int flags) {
8054        if (!DEFAULT_VERIFY_ENABLE) {
8055            return false;
8056        }
8057
8058        // Check if installing from ADB
8059        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8060            // Do not run verification in a test harness environment
8061            if (ActivityManager.isRunningInTestHarness()) {
8062                return false;
8063            }
8064            // Check if the developer does not want package verification for ADB installs
8065            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8066                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8067                return false;
8068            }
8069        }
8070
8071        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8072                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8073    }
8074
8075    /**
8076     * Get the "allow unknown sources" setting.
8077     *
8078     * @return the current "allow unknown sources" setting
8079     */
8080    private int getUnknownSourcesSettings() {
8081        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8082                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8083                -1);
8084    }
8085
8086    @Override
8087    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8088        final int uid = Binder.getCallingUid();
8089        // writer
8090        synchronized (mPackages) {
8091            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8092            if (targetPackageSetting == null) {
8093                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8094            }
8095
8096            PackageSetting installerPackageSetting;
8097            if (installerPackageName != null) {
8098                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8099                if (installerPackageSetting == null) {
8100                    throw new IllegalArgumentException("Unknown installer package: "
8101                            + installerPackageName);
8102                }
8103            } else {
8104                installerPackageSetting = null;
8105            }
8106
8107            Signature[] callerSignature;
8108            Object obj = mSettings.getUserIdLPr(uid);
8109            if (obj != null) {
8110                if (obj instanceof SharedUserSetting) {
8111                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8112                } else if (obj instanceof PackageSetting) {
8113                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8114                } else {
8115                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8116                }
8117            } else {
8118                throw new SecurityException("Unknown calling uid " + uid);
8119            }
8120
8121            // Verify: can't set installerPackageName to a package that is
8122            // not signed with the same cert as the caller.
8123            if (installerPackageSetting != null) {
8124                if (compareSignatures(callerSignature,
8125                        installerPackageSetting.signatures.mSignatures)
8126                        != PackageManager.SIGNATURE_MATCH) {
8127                    throw new SecurityException(
8128                            "Caller does not have same cert as new installer package "
8129                            + installerPackageName);
8130                }
8131            }
8132
8133            // Verify: if target already has an installer package, it must
8134            // be signed with the same cert as the caller.
8135            if (targetPackageSetting.installerPackageName != null) {
8136                PackageSetting setting = mSettings.mPackages.get(
8137                        targetPackageSetting.installerPackageName);
8138                // If the currently set package isn't valid, then it's always
8139                // okay to change it.
8140                if (setting != null) {
8141                    if (compareSignatures(callerSignature,
8142                            setting.signatures.mSignatures)
8143                            != PackageManager.SIGNATURE_MATCH) {
8144                        throw new SecurityException(
8145                                "Caller does not have same cert as old installer package "
8146                                + targetPackageSetting.installerPackageName);
8147                    }
8148                }
8149            }
8150
8151            // Okay!
8152            targetPackageSetting.installerPackageName = installerPackageName;
8153            scheduleWriteSettingsLocked();
8154        }
8155    }
8156
8157    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8158        // Queue up an async operation since the package installation may take a little while.
8159        mHandler.post(new Runnable() {
8160            public void run() {
8161                mHandler.removeCallbacks(this);
8162                 // Result object to be returned
8163                PackageInstalledInfo res = new PackageInstalledInfo();
8164                res.returnCode = currentStatus;
8165                res.uid = -1;
8166                res.pkg = null;
8167                res.removedInfo = new PackageRemovedInfo();
8168                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8169                    args.doPreInstall(res.returnCode);
8170                    synchronized (mInstallLock) {
8171                        installPackageLI(args, true, res);
8172                    }
8173                    args.doPostInstall(res.returnCode, res.uid);
8174                }
8175
8176                // A restore should be performed at this point if (a) the install
8177                // succeeded, (b) the operation is not an update, and (c) the new
8178                // package has a backupAgent defined.
8179                final boolean update = res.removedInfo.removedPackage != null;
8180                boolean doRestore = (!update
8181                        && res.pkg != null
8182                        && res.pkg.applicationInfo.backupAgentName != null);
8183
8184                // Set up the post-install work request bookkeeping.  This will be used
8185                // and cleaned up by the post-install event handling regardless of whether
8186                // there's a restore pass performed.  Token values are >= 1.
8187                int token;
8188                if (mNextInstallToken < 0) mNextInstallToken = 1;
8189                token = mNextInstallToken++;
8190
8191                PostInstallData data = new PostInstallData(args, res);
8192                mRunningInstalls.put(token, data);
8193                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8194
8195                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8196                    // Pass responsibility to the Backup Manager.  It will perform a
8197                    // restore if appropriate, then pass responsibility back to the
8198                    // Package Manager to run the post-install observer callbacks
8199                    // and broadcasts.
8200                    IBackupManager bm = IBackupManager.Stub.asInterface(
8201                            ServiceManager.getService(Context.BACKUP_SERVICE));
8202                    if (bm != null) {
8203                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8204                                + " to BM for possible restore");
8205                        try {
8206                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8207                        } catch (RemoteException e) {
8208                            // can't happen; the backup manager is local
8209                        } catch (Exception e) {
8210                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8211                            doRestore = false;
8212                        }
8213                    } else {
8214                        Slog.e(TAG, "Backup Manager not found!");
8215                        doRestore = false;
8216                    }
8217                }
8218
8219                if (!doRestore) {
8220                    // No restore possible, or the Backup Manager was mysteriously not
8221                    // available -- just fire the post-install work request directly.
8222                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8223                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8224                    mHandler.sendMessage(msg);
8225                }
8226            }
8227        });
8228    }
8229
8230    private abstract class HandlerParams {
8231        private static final int MAX_RETRIES = 4;
8232
8233        /**
8234         * Number of times startCopy() has been attempted and had a non-fatal
8235         * error.
8236         */
8237        private int mRetries = 0;
8238
8239        /** User handle for the user requesting the information or installation. */
8240        private final UserHandle mUser;
8241
8242        HandlerParams(UserHandle user) {
8243            mUser = user;
8244        }
8245
8246        UserHandle getUser() {
8247            return mUser;
8248        }
8249
8250        final boolean startCopy() {
8251            boolean res;
8252            try {
8253                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8254
8255                if (++mRetries > MAX_RETRIES) {
8256                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8257                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8258                    handleServiceError();
8259                    return false;
8260                } else {
8261                    handleStartCopy();
8262                    res = true;
8263                }
8264            } catch (RemoteException e) {
8265                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8266                mHandler.sendEmptyMessage(MCS_RECONNECT);
8267                res = false;
8268            }
8269            handleReturnCode();
8270            return res;
8271        }
8272
8273        final void serviceError() {
8274            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8275            handleServiceError();
8276            handleReturnCode();
8277        }
8278
8279        abstract void handleStartCopy() throws RemoteException;
8280        abstract void handleServiceError();
8281        abstract void handleReturnCode();
8282    }
8283
8284    class MeasureParams extends HandlerParams {
8285        private final PackageStats mStats;
8286        private boolean mSuccess;
8287
8288        private final IPackageStatsObserver mObserver;
8289
8290        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8291            super(new UserHandle(stats.userHandle));
8292            mObserver = observer;
8293            mStats = stats;
8294        }
8295
8296        @Override
8297        public String toString() {
8298            return "MeasureParams{"
8299                + Integer.toHexString(System.identityHashCode(this))
8300                + " " + mStats.packageName + "}";
8301        }
8302
8303        @Override
8304        void handleStartCopy() throws RemoteException {
8305            synchronized (mInstallLock) {
8306                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8307            }
8308
8309            if (mSuccess) {
8310                final boolean mounted;
8311                if (Environment.isExternalStorageEmulated()) {
8312                    mounted = true;
8313                } else {
8314                    final String status = Environment.getExternalStorageState();
8315                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8316                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8317                }
8318
8319                if (mounted) {
8320                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8321
8322                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8323                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8324
8325                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8326                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8327
8328                    // Always subtract cache size, since it's a subdirectory
8329                    mStats.externalDataSize -= mStats.externalCacheSize;
8330
8331                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8332                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8333
8334                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8335                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8336                }
8337            }
8338        }
8339
8340        @Override
8341        void handleReturnCode() {
8342            if (mObserver != null) {
8343                try {
8344                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8345                } catch (RemoteException e) {
8346                    Slog.i(TAG, "Observer no longer exists.");
8347                }
8348            }
8349        }
8350
8351        @Override
8352        void handleServiceError() {
8353            Slog.e(TAG, "Could not measure application " + mStats.packageName
8354                            + " external storage");
8355        }
8356    }
8357
8358    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8359            throws RemoteException {
8360        long result = 0;
8361        for (File path : paths) {
8362            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8363        }
8364        return result;
8365    }
8366
8367    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8368        for (File path : paths) {
8369            try {
8370                mcs.clearDirectory(path.getAbsolutePath());
8371            } catch (RemoteException e) {
8372            }
8373        }
8374    }
8375
8376    class InstallParams extends HandlerParams {
8377        final IPackageInstallObserver observer;
8378        final IPackageInstallObserver2 observer2;
8379        int flags;
8380
8381        private final Uri mPackageURI;
8382        final String installerPackageName;
8383        final VerificationParams verificationParams;
8384        private InstallArgs mArgs;
8385        private int mRet;
8386        private File mTempPackage;
8387        final ContainerEncryptionParams encryptionParams;
8388        final String packageAbiOverride;
8389        final String packageInstructionSetOverride;
8390
8391        InstallParams(Uri packageURI,
8392                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8393                int flags, String installerPackageName, VerificationParams verificationParams,
8394                ContainerEncryptionParams encryptionParams, UserHandle user,
8395                String packageAbiOverride) {
8396            super(user);
8397            this.mPackageURI = packageURI;
8398            this.flags = flags;
8399            this.observer = observer;
8400            this.observer2 = observer2;
8401            this.installerPackageName = installerPackageName;
8402            this.verificationParams = verificationParams;
8403            this.encryptionParams = encryptionParams;
8404            this.packageAbiOverride = packageAbiOverride;
8405            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8406                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8407        }
8408
8409        @Override
8410        public String toString() {
8411            return "InstallParams{"
8412                + Integer.toHexString(System.identityHashCode(this))
8413                + " " + mPackageURI + "}";
8414        }
8415
8416        public ManifestDigest getManifestDigest() {
8417            if (verificationParams == null) {
8418                return null;
8419            }
8420            return verificationParams.getManifestDigest();
8421        }
8422
8423        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8424            String packageName = pkgLite.packageName;
8425            int installLocation = pkgLite.installLocation;
8426            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8427            // reader
8428            synchronized (mPackages) {
8429                PackageParser.Package pkg = mPackages.get(packageName);
8430                if (pkg != null) {
8431                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8432                        // Check for downgrading.
8433                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8434                            if (pkgLite.versionCode < pkg.mVersionCode) {
8435                                Slog.w(TAG, "Can't install update of " + packageName
8436                                        + " update version " + pkgLite.versionCode
8437                                        + " is older than installed version "
8438                                        + pkg.mVersionCode);
8439                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8440                            }
8441                        }
8442                        // Check for updated system application.
8443                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8444                            if (onSd) {
8445                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8446                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8447                            }
8448                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8449                        } else {
8450                            if (onSd) {
8451                                // Install flag overrides everything.
8452                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8453                            }
8454                            // If current upgrade specifies particular preference
8455                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8456                                // Application explicitly specified internal.
8457                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8458                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8459                                // App explictly prefers external. Let policy decide
8460                            } else {
8461                                // Prefer previous location
8462                                if (isExternal(pkg)) {
8463                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8464                                }
8465                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8466                            }
8467                        }
8468                    } else {
8469                        // Invalid install. Return error code
8470                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8471                    }
8472                }
8473            }
8474            // All the special cases have been taken care of.
8475            // Return result based on recommended install location.
8476            if (onSd) {
8477                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8478            }
8479            return pkgLite.recommendedInstallLocation;
8480        }
8481
8482        private long getMemoryLowThreshold() {
8483            final DeviceStorageMonitorInternal
8484                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8485            if (dsm == null) {
8486                return 0L;
8487            }
8488            return dsm.getMemoryLowThreshold();
8489        }
8490
8491        /*
8492         * Invoke remote method to get package information and install
8493         * location values. Override install location based on default
8494         * policy if needed and then create install arguments based
8495         * on the install location.
8496         */
8497        public void handleStartCopy() throws RemoteException {
8498            int ret = PackageManager.INSTALL_SUCCEEDED;
8499            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8500            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8501            PackageInfoLite pkgLite = null;
8502
8503            if (onInt && onSd) {
8504                // Check if both bits are set.
8505                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8506                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8507            } else {
8508                final long lowThreshold = getMemoryLowThreshold();
8509                if (lowThreshold == 0L) {
8510                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8511                }
8512
8513                try {
8514                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8515                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8516
8517                    final File packageFile;
8518                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8519                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8520                        if (mTempPackage != null) {
8521                            ParcelFileDescriptor out;
8522                            try {
8523                                out = ParcelFileDescriptor.open(mTempPackage,
8524                                        ParcelFileDescriptor.MODE_READ_WRITE);
8525                            } catch (FileNotFoundException e) {
8526                                out = null;
8527                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8528                            }
8529
8530                            // Make a temporary file for decryption.
8531                            ret = mContainerService
8532                                    .copyResource(mPackageURI, encryptionParams, out);
8533                            IoUtils.closeQuietly(out);
8534
8535                            packageFile = mTempPackage;
8536
8537                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8538                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8539                                            | FileUtils.S_IROTH,
8540                                    -1, -1);
8541                        } else {
8542                            packageFile = null;
8543                        }
8544                    } else {
8545                        packageFile = new File(mPackageURI.getPath());
8546                    }
8547
8548                    if (packageFile != null) {
8549                        // Remote call to find out default install location
8550                        final String packageFilePath = packageFile.getAbsolutePath();
8551                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8552                                lowThreshold, packageAbiOverride);
8553
8554                        /*
8555                         * If we have too little free space, try to free cache
8556                         * before giving up.
8557                         */
8558                        if (pkgLite.recommendedInstallLocation
8559                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8560                            final long size = mContainerService.calculateInstalledSize(
8561                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8562                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8563                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8564                                        flags, lowThreshold, packageAbiOverride);
8565                            }
8566                            /*
8567                             * The cache free must have deleted the file we
8568                             * downloaded to install.
8569                             *
8570                             * TODO: fix the "freeCache" call to not delete
8571                             *       the file we care about.
8572                             */
8573                            if (pkgLite.recommendedInstallLocation
8574                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8575                                pkgLite.recommendedInstallLocation
8576                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8577                            }
8578                        }
8579                    }
8580                } finally {
8581                    mContext.revokeUriPermission(mPackageURI,
8582                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8583                }
8584            }
8585
8586            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8587                int loc = pkgLite.recommendedInstallLocation;
8588                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8589                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8590                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8591                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8592                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8593                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8594                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8595                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8596                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8597                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8598                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8599                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8600                } else {
8601                    // Override with defaults if needed.
8602                    loc = installLocationPolicy(pkgLite, flags);
8603                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8604                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8605                    } else if (!onSd && !onInt) {
8606                        // Override install location with flags
8607                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8608                            // Set the flag to install on external media.
8609                            flags |= PackageManager.INSTALL_EXTERNAL;
8610                            flags &= ~PackageManager.INSTALL_INTERNAL;
8611                        } else {
8612                            // Make sure the flag for installing on external
8613                            // media is unset
8614                            flags |= PackageManager.INSTALL_INTERNAL;
8615                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8616                        }
8617                    }
8618                }
8619            }
8620
8621            final InstallArgs args = createInstallArgs(this);
8622            mArgs = args;
8623
8624            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8625                 /*
8626                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8627                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8628                 */
8629                int userIdentifier = getUser().getIdentifier();
8630                if (userIdentifier == UserHandle.USER_ALL
8631                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8632                    userIdentifier = UserHandle.USER_OWNER;
8633                }
8634
8635                /*
8636                 * Determine if we have any installed package verifiers. If we
8637                 * do, then we'll defer to them to verify the packages.
8638                 */
8639                final int requiredUid = mRequiredVerifierPackage == null ? -1
8640                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8641                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8642                    final Intent verification = new Intent(
8643                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8644                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8645                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8646
8647                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8648                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8649                            0 /* TODO: Which userId? */);
8650
8651                    if (DEBUG_VERIFY) {
8652                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8653                                + verification.toString() + " with " + pkgLite.verifiers.length
8654                                + " optional verifiers");
8655                    }
8656
8657                    final int verificationId = mPendingVerificationToken++;
8658
8659                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8660
8661                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8662                            installerPackageName);
8663
8664                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8665
8666                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8667                            pkgLite.packageName);
8668
8669                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8670                            pkgLite.versionCode);
8671
8672                    if (verificationParams != null) {
8673                        if (verificationParams.getVerificationURI() != null) {
8674                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8675                                 verificationParams.getVerificationURI());
8676                        }
8677                        if (verificationParams.getOriginatingURI() != null) {
8678                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8679                                  verificationParams.getOriginatingURI());
8680                        }
8681                        if (verificationParams.getReferrer() != null) {
8682                            verification.putExtra(Intent.EXTRA_REFERRER,
8683                                  verificationParams.getReferrer());
8684                        }
8685                        if (verificationParams.getOriginatingUid() >= 0) {
8686                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8687                                  verificationParams.getOriginatingUid());
8688                        }
8689                        if (verificationParams.getInstallerUid() >= 0) {
8690                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8691                                  verificationParams.getInstallerUid());
8692                        }
8693                    }
8694
8695                    final PackageVerificationState verificationState = new PackageVerificationState(
8696                            requiredUid, args);
8697
8698                    mPendingVerification.append(verificationId, verificationState);
8699
8700                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8701                            receivers, verificationState);
8702
8703                    /*
8704                     * If any sufficient verifiers were listed in the package
8705                     * manifest, attempt to ask them.
8706                     */
8707                    if (sufficientVerifiers != null) {
8708                        final int N = sufficientVerifiers.size();
8709                        if (N == 0) {
8710                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8711                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8712                        } else {
8713                            for (int i = 0; i < N; i++) {
8714                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8715
8716                                final Intent sufficientIntent = new Intent(verification);
8717                                sufficientIntent.setComponent(verifierComponent);
8718
8719                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8720                            }
8721                        }
8722                    }
8723
8724                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8725                            mRequiredVerifierPackage, receivers);
8726                    if (ret == PackageManager.INSTALL_SUCCEEDED
8727                            && mRequiredVerifierPackage != null) {
8728                        /*
8729                         * Send the intent to the required verification agent,
8730                         * but only start the verification timeout after the
8731                         * target BroadcastReceivers have run.
8732                         */
8733                        verification.setComponent(requiredVerifierComponent);
8734                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8735                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8736                                new BroadcastReceiver() {
8737                                    @Override
8738                                    public void onReceive(Context context, Intent intent) {
8739                                        final Message msg = mHandler
8740                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8741                                        msg.arg1 = verificationId;
8742                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8743                                    }
8744                                }, null, 0, null, null);
8745
8746                        /*
8747                         * We don't want the copy to proceed until verification
8748                         * succeeds, so null out this field.
8749                         */
8750                        mArgs = null;
8751                    }
8752                } else {
8753                    /*
8754                     * No package verification is enabled, so immediately start
8755                     * the remote call to initiate copy using temporary file.
8756                     */
8757                    ret = args.copyApk(mContainerService, true);
8758                }
8759            }
8760
8761            mRet = ret;
8762        }
8763
8764        @Override
8765        void handleReturnCode() {
8766            // If mArgs is null, then MCS couldn't be reached. When it
8767            // reconnects, it will try again to install. At that point, this
8768            // will succeed.
8769            if (mArgs != null) {
8770                processPendingInstall(mArgs, mRet);
8771
8772                if (mTempPackage != null) {
8773                    if (!mTempPackage.delete()) {
8774                        Slog.w(TAG, "Couldn't delete temporary file: " +
8775                                mTempPackage.getAbsolutePath());
8776                    }
8777                }
8778            }
8779        }
8780
8781        @Override
8782        void handleServiceError() {
8783            mArgs = createInstallArgs(this);
8784            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8785        }
8786
8787        public boolean isForwardLocked() {
8788            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8789        }
8790
8791        public Uri getPackageUri() {
8792            if (mTempPackage != null) {
8793                return Uri.fromFile(mTempPackage);
8794            } else {
8795                return mPackageURI;
8796            }
8797        }
8798    }
8799
8800    /*
8801     * Utility class used in movePackage api.
8802     * srcArgs and targetArgs are not set for invalid flags and make
8803     * sure to do null checks when invoking methods on them.
8804     * We probably want to return ErrorPrams for both failed installs
8805     * and moves.
8806     */
8807    class MoveParams extends HandlerParams {
8808        final IPackageMoveObserver observer;
8809        final int flags;
8810        final String packageName;
8811        final InstallArgs srcArgs;
8812        final InstallArgs targetArgs;
8813        int uid;
8814        int mRet;
8815
8816        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8817                String packageName, String dataDir, String instructionSet,
8818                int uid, UserHandle user) {
8819            super(user);
8820            this.srcArgs = srcArgs;
8821            this.observer = observer;
8822            this.flags = flags;
8823            this.packageName = packageName;
8824            this.uid = uid;
8825            if (srcArgs != null) {
8826                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8827                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8828            } else {
8829                targetArgs = null;
8830            }
8831        }
8832
8833        @Override
8834        public String toString() {
8835            return "MoveParams{"
8836                + Integer.toHexString(System.identityHashCode(this))
8837                + " " + packageName + "}";
8838        }
8839
8840        public void handleStartCopy() throws RemoteException {
8841            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8842            // Check for storage space on target medium
8843            if (!targetArgs.checkFreeStorage(mContainerService)) {
8844                Log.w(TAG, "Insufficient storage to install");
8845                return;
8846            }
8847
8848            mRet = srcArgs.doPreCopy();
8849            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8850                return;
8851            }
8852
8853            mRet = targetArgs.copyApk(mContainerService, false);
8854            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8855                srcArgs.doPostCopy(uid);
8856                return;
8857            }
8858
8859            mRet = srcArgs.doPostCopy(uid);
8860            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8861                return;
8862            }
8863
8864            mRet = targetArgs.doPreInstall(mRet);
8865            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8866                return;
8867            }
8868
8869            if (DEBUG_SD_INSTALL) {
8870                StringBuilder builder = new StringBuilder();
8871                if (srcArgs != null) {
8872                    builder.append("src: ");
8873                    builder.append(srcArgs.getCodePath());
8874                }
8875                if (targetArgs != null) {
8876                    builder.append(" target : ");
8877                    builder.append(targetArgs.getCodePath());
8878                }
8879                Log.i(TAG, builder.toString());
8880            }
8881        }
8882
8883        @Override
8884        void handleReturnCode() {
8885            targetArgs.doPostInstall(mRet, uid);
8886            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8887            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8888                currentStatus = PackageManager.MOVE_SUCCEEDED;
8889            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8890                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8891            }
8892            processPendingMove(this, currentStatus);
8893        }
8894
8895        @Override
8896        void handleServiceError() {
8897            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8898        }
8899    }
8900
8901    /**
8902     * Used during creation of InstallArgs
8903     *
8904     * @param flags package installation flags
8905     * @return true if should be installed on external storage
8906     */
8907    private static boolean installOnSd(int flags) {
8908        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8909            return false;
8910        }
8911        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8912            return true;
8913        }
8914        return false;
8915    }
8916
8917    /**
8918     * Used during creation of InstallArgs
8919     *
8920     * @param flags package installation flags
8921     * @return true if should be installed as forward locked
8922     */
8923    private static boolean installForwardLocked(int flags) {
8924        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8925    }
8926
8927    private InstallArgs createInstallArgs(InstallParams params) {
8928        if (installOnSd(params.flags) || params.isForwardLocked()) {
8929            return new AsecInstallArgs(params);
8930        } else {
8931            return new FileInstallArgs(params);
8932        }
8933    }
8934
8935    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8936            String nativeLibraryPath, String instructionSet) {
8937        final boolean isInAsec;
8938        if (installOnSd(flags)) {
8939            /* Apps on SD card are always in ASEC containers. */
8940            isInAsec = true;
8941        } else if (installForwardLocked(flags)
8942                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8943            /*
8944             * Forward-locked apps are only in ASEC containers if they're the
8945             * new style
8946             */
8947            isInAsec = true;
8948        } else {
8949            isInAsec = false;
8950        }
8951
8952        if (isInAsec) {
8953            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8954                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8955        } else {
8956            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8957                    instructionSet);
8958        }
8959    }
8960
8961    // Used by package mover
8962    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8963            String instructionSet) {
8964        if (installOnSd(flags) || installForwardLocked(flags)) {
8965            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8966                    + AsecInstallArgs.RES_FILE_NAME);
8967            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8968                    installForwardLocked(flags));
8969        } else {
8970            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8971        }
8972    }
8973
8974    static abstract class InstallArgs {
8975        final IPackageInstallObserver observer;
8976        final IPackageInstallObserver2 observer2;
8977        // Always refers to PackageManager flags only
8978        final int flags;
8979        final Uri packageURI;
8980        final String installerPackageName;
8981        final ManifestDigest manifestDigest;
8982        final UserHandle user;
8983        final String instructionSet;
8984        final String abiOverride;
8985
8986        InstallArgs(Uri packageURI,
8987                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8988                int flags, String installerPackageName, ManifestDigest manifestDigest,
8989                UserHandle user, String instructionSet, String abiOverride) {
8990            this.packageURI = packageURI;
8991            this.flags = flags;
8992            this.observer = observer;
8993            this.observer2 = observer2;
8994            this.installerPackageName = installerPackageName;
8995            this.manifestDigest = manifestDigest;
8996            this.user = user;
8997            this.instructionSet = instructionSet;
8998            this.abiOverride = abiOverride;
8999        }
9000
9001        abstract void createCopyFile();
9002        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9003        abstract int doPreInstall(int status);
9004        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9005
9006        abstract int doPostInstall(int status, int uid);
9007        abstract String getCodePath();
9008        abstract String getResourcePath();
9009        abstract String getNativeLibraryPath();
9010        // Need installer lock especially for dex file removal.
9011        abstract void cleanUpResourcesLI();
9012        abstract boolean doPostDeleteLI(boolean delete);
9013        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9014
9015        String[] getSplitCodePaths() {
9016            return null;
9017        }
9018
9019        /**
9020         * Called before the source arguments are copied. This is used mostly
9021         * for MoveParams when it needs to read the source file to put it in the
9022         * destination.
9023         */
9024        int doPreCopy() {
9025            return PackageManager.INSTALL_SUCCEEDED;
9026        }
9027
9028        /**
9029         * Called after the source arguments are copied. This is used mostly for
9030         * MoveParams when it needs to read the source file to put it in the
9031         * destination.
9032         *
9033         * @return
9034         */
9035        int doPostCopy(int uid) {
9036            return PackageManager.INSTALL_SUCCEEDED;
9037        }
9038
9039        protected boolean isFwdLocked() {
9040            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9041        }
9042
9043        UserHandle getUser() {
9044            return user;
9045        }
9046    }
9047
9048    class FileInstallArgs extends InstallArgs {
9049        File installDir;
9050        String codeFileName;
9051        String resourceFileName;
9052        String libraryPath;
9053        boolean created = false;
9054
9055        FileInstallArgs(InstallParams params) {
9056            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9057                    params.installerPackageName, params.getManifestDigest(),
9058                    params.getUser(), params.packageInstructionSetOverride,
9059                    params.packageAbiOverride);
9060        }
9061
9062        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9063                String instructionSet) {
9064            super(null, null, null, 0, null, null, null, instructionSet, null);
9065            File codeFile = new File(fullCodePath);
9066            installDir = codeFile.getParentFile();
9067            codeFileName = fullCodePath;
9068            resourceFileName = fullResourcePath;
9069            libraryPath = nativeLibraryPath;
9070        }
9071
9072        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9073            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9074            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9075            String apkName = getNextCodePath(null, pkgName, ".apk");
9076            codeFileName = new File(installDir, apkName + ".apk").getPath();
9077            resourceFileName = getResourcePathFromCodePath();
9078            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9079        }
9080
9081        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9082            final long lowThreshold;
9083
9084            final DeviceStorageMonitorInternal
9085                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9086            if (dsm == null) {
9087                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9088                lowThreshold = 0L;
9089            } else {
9090                if (dsm.isMemoryLow()) {
9091                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9092                    return false;
9093                }
9094
9095                lowThreshold = dsm.getMemoryLowThreshold();
9096            }
9097
9098            try {
9099                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9100                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9101                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9102            } finally {
9103                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9104            }
9105        }
9106
9107        void createCopyFile() {
9108            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9109            codeFileName = createTempPackageFile(installDir).getPath();
9110            resourceFileName = getResourcePathFromCodePath();
9111            libraryPath = getLibraryPathFromCodePath();
9112            created = true;
9113        }
9114
9115        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9116            if (temp) {
9117                // Generate temp file name
9118                createCopyFile();
9119            }
9120            // Get a ParcelFileDescriptor to write to the output file
9121            File codeFile = new File(codeFileName);
9122            if (!created) {
9123                try {
9124                    codeFile.createNewFile();
9125                    // Set permissions
9126                    if (!setPermissions()) {
9127                        // Failed setting permissions.
9128                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9129                    }
9130                } catch (IOException e) {
9131                   Slog.w(TAG, "Failed to create file " + codeFile);
9132                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9133                }
9134            }
9135            ParcelFileDescriptor out = null;
9136            try {
9137                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9138            } catch (FileNotFoundException e) {
9139                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9140                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9141            }
9142            // Copy the resource now
9143            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9144            try {
9145                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9146                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9147                ret = imcs.copyResource(packageURI, null, out);
9148            } finally {
9149                IoUtils.closeQuietly(out);
9150                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9151            }
9152
9153            if (isFwdLocked()) {
9154                final File destResourceFile = new File(getResourcePath());
9155
9156                // Copy the public files
9157                try {
9158                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9159                } catch (IOException e) {
9160                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9161                            + " forward-locked app.");
9162                    destResourceFile.delete();
9163                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9164                }
9165            }
9166
9167            final File nativeLibraryFile = new File(getNativeLibraryPath());
9168            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9169            if (nativeLibraryFile.exists()) {
9170                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9171                nativeLibraryFile.delete();
9172            }
9173
9174            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9175            String[] abiList = (abiOverride != null) ?
9176                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9177            try {
9178                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9179                        abiOverride == null &&
9180                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9181                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9182                }
9183
9184                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9185                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9186                    return copyRet;
9187                }
9188            } catch (IOException e) {
9189                Slog.e(TAG, "Copying native libraries failed", e);
9190                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9191            } finally {
9192                handle.close();
9193            }
9194
9195            return ret;
9196        }
9197
9198        int doPreInstall(int status) {
9199            if (status != PackageManager.INSTALL_SUCCEEDED) {
9200                cleanUp();
9201            }
9202            return status;
9203        }
9204
9205        boolean doRename(int status, final String pkgName, String oldCodePath) {
9206            if (status != PackageManager.INSTALL_SUCCEEDED) {
9207                cleanUp();
9208                return false;
9209            } else {
9210                final File oldCodeFile = new File(getCodePath());
9211                final File oldResourceFile = new File(getResourcePath());
9212                final File oldLibraryFile = new File(getNativeLibraryPath());
9213
9214                // Rename APK file based on packageName
9215                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9216                final File newCodeFile = new File(installDir, apkName + ".apk");
9217                if (!oldCodeFile.renameTo(newCodeFile)) {
9218                    return false;
9219                }
9220                codeFileName = newCodeFile.getPath();
9221
9222                // Rename public resource file if it's forward-locked.
9223                final File newResFile = new File(getResourcePathFromCodePath());
9224                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9225                    return false;
9226                }
9227                resourceFileName = newResFile.getPath();
9228
9229                // Rename library path
9230                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9231                if (newLibraryFile.exists()) {
9232                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9233                    newLibraryFile.delete();
9234                }
9235                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9236                    Slog.e(TAG, "Cannot rename native library directory "
9237                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9238                    return false;
9239                }
9240                libraryPath = newLibraryFile.getPath();
9241
9242                // Attempt to set permissions
9243                if (!setPermissions()) {
9244                    return false;
9245                }
9246
9247                if (!SELinux.restorecon(newCodeFile)) {
9248                    return false;
9249                }
9250
9251                return true;
9252            }
9253        }
9254
9255        int doPostInstall(int status, int uid) {
9256            if (status != PackageManager.INSTALL_SUCCEEDED) {
9257                cleanUp();
9258            }
9259            return status;
9260        }
9261
9262        private String getResourcePathFromCodePath() {
9263            final String codePath = getCodePath();
9264            if (isFwdLocked()) {
9265                final StringBuilder sb = new StringBuilder();
9266
9267                sb.append(mAppInstallDir.getPath());
9268                sb.append('/');
9269                sb.append(getApkName(codePath));
9270                sb.append(".zip");
9271
9272                /*
9273                 * If our APK is a temporary file, mark the resource as a
9274                 * temporary file as well so it can be cleaned up after
9275                 * catastrophic failure.
9276                 */
9277                if (codePath.endsWith(".tmp")) {
9278                    sb.append(".tmp");
9279                }
9280
9281                return sb.toString();
9282            } else {
9283                return codePath;
9284            }
9285        }
9286
9287        private String getLibraryPathFromCodePath() {
9288            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9289        }
9290
9291        @Override
9292        String getCodePath() {
9293            return codeFileName;
9294        }
9295
9296        @Override
9297        String getResourcePath() {
9298            return resourceFileName;
9299        }
9300
9301        @Override
9302        String getNativeLibraryPath() {
9303            if (libraryPath == null) {
9304                libraryPath = getLibraryPathFromCodePath();
9305            }
9306            return libraryPath;
9307        }
9308
9309        private boolean cleanUp() {
9310            boolean ret = true;
9311            String sourceDir = getCodePath();
9312            String publicSourceDir = getResourcePath();
9313            if (sourceDir != null) {
9314                File sourceFile = new File(sourceDir);
9315                if (!sourceFile.exists()) {
9316                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9317                    ret = false;
9318                }
9319                // Delete application's code and resources
9320                sourceFile.delete();
9321            }
9322            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9323                final File publicSourceFile = new File(publicSourceDir);
9324                if (!publicSourceFile.exists()) {
9325                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9326                }
9327                if (publicSourceFile.exists()) {
9328                    publicSourceFile.delete();
9329                }
9330            }
9331
9332            if (libraryPath != null) {
9333                File nativeLibraryFile = new File(libraryPath);
9334                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9335                if (!nativeLibraryFile.delete()) {
9336                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9337                }
9338            }
9339
9340            return ret;
9341        }
9342
9343        void cleanUpResourcesLI() {
9344            String sourceDir = getCodePath();
9345            if (cleanUp()) {
9346                if (instructionSet == null) {
9347                    throw new IllegalStateException("instructionSet == null");
9348                }
9349                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9350                if (retCode < 0) {
9351                    Slog.w(TAG, "Couldn't remove dex file for package: "
9352                            +  " at location "
9353                            + sourceDir + ", retcode=" + retCode);
9354                    // we don't consider this to be a failure of the core package deletion
9355                }
9356            }
9357        }
9358
9359        private boolean setPermissions() {
9360            // TODO Do this in a more elegant way later on. for now just a hack
9361            if (!isFwdLocked()) {
9362                final int filePermissions =
9363                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9364                    |FileUtils.S_IROTH;
9365                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9366                if (retCode != 0) {
9367                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9368                            getCodePath()
9369                            + ". The return code was: " + retCode);
9370                    // TODO Define new internal error
9371                    return false;
9372                }
9373                return true;
9374            }
9375            return true;
9376        }
9377
9378        boolean doPostDeleteLI(boolean delete) {
9379            // XXX err, shouldn't we respect the delete flag?
9380            cleanUpResourcesLI();
9381            return true;
9382        }
9383    }
9384
9385    private boolean isAsecExternal(String cid) {
9386        final String asecPath = PackageHelper.getSdFilesystem(cid);
9387        return !asecPath.startsWith(mAsecInternalPath);
9388    }
9389
9390    /**
9391     * Extract the MountService "container ID" from the full code path of an
9392     * .apk.
9393     */
9394    static String cidFromCodePath(String fullCodePath) {
9395        int eidx = fullCodePath.lastIndexOf("/");
9396        String subStr1 = fullCodePath.substring(0, eidx);
9397        int sidx = subStr1.lastIndexOf("/");
9398        return subStr1.substring(sidx+1, eidx);
9399    }
9400
9401    class AsecInstallArgs extends InstallArgs {
9402        static final String RES_FILE_NAME = "pkg.apk";
9403        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9404
9405        String cid;
9406        String packagePath;
9407        String resourcePath;
9408        String libraryPath;
9409
9410        AsecInstallArgs(InstallParams params) {
9411            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9412                    params.installerPackageName, params.getManifestDigest(),
9413                    params.getUser(), params.packageInstructionSetOverride,
9414                    params.packageAbiOverride);
9415        }
9416
9417        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9418                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9419            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9420                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9421                    null, null, null, instructionSet, null);
9422            // Extract cid from fullCodePath
9423            int eidx = fullCodePath.lastIndexOf("/");
9424            String subStr1 = fullCodePath.substring(0, eidx);
9425            int sidx = subStr1.lastIndexOf("/");
9426            cid = subStr1.substring(sidx+1, eidx);
9427            setCachePath(subStr1);
9428        }
9429
9430        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9431            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9432                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9433                    null, null, null, instructionSet, null);
9434            this.cid = cid;
9435            setCachePath(PackageHelper.getSdDir(cid));
9436        }
9437
9438        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9439                boolean isExternal, boolean isForwardLocked) {
9440            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9441                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9442                    null, null, null, instructionSet, null);
9443            this.cid = cid;
9444        }
9445
9446        void createCopyFile() {
9447            cid = getTempContainerId();
9448        }
9449
9450        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9451            try {
9452                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9453                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9454                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9455            } finally {
9456                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9457            }
9458        }
9459
9460        private final boolean isExternal() {
9461            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9462        }
9463
9464        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9465            if (temp) {
9466                createCopyFile();
9467            } else {
9468                /*
9469                 * Pre-emptively destroy the container since it's destroyed if
9470                 * copying fails due to it existing anyway.
9471                 */
9472                PackageHelper.destroySdDir(cid);
9473            }
9474
9475            final String newCachePath;
9476            try {
9477                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9478                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9479                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9480                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9481                        abiOverride);
9482            } finally {
9483                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9484            }
9485
9486            if (newCachePath != null) {
9487                setCachePath(newCachePath);
9488                return PackageManager.INSTALL_SUCCEEDED;
9489            } else {
9490                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9491            }
9492        }
9493
9494        @Override
9495        String getCodePath() {
9496            return packagePath;
9497        }
9498
9499        @Override
9500        String getResourcePath() {
9501            return resourcePath;
9502        }
9503
9504        @Override
9505        String getNativeLibraryPath() {
9506            return libraryPath;
9507        }
9508
9509        int doPreInstall(int status) {
9510            if (status != PackageManager.INSTALL_SUCCEEDED) {
9511                // Destroy container
9512                PackageHelper.destroySdDir(cid);
9513            } else {
9514                boolean mounted = PackageHelper.isContainerMounted(cid);
9515                if (!mounted) {
9516                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9517                            Process.SYSTEM_UID);
9518                    if (newCachePath != null) {
9519                        setCachePath(newCachePath);
9520                    } else {
9521                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9522                    }
9523                }
9524            }
9525            return status;
9526        }
9527
9528        boolean doRename(int status, final String pkgName,
9529                String oldCodePath) {
9530            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9531            String newCachePath = null;
9532            if (PackageHelper.isContainerMounted(cid)) {
9533                // Unmount the container
9534                if (!PackageHelper.unMountSdDir(cid)) {
9535                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9536                    return false;
9537                }
9538            }
9539            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9540                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9541                        " which might be stale. Will try to clean up.");
9542                // Clean up the stale container and proceed to recreate.
9543                if (!PackageHelper.destroySdDir(newCacheId)) {
9544                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9545                    return false;
9546                }
9547                // Successfully cleaned up stale container. Try to rename again.
9548                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9549                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9550                            + " inspite of cleaning it up.");
9551                    return false;
9552                }
9553            }
9554            if (!PackageHelper.isContainerMounted(newCacheId)) {
9555                Slog.w(TAG, "Mounting container " + newCacheId);
9556                newCachePath = PackageHelper.mountSdDir(newCacheId,
9557                        getEncryptKey(), Process.SYSTEM_UID);
9558            } else {
9559                newCachePath = PackageHelper.getSdDir(newCacheId);
9560            }
9561            if (newCachePath == null) {
9562                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9563                return false;
9564            }
9565            Log.i(TAG, "Succesfully renamed " + cid +
9566                    " to " + newCacheId +
9567                    " at new path: " + newCachePath);
9568            cid = newCacheId;
9569            setCachePath(newCachePath);
9570            return true;
9571        }
9572
9573        private void setCachePath(String newCachePath) {
9574            File cachePath = new File(newCachePath);
9575            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9576            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9577
9578            if (isFwdLocked()) {
9579                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9580            } else {
9581                resourcePath = packagePath;
9582            }
9583        }
9584
9585        int doPostInstall(int status, int uid) {
9586            if (status != PackageManager.INSTALL_SUCCEEDED) {
9587                cleanUp();
9588            } else {
9589                final int groupOwner;
9590                final String protectedFile;
9591                if (isFwdLocked()) {
9592                    groupOwner = UserHandle.getSharedAppGid(uid);
9593                    protectedFile = RES_FILE_NAME;
9594                } else {
9595                    groupOwner = -1;
9596                    protectedFile = null;
9597                }
9598
9599                if (uid < Process.FIRST_APPLICATION_UID
9600                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9601                    Slog.e(TAG, "Failed to finalize " + cid);
9602                    PackageHelper.destroySdDir(cid);
9603                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9604                }
9605
9606                boolean mounted = PackageHelper.isContainerMounted(cid);
9607                if (!mounted) {
9608                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9609                }
9610            }
9611            return status;
9612        }
9613
9614        private void cleanUp() {
9615            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9616
9617            // Destroy secure container
9618            PackageHelper.destroySdDir(cid);
9619        }
9620
9621        void cleanUpResourcesLI() {
9622            String sourceFile = getCodePath();
9623            // Remove dex file
9624            if (instructionSet == null) {
9625                throw new IllegalStateException("instructionSet == null");
9626            }
9627            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9628            if (retCode < 0) {
9629                Slog.w(TAG, "Couldn't remove dex file for package: "
9630                        + " at location "
9631                        + sourceFile.toString() + ", retcode=" + retCode);
9632                // we don't consider this to be a failure of the core package deletion
9633            }
9634            cleanUp();
9635        }
9636
9637        boolean matchContainer(String app) {
9638            if (cid.startsWith(app)) {
9639                return true;
9640            }
9641            return false;
9642        }
9643
9644        String getPackageName() {
9645            return getAsecPackageName(cid);
9646        }
9647
9648        boolean doPostDeleteLI(boolean delete) {
9649            boolean ret = false;
9650            boolean mounted = PackageHelper.isContainerMounted(cid);
9651            if (mounted) {
9652                // Unmount first
9653                ret = PackageHelper.unMountSdDir(cid);
9654            }
9655            if (ret && delete) {
9656                cleanUpResourcesLI();
9657            }
9658            return ret;
9659        }
9660
9661        @Override
9662        int doPreCopy() {
9663            if (isFwdLocked()) {
9664                if (!PackageHelper.fixSdPermissions(cid,
9665                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9666                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9667                }
9668            }
9669
9670            return PackageManager.INSTALL_SUCCEEDED;
9671        }
9672
9673        @Override
9674        int doPostCopy(int uid) {
9675            if (isFwdLocked()) {
9676                if (uid < Process.FIRST_APPLICATION_UID
9677                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9678                                RES_FILE_NAME)) {
9679                    Slog.e(TAG, "Failed to finalize " + cid);
9680                    PackageHelper.destroySdDir(cid);
9681                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9682                }
9683            }
9684
9685            return PackageManager.INSTALL_SUCCEEDED;
9686        }
9687    }
9688
9689    static String getAsecPackageName(String packageCid) {
9690        int idx = packageCid.lastIndexOf("-");
9691        if (idx == -1) {
9692            return packageCid;
9693        }
9694        return packageCid.substring(0, idx);
9695    }
9696
9697    // Utility method used to create code paths based on package name and available index.
9698    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9699        String idxStr = "";
9700        int idx = 1;
9701        // Fall back to default value of idx=1 if prefix is not
9702        // part of oldCodePath
9703        if (oldCodePath != null) {
9704            String subStr = oldCodePath;
9705            // Drop the suffix right away
9706            if (subStr.endsWith(suffix)) {
9707                subStr = subStr.substring(0, subStr.length() - suffix.length());
9708            }
9709            // If oldCodePath already contains prefix find out the
9710            // ending index to either increment or decrement.
9711            int sidx = subStr.lastIndexOf(prefix);
9712            if (sidx != -1) {
9713                subStr = subStr.substring(sidx + prefix.length());
9714                if (subStr != null) {
9715                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9716                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9717                    }
9718                    try {
9719                        idx = Integer.parseInt(subStr);
9720                        if (idx <= 1) {
9721                            idx++;
9722                        } else {
9723                            idx--;
9724                        }
9725                    } catch(NumberFormatException e) {
9726                    }
9727                }
9728            }
9729        }
9730        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9731        return prefix + idxStr;
9732    }
9733
9734    // Utility method used to ignore ADD/REMOVE events
9735    // by directory observer.
9736    private static boolean ignoreCodePath(String fullPathStr) {
9737        String apkName = getApkName(fullPathStr);
9738        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9739        if (idx != -1 && ((idx+1) < apkName.length())) {
9740            // Make sure the package ends with a numeral
9741            String version = apkName.substring(idx+1);
9742            try {
9743                Integer.parseInt(version);
9744                return true;
9745            } catch (NumberFormatException e) {}
9746        }
9747        return false;
9748    }
9749
9750    // Utility method that returns the relative package path with respect
9751    // to the installation directory. Like say for /data/data/com.test-1.apk
9752    // string com.test-1 is returned.
9753    static String getApkName(String codePath) {
9754        if (codePath == null) {
9755            return null;
9756        }
9757        int sidx = codePath.lastIndexOf("/");
9758        int eidx = codePath.lastIndexOf(".");
9759        if (eidx == -1) {
9760            eidx = codePath.length();
9761        } else if (eidx == 0) {
9762            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9763            return null;
9764        }
9765        return codePath.substring(sidx+1, eidx);
9766    }
9767
9768    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9769        String[] splitResPaths = null;
9770        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9771            splitResPaths = new String[splitCodePaths.length];
9772            for (int i = 0; i < splitCodePaths.length; i++) {
9773                final String splitCodePath = splitCodePaths[i];
9774                final String resName = getApkName(splitCodePath) + ".zip";
9775                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9776                        resName).getAbsolutePath();
9777            }
9778        }
9779        return splitResPaths;
9780    }
9781
9782    class PackageInstalledInfo {
9783        String name;
9784        int uid;
9785        // The set of users that originally had this package installed.
9786        int[] origUsers;
9787        // The set of users that now have this package installed.
9788        int[] newUsers;
9789        PackageParser.Package pkg;
9790        int returnCode;
9791        PackageRemovedInfo removedInfo;
9792
9793        // In some error cases we want to convey more info back to the observer
9794        String origPackage;
9795        String origPermission;
9796    }
9797
9798    /*
9799     * Install a non-existing package.
9800     */
9801    private void installNewPackageLI(PackageParser.Package pkg,
9802            int parseFlags, int scanMode, UserHandle user,
9803            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9804        // Remember this for later, in case we need to rollback this install
9805        String pkgName = pkg.packageName;
9806
9807        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9808        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9809        synchronized(mPackages) {
9810            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9811                // A package with the same name is already installed, though
9812                // it has been renamed to an older name.  The package we
9813                // are trying to install should be installed as an update to
9814                // the existing one, but that has not been requested, so bail.
9815                Slog.w(TAG, "Attempt to re-install " + pkgName
9816                        + " without first uninstalling package running as "
9817                        + mSettings.mRenamedPackages.get(pkgName));
9818                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9819                return;
9820            }
9821            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9822                // Don't allow installation over an existing package with the same name.
9823                Slog.w(TAG, "Attempt to re-install " + pkgName
9824                        + " without first uninstalling.");
9825                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9826                return;
9827            }
9828        }
9829        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9830        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9831                System.currentTimeMillis(), user, abiOverride);
9832        if (newPackage == null) {
9833            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9834            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9835                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9836            }
9837        } else {
9838            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9839            // delete the partially installed application. the data directory will have to be
9840            // restored if it was already existing
9841            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9842                // remove package from internal structures.  Note that we want deletePackageX to
9843                // delete the package data and cache directories that it created in
9844                // scanPackageLocked, unless those directories existed before we even tried to
9845                // install.
9846                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9847                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9848                                res.removedInfo, true);
9849            }
9850        }
9851    }
9852
9853    private void replacePackageLI(PackageParser.Package pkg,
9854            int parseFlags, int scanMode, UserHandle user,
9855            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9856
9857        PackageParser.Package oldPackage;
9858        String pkgName = pkg.packageName;
9859        int[] allUsers;
9860        boolean[] perUserInstalled;
9861
9862        // First find the old package info and check signatures
9863        synchronized(mPackages) {
9864            oldPackage = mPackages.get(pkgName);
9865            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9866            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9867                    != PackageManager.SIGNATURE_MATCH) {
9868                Slog.w(TAG, "New package has a different signature: " + pkgName);
9869                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9870                return;
9871            }
9872
9873            // In case of rollback, remember per-user/profile install state
9874            PackageSetting ps = mSettings.mPackages.get(pkgName);
9875            allUsers = sUserManager.getUserIds();
9876            perUserInstalled = new boolean[allUsers.length];
9877            for (int i = 0; i < allUsers.length; i++) {
9878                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9879            }
9880        }
9881        boolean sysPkg = (isSystemApp(oldPackage));
9882        if (sysPkg) {
9883            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9884                    user, allUsers, perUserInstalled, installerPackageName, res,
9885                    abiOverride);
9886        } else {
9887            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9888                    user, allUsers, perUserInstalled, installerPackageName, res,
9889                    abiOverride);
9890        }
9891    }
9892
9893    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9894            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9895            int[] allUsers, boolean[] perUserInstalled,
9896            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9897        PackageParser.Package newPackage = null;
9898        String pkgName = deletedPackage.packageName;
9899        boolean deletedPkg = true;
9900        boolean updatedSettings = false;
9901
9902        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9903                + deletedPackage);
9904        long origUpdateTime;
9905        if (pkg.mExtras != null) {
9906            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9907        } else {
9908            origUpdateTime = 0;
9909        }
9910
9911        // First delete the existing package while retaining the data directory
9912        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9913                res.removedInfo, true)) {
9914            // If the existing package wasn't successfully deleted
9915            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9916            deletedPkg = false;
9917        } else {
9918            // Successfully deleted the old package. Now proceed with re-installation
9919            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9920            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9921                    System.currentTimeMillis(), user, abiOverride);
9922            if (newPackage == null) {
9923                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9924                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9925                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9926                }
9927            } else {
9928                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9929                updatedSettings = true;
9930            }
9931        }
9932
9933        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9934            // remove package from internal structures.  Note that we want deletePackageX to
9935            // delete the package data and cache directories that it created in
9936            // scanPackageLocked, unless those directories existed before we even tried to
9937            // install.
9938            if(updatedSettings) {
9939                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9940                deletePackageLI(
9941                        pkgName, null, true, allUsers, perUserInstalled,
9942                        PackageManager.DELETE_KEEP_DATA,
9943                                res.removedInfo, true);
9944            }
9945            // Since we failed to install the new package we need to restore the old
9946            // package that we deleted.
9947            if (deletedPkg) {
9948                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9949                File restoreFile = new File(deletedPackage.codePath);
9950                // Parse old package
9951                boolean oldOnSd = isExternal(deletedPackage);
9952                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9953                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9954                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9955                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9956                        | SCAN_UPDATE_TIME;
9957                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9958                        origUpdateTime, null, null) == null) {
9959                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9960                    return;
9961                }
9962                // Restore of old package succeeded. Update permissions.
9963                // writer
9964                synchronized (mPackages) {
9965                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9966                            UPDATE_PERMISSIONS_ALL);
9967                    // can downgrade to reader
9968                    mSettings.writeLPr();
9969                }
9970                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9971            }
9972        }
9973    }
9974
9975    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9976            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9977            int[] allUsers, boolean[] perUserInstalled,
9978            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9979        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9980                + ", old=" + deletedPackage);
9981        PackageParser.Package newPackage = null;
9982        boolean updatedSettings = false;
9983        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9984                PackageParser.PARSE_IS_SYSTEM;
9985        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9986            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9987        }
9988        String packageName = deletedPackage.packageName;
9989        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9990        if (packageName == null) {
9991            Slog.w(TAG, "Attempt to delete null packageName.");
9992            return;
9993        }
9994        PackageParser.Package oldPkg;
9995        PackageSetting oldPkgSetting;
9996        // reader
9997        synchronized (mPackages) {
9998            oldPkg = mPackages.get(packageName);
9999            oldPkgSetting = mSettings.mPackages.get(packageName);
10000            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10001                    (oldPkgSetting == null)) {
10002                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10003                return;
10004            }
10005        }
10006
10007        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10008
10009        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10010        res.removedInfo.removedPackage = packageName;
10011        // Remove existing system package
10012        removePackageLI(oldPkgSetting, true);
10013        // writer
10014        synchronized (mPackages) {
10015            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10016                // We didn't need to disable the .apk as a current system package,
10017                // which means we are replacing another update that is already
10018                // installed.  We need to make sure to delete the older one's .apk.
10019                res.removedInfo.args = createInstallArgs(0,
10020                        deletedPackage.applicationInfo.sourceDir,
10021                        deletedPackage.applicationInfo.publicSourceDir,
10022                        deletedPackage.applicationInfo.nativeLibraryDir,
10023                        getAppInstructionSet(deletedPackage.applicationInfo));
10024            } else {
10025                res.removedInfo.args = null;
10026            }
10027        }
10028
10029        // Successfully disabled the old package. Now proceed with re-installation
10030        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10031        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10032        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10033        if (newPackage == null) {
10034            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10035            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10036                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10037            }
10038        } else {
10039            if (newPackage.mExtras != null) {
10040                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10041                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10042                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10043
10044                // is the update attempting to change shared user? that isn't going to work...
10045                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10046                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10047                            + " to " + newPkgSetting.sharedUser);
10048                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10049                    updatedSettings = true;
10050                }
10051            }
10052
10053            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10054                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10055                updatedSettings = true;
10056            }
10057        }
10058
10059        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10060            // Re installation failed. Restore old information
10061            // Remove new pkg information
10062            if (newPackage != null) {
10063                removeInstalledPackageLI(newPackage, true);
10064            }
10065            // Add back the old system package
10066            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10067            // Restore the old system information in Settings
10068            synchronized(mPackages) {
10069                if (updatedSettings) {
10070                    mSettings.enableSystemPackageLPw(packageName);
10071                    mSettings.setInstallerPackageName(packageName,
10072                            oldPkgSetting.installerPackageName);
10073                }
10074                mSettings.writeLPr();
10075            }
10076        }
10077    }
10078
10079    // Utility method used to move dex files during install.
10080    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10081        // TODO: extend to move split APK dex files
10082        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10083            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10084            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10085                                             instructionSet);
10086            if (retCode != 0) {
10087                /*
10088                 * Programs may be lazily run through dexopt, so the
10089                 * source may not exist. However, something seems to
10090                 * have gone wrong, so note that dexopt needs to be
10091                 * run again and remove the source file. In addition,
10092                 * remove the target to make sure there isn't a stale
10093                 * file from a previous version of the package.
10094                 */
10095                newPackage.mDexOptNeeded = true;
10096                mInstaller.rmdex(oldCodePath, instructionSet);
10097                mInstaller.rmdex(newPackage.codePath, instructionSet);
10098            }
10099        }
10100        return PackageManager.INSTALL_SUCCEEDED;
10101    }
10102
10103    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10104            int[] allUsers, boolean[] perUserInstalled,
10105            PackageInstalledInfo res) {
10106        String pkgName = newPackage.packageName;
10107        synchronized (mPackages) {
10108            //write settings. the installStatus will be incomplete at this stage.
10109            //note that the new package setting would have already been
10110            //added to mPackages. It hasn't been persisted yet.
10111            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10112            mSettings.writeLPr();
10113        }
10114
10115        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10116
10117        synchronized (mPackages) {
10118            updatePermissionsLPw(newPackage.packageName, newPackage,
10119                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10120                            ? UPDATE_PERMISSIONS_ALL : 0));
10121            // For system-bundled packages, we assume that installing an upgraded version
10122            // of the package implies that the user actually wants to run that new code,
10123            // so we enable the package.
10124            if (isSystemApp(newPackage)) {
10125                // NB: implicit assumption that system package upgrades apply to all users
10126                if (DEBUG_INSTALL) {
10127                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10128                }
10129                PackageSetting ps = mSettings.mPackages.get(pkgName);
10130                if (ps != null) {
10131                    if (res.origUsers != null) {
10132                        for (int userHandle : res.origUsers) {
10133                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10134                                    userHandle, installerPackageName);
10135                        }
10136                    }
10137                    // Also convey the prior install/uninstall state
10138                    if (allUsers != null && perUserInstalled != null) {
10139                        for (int i = 0; i < allUsers.length; i++) {
10140                            if (DEBUG_INSTALL) {
10141                                Slog.d(TAG, "    user " + allUsers[i]
10142                                        + " => " + perUserInstalled[i]);
10143                            }
10144                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10145                        }
10146                        // these install state changes will be persisted in the
10147                        // upcoming call to mSettings.writeLPr().
10148                    }
10149                }
10150            }
10151            res.name = pkgName;
10152            res.uid = newPackage.applicationInfo.uid;
10153            res.pkg = newPackage;
10154            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10155            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10156            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10157            //to update install status
10158            mSettings.writeLPr();
10159        }
10160    }
10161
10162    private void installPackageLI(InstallArgs args,
10163            boolean newInstall, PackageInstalledInfo res) {
10164        int pFlags = args.flags;
10165        String installerPackageName = args.installerPackageName;
10166        File tmpPackageFile = new File(args.getCodePath());
10167        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10168        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10169        boolean replace = false;
10170        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10171                | (newInstall ? SCAN_NEW_INSTALL : 0);
10172        // Result object to be returned
10173        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10174
10175        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10176        // Retrieve PackageSettings and parse package
10177        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10178                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10179                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10180        PackageParser pp = new PackageParser();
10181        pp.setSeparateProcesses(mSeparateProcesses);
10182        pp.setDisplayMetrics(mMetrics);
10183
10184        final PackageParser.Package pkg;
10185        try {
10186            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10187        } catch (PackageParserException e) {
10188            res.returnCode = e.error;
10189            return;
10190        }
10191
10192        String pkgName = res.name = pkg.packageName;
10193        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10194            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10195                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10196                return;
10197            }
10198        }
10199
10200        try {
10201            pp.collectCertificates(pkg, parseFlags);
10202            pp.collectManifestDigest(pkg);
10203        } catch (PackageParserException e) {
10204            res.returnCode = e.error;
10205            return;
10206        }
10207
10208        /* If the installer passed in a manifest digest, compare it now. */
10209        if (args.manifestDigest != null) {
10210            if (DEBUG_INSTALL) {
10211                final String parsedManifest = pkg.manifestDigest == null ? "null"
10212                        : pkg.manifestDigest.toString();
10213                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10214                        + parsedManifest);
10215            }
10216
10217            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10218                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10219                return;
10220            }
10221        } else if (DEBUG_INSTALL) {
10222            final String parsedManifest = pkg.manifestDigest == null
10223                    ? "null" : pkg.manifestDigest.toString();
10224            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10225        }
10226
10227        // Get rid of all references to package scan path via parser.
10228        pp = null;
10229        String oldCodePath = null;
10230        boolean systemApp = false;
10231        synchronized (mPackages) {
10232            // Check whether the newly-scanned package wants to define an already-defined perm
10233            int N = pkg.permissions.size();
10234            for (int i = N-1; i >= 0; i--) {
10235                PackageParser.Permission perm = pkg.permissions.get(i);
10236                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10237                if (bp != null) {
10238                    // If the defining package is signed with our cert, it's okay.  This
10239                    // also includes the "updating the same package" case, of course.
10240                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10241                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10242                        // If the owning package is the system itself, we log but allow
10243                        // install to proceed; we fail the install on all other permission
10244                        // redefinitions.
10245                        if (!bp.sourcePackage.equals("android")) {
10246                            Slog.w(TAG, "Package " + pkg.packageName
10247                                    + " attempting to redeclare permission " + perm.info.name
10248                                    + " already owned by " + bp.sourcePackage);
10249                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10250                            res.origPermission = perm.info.name;
10251                            res.origPackage = bp.sourcePackage;
10252                            return;
10253                        } else {
10254                            Slog.w(TAG, "Package " + pkg.packageName
10255                                    + " attempting to redeclare system permission "
10256                                    + perm.info.name + "; ignoring new declaration");
10257                            pkg.permissions.remove(i);
10258                        }
10259                    }
10260                }
10261            }
10262
10263            // Check if installing already existing package
10264            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10265                String oldName = mSettings.mRenamedPackages.get(pkgName);
10266                if (pkg.mOriginalPackages != null
10267                        && pkg.mOriginalPackages.contains(oldName)
10268                        && mPackages.containsKey(oldName)) {
10269                    // This package is derived from an original package,
10270                    // and this device has been updating from that original
10271                    // name.  We must continue using the original name, so
10272                    // rename the new package here.
10273                    pkg.setPackageName(oldName);
10274                    pkgName = pkg.packageName;
10275                    replace = true;
10276                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10277                            + oldName + " pkgName=" + pkgName);
10278                } else if (mPackages.containsKey(pkgName)) {
10279                    // This package, under its official name, already exists
10280                    // on the device; we should replace it.
10281                    replace = true;
10282                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10283                }
10284            }
10285            PackageSetting ps = mSettings.mPackages.get(pkgName);
10286            if (ps != null) {
10287                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10288                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10289                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10290                    systemApp = (ps.pkg.applicationInfo.flags &
10291                            ApplicationInfo.FLAG_SYSTEM) != 0;
10292                }
10293                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10294            }
10295        }
10296
10297        if (systemApp && onSd) {
10298            // Disable updates to system apps on sdcard
10299            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10300            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10301            return;
10302        }
10303
10304        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10305            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10306            return;
10307        }
10308        // Set application objects path explicitly after the rename
10309        pkg.codePath = args.getCodePath();
10310        pkg.applicationInfo.sourceDir = args.getCodePath();
10311        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10312        pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths();
10313        pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths(
10314                pkg.applicationInfo.splitSourceDirs);
10315        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10316        if (replace) {
10317            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10318                    installerPackageName, res, args.abiOverride);
10319        } else {
10320            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10321                    installerPackageName, res, args.abiOverride);
10322        }
10323        synchronized (mPackages) {
10324            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10325            if (ps != null) {
10326                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10327            }
10328        }
10329    }
10330
10331    private static boolean isForwardLocked(PackageParser.Package pkg) {
10332        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10333    }
10334
10335
10336    private boolean isForwardLocked(PackageSetting ps) {
10337        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10338    }
10339
10340    private static boolean isExternal(PackageParser.Package pkg) {
10341        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10342    }
10343
10344    private static boolean isExternal(PackageSetting ps) {
10345        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10346    }
10347
10348    private static boolean isSystemApp(PackageParser.Package pkg) {
10349        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10350    }
10351
10352    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10353        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10354    }
10355
10356    private static boolean isSystemApp(ApplicationInfo info) {
10357        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10358    }
10359
10360    private static boolean isSystemApp(PackageSetting ps) {
10361        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10362    }
10363
10364    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10365        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10366    }
10367
10368    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10369        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10370    }
10371
10372    private int packageFlagsToInstallFlags(PackageSetting ps) {
10373        int installFlags = 0;
10374        if (isExternal(ps)) {
10375            installFlags |= PackageManager.INSTALL_EXTERNAL;
10376        }
10377        if (isForwardLocked(ps)) {
10378            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10379        }
10380        return installFlags;
10381    }
10382
10383    private void deleteTempPackageFiles() {
10384        final FilenameFilter filter = new FilenameFilter() {
10385            public boolean accept(File dir, String name) {
10386                return name.startsWith("vmdl") && name.endsWith(".tmp");
10387            }
10388        };
10389        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10390        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10391    }
10392
10393    private static final void deleteTempPackageFilesInDirectory(File directory,
10394            FilenameFilter filter) {
10395        final String[] tmpFilesList = directory.list(filter);
10396        if (tmpFilesList == null) {
10397            return;
10398        }
10399        for (int i = 0; i < tmpFilesList.length; i++) {
10400            final File tmpFile = new File(directory, tmpFilesList[i]);
10401            tmpFile.delete();
10402        }
10403    }
10404
10405    private File createTempPackageFile(File installDir) {
10406        File tmpPackageFile;
10407        try {
10408            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10409        } catch (IOException e) {
10410            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10411            return null;
10412        }
10413        try {
10414            FileUtils.setPermissions(
10415                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10416                    -1, -1);
10417            if (!SELinux.restorecon(tmpPackageFile)) {
10418                return null;
10419            }
10420        } catch (IOException e) {
10421            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10422            return null;
10423        }
10424        return tmpPackageFile;
10425    }
10426
10427    @Override
10428    public void deletePackageAsUser(final String packageName,
10429                                    final IPackageDeleteObserver observer,
10430                                    final int userId, final int flags) {
10431        mContext.enforceCallingOrSelfPermission(
10432                android.Manifest.permission.DELETE_PACKAGES, null);
10433        final int uid = Binder.getCallingUid();
10434        if (UserHandle.getUserId(uid) != userId) {
10435            mContext.enforceCallingPermission(
10436                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10437                    "deletePackage for user " + userId);
10438        }
10439        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10440            try {
10441                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10442            } catch (RemoteException re) {
10443            }
10444            return;
10445        }
10446
10447        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10448        // Queue up an async operation since the package deletion may take a little while.
10449        mHandler.post(new Runnable() {
10450            public void run() {
10451                mHandler.removeCallbacks(this);
10452                final int returnCode = deletePackageX(packageName, userId, flags);
10453                if (observer != null) {
10454                    try {
10455                        observer.packageDeleted(packageName, returnCode);
10456                    } catch (RemoteException e) {
10457                        Log.i(TAG, "Observer no longer exists.");
10458                    } //end catch
10459                } //end if
10460            } //end run
10461        });
10462    }
10463
10464    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10465        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10466                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10467        try {
10468            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10469                    || dpm.isDeviceOwner(packageName))) {
10470                return true;
10471            }
10472        } catch (RemoteException e) {
10473        }
10474        return false;
10475    }
10476
10477    /**
10478     *  This method is an internal method that could be get invoked either
10479     *  to delete an installed package or to clean up a failed installation.
10480     *  After deleting an installed package, a broadcast is sent to notify any
10481     *  listeners that the package has been installed. For cleaning up a failed
10482     *  installation, the broadcast is not necessary since the package's
10483     *  installation wouldn't have sent the initial broadcast either
10484     *  The key steps in deleting a package are
10485     *  deleting the package information in internal structures like mPackages,
10486     *  deleting the packages base directories through installd
10487     *  updating mSettings to reflect current status
10488     *  persisting settings for later use
10489     *  sending a broadcast if necessary
10490     */
10491    private int deletePackageX(String packageName, int userId, int flags) {
10492        final PackageRemovedInfo info = new PackageRemovedInfo();
10493        final boolean res;
10494
10495        if (isPackageDeviceAdmin(packageName, userId)) {
10496            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10497            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10498        }
10499
10500        boolean removedForAllUsers = false;
10501        boolean systemUpdate = false;
10502
10503        // for the uninstall-updates case and restricted profiles, remember the per-
10504        // userhandle installed state
10505        int[] allUsers;
10506        boolean[] perUserInstalled;
10507        synchronized (mPackages) {
10508            PackageSetting ps = mSettings.mPackages.get(packageName);
10509            allUsers = sUserManager.getUserIds();
10510            perUserInstalled = new boolean[allUsers.length];
10511            for (int i = 0; i < allUsers.length; i++) {
10512                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10513            }
10514        }
10515
10516        synchronized (mInstallLock) {
10517            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10518            res = deletePackageLI(packageName,
10519                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10520                            ? UserHandle.ALL : new UserHandle(userId),
10521                    true, allUsers, perUserInstalled,
10522                    flags | REMOVE_CHATTY, info, true);
10523            systemUpdate = info.isRemovedPackageSystemUpdate;
10524            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10525                removedForAllUsers = true;
10526            }
10527            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10528                    + " removedForAllUsers=" + removedForAllUsers);
10529        }
10530
10531        if (res) {
10532            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10533
10534            // If the removed package was a system update, the old system package
10535            // was re-enabled; we need to broadcast this information
10536            if (systemUpdate) {
10537                Bundle extras = new Bundle(1);
10538                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10539                        ? info.removedAppId : info.uid);
10540                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10541
10542                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10543                        extras, null, null, null);
10544                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10545                        extras, null, null, null);
10546                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10547                        null, packageName, null, null);
10548            }
10549        }
10550        // Force a gc here.
10551        Runtime.getRuntime().gc();
10552        // Delete the resources here after sending the broadcast to let
10553        // other processes clean up before deleting resources.
10554        if (info.args != null) {
10555            synchronized (mInstallLock) {
10556                info.args.doPostDeleteLI(true);
10557            }
10558        }
10559
10560        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10561    }
10562
10563    static class PackageRemovedInfo {
10564        String removedPackage;
10565        int uid = -1;
10566        int removedAppId = -1;
10567        int[] removedUsers = null;
10568        boolean isRemovedPackageSystemUpdate = false;
10569        // Clean up resources deleted packages.
10570        InstallArgs args = null;
10571
10572        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10573            Bundle extras = new Bundle(1);
10574            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10575            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10576            if (replacing) {
10577                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10578            }
10579            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10580            if (removedPackage != null) {
10581                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10582                        extras, null, null, removedUsers);
10583                if (fullRemove && !replacing) {
10584                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10585                            extras, null, null, removedUsers);
10586                }
10587            }
10588            if (removedAppId >= 0) {
10589                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10590                        removedUsers);
10591            }
10592        }
10593    }
10594
10595    /*
10596     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10597     * flag is not set, the data directory is removed as well.
10598     * make sure this flag is set for partially installed apps. If not its meaningless to
10599     * delete a partially installed application.
10600     */
10601    private void removePackageDataLI(PackageSetting ps,
10602            int[] allUserHandles, boolean[] perUserInstalled,
10603            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10604        String packageName = ps.name;
10605        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10606        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10607        // Retrieve object to delete permissions for shared user later on
10608        final PackageSetting deletedPs;
10609        // reader
10610        synchronized (mPackages) {
10611            deletedPs = mSettings.mPackages.get(packageName);
10612            if (outInfo != null) {
10613                outInfo.removedPackage = packageName;
10614                outInfo.removedUsers = deletedPs != null
10615                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10616                        : null;
10617            }
10618        }
10619        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10620            removeDataDirsLI(packageName);
10621            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10622        }
10623        // writer
10624        synchronized (mPackages) {
10625            if (deletedPs != null) {
10626                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10627                    if (outInfo != null) {
10628                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10629                    }
10630                    if (deletedPs != null) {
10631                        updatePermissionsLPw(deletedPs.name, null, 0);
10632                        if (deletedPs.sharedUser != null) {
10633                            // remove permissions associated with package
10634                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10635                        }
10636                    }
10637                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10638                }
10639                // make sure to preserve per-user disabled state if this removal was just
10640                // a downgrade of a system app to the factory package
10641                if (allUserHandles != null && perUserInstalled != null) {
10642                    if (DEBUG_REMOVE) {
10643                        Slog.d(TAG, "Propagating install state across downgrade");
10644                    }
10645                    for (int i = 0; i < allUserHandles.length; i++) {
10646                        if (DEBUG_REMOVE) {
10647                            Slog.d(TAG, "    user " + allUserHandles[i]
10648                                    + " => " + perUserInstalled[i]);
10649                        }
10650                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10651                    }
10652                }
10653            }
10654            // can downgrade to reader
10655            if (writeSettings) {
10656                // Save settings now
10657                mSettings.writeLPr();
10658            }
10659        }
10660        if (outInfo != null) {
10661            // A user ID was deleted here. Go through all users and remove it
10662            // from KeyStore.
10663            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10664        }
10665    }
10666
10667    static boolean locationIsPrivileged(File path) {
10668        try {
10669            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10670                    .getCanonicalPath();
10671            return path.getCanonicalPath().startsWith(privilegedAppDir);
10672        } catch (IOException e) {
10673            Slog.e(TAG, "Unable to access code path " + path);
10674        }
10675        return false;
10676    }
10677
10678    /*
10679     * Tries to delete system package.
10680     */
10681    private boolean deleteSystemPackageLI(PackageSetting newPs,
10682            int[] allUserHandles, boolean[] perUserInstalled,
10683            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10684        final boolean applyUserRestrictions
10685                = (allUserHandles != null) && (perUserInstalled != null);
10686        PackageSetting disabledPs = null;
10687        // Confirm if the system package has been updated
10688        // An updated system app can be deleted. This will also have to restore
10689        // the system pkg from system partition
10690        // reader
10691        synchronized (mPackages) {
10692            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10693        }
10694        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10695                + " disabledPs=" + disabledPs);
10696        if (disabledPs == null) {
10697            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10698            return false;
10699        } else if (DEBUG_REMOVE) {
10700            Slog.d(TAG, "Deleting system pkg from data partition");
10701        }
10702        if (DEBUG_REMOVE) {
10703            if (applyUserRestrictions) {
10704                Slog.d(TAG, "Remembering install states:");
10705                for (int i = 0; i < allUserHandles.length; i++) {
10706                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10707                }
10708            }
10709        }
10710        // Delete the updated package
10711        outInfo.isRemovedPackageSystemUpdate = true;
10712        if (disabledPs.versionCode < newPs.versionCode) {
10713            // Delete data for downgrades
10714            flags &= ~PackageManager.DELETE_KEEP_DATA;
10715        } else {
10716            // Preserve data by setting flag
10717            flags |= PackageManager.DELETE_KEEP_DATA;
10718        }
10719        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10720                allUserHandles, perUserInstalled, outInfo, writeSettings);
10721        if (!ret) {
10722            return false;
10723        }
10724        // writer
10725        synchronized (mPackages) {
10726            // Reinstate the old system package
10727            mSettings.enableSystemPackageLPw(newPs.name);
10728            // Remove any native libraries from the upgraded package.
10729            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10730        }
10731        // Install the system package
10732        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10733        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10734        if (locationIsPrivileged(disabledPs.codePath)) {
10735            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10736        }
10737        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10738                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10739
10740        if (newPkg == null) {
10741            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10742                    + " with error:" + mLastScanError);
10743            return false;
10744        }
10745        // writer
10746        synchronized (mPackages) {
10747            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10748            setInternalAppNativeLibraryPath(newPkg, ps);
10749            updatePermissionsLPw(newPkg.packageName, newPkg,
10750                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10751            if (applyUserRestrictions) {
10752                if (DEBUG_REMOVE) {
10753                    Slog.d(TAG, "Propagating install state across reinstall");
10754                }
10755                for (int i = 0; i < allUserHandles.length; i++) {
10756                    if (DEBUG_REMOVE) {
10757                        Slog.d(TAG, "    user " + allUserHandles[i]
10758                                + " => " + perUserInstalled[i]);
10759                    }
10760                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10761                }
10762                // Regardless of writeSettings we need to ensure that this restriction
10763                // state propagation is persisted
10764                mSettings.writeAllUsersPackageRestrictionsLPr();
10765            }
10766            // can downgrade to reader here
10767            if (writeSettings) {
10768                mSettings.writeLPr();
10769            }
10770        }
10771        return true;
10772    }
10773
10774    private boolean deleteInstalledPackageLI(PackageSetting ps,
10775            boolean deleteCodeAndResources, int flags,
10776            int[] allUserHandles, boolean[] perUserInstalled,
10777            PackageRemovedInfo outInfo, boolean writeSettings) {
10778        if (outInfo != null) {
10779            outInfo.uid = ps.appId;
10780        }
10781
10782        // Delete package data from internal structures and also remove data if flag is set
10783        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10784
10785        // Delete application code and resources
10786        if (deleteCodeAndResources && (outInfo != null)) {
10787            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10788                    ps.resourcePathString, ps.nativeLibraryPathString,
10789                    getAppInstructionSetFromSettings(ps));
10790        }
10791        return true;
10792    }
10793
10794    /*
10795     * This method handles package deletion in general
10796     */
10797    private boolean deletePackageLI(String packageName, UserHandle user,
10798            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10799            int flags, PackageRemovedInfo outInfo,
10800            boolean writeSettings) {
10801        if (packageName == null) {
10802            Slog.w(TAG, "Attempt to delete null packageName.");
10803            return false;
10804        }
10805        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10806        PackageSetting ps;
10807        boolean dataOnly = false;
10808        int removeUser = -1;
10809        int appId = -1;
10810        synchronized (mPackages) {
10811            ps = mSettings.mPackages.get(packageName);
10812            if (ps == null) {
10813                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10814                return false;
10815            }
10816            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10817                    && user.getIdentifier() != UserHandle.USER_ALL) {
10818                // The caller is asking that the package only be deleted for a single
10819                // user.  To do this, we just mark its uninstalled state and delete
10820                // its data.  If this is a system app, we only allow this to happen if
10821                // they have set the special DELETE_SYSTEM_APP which requests different
10822                // semantics than normal for uninstalling system apps.
10823                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10824                ps.setUserState(user.getIdentifier(),
10825                        COMPONENT_ENABLED_STATE_DEFAULT,
10826                        false, //installed
10827                        true,  //stopped
10828                        true,  //notLaunched
10829                        false, //blocked
10830                        null, null, null);
10831                if (!isSystemApp(ps)) {
10832                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10833                        // Other user still have this package installed, so all
10834                        // we need to do is clear this user's data and save that
10835                        // it is uninstalled.
10836                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10837                        removeUser = user.getIdentifier();
10838                        appId = ps.appId;
10839                        mSettings.writePackageRestrictionsLPr(removeUser);
10840                    } else {
10841                        // We need to set it back to 'installed' so the uninstall
10842                        // broadcasts will be sent correctly.
10843                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10844                        ps.setInstalled(true, user.getIdentifier());
10845                    }
10846                } else {
10847                    // This is a system app, so we assume that the
10848                    // other users still have this package installed, so all
10849                    // we need to do is clear this user's data and save that
10850                    // it is uninstalled.
10851                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10852                    removeUser = user.getIdentifier();
10853                    appId = ps.appId;
10854                    mSettings.writePackageRestrictionsLPr(removeUser);
10855                }
10856            }
10857        }
10858
10859        if (removeUser >= 0) {
10860            // From above, we determined that we are deleting this only
10861            // for a single user.  Continue the work here.
10862            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10863            if (outInfo != null) {
10864                outInfo.removedPackage = packageName;
10865                outInfo.removedAppId = appId;
10866                outInfo.removedUsers = new int[] {removeUser};
10867            }
10868            mInstaller.clearUserData(packageName, removeUser);
10869            removeKeystoreDataIfNeeded(removeUser, appId);
10870            schedulePackageCleaning(packageName, removeUser, false);
10871            return true;
10872        }
10873
10874        if (dataOnly) {
10875            // Delete application data first
10876            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10877            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10878            return true;
10879        }
10880
10881        boolean ret = false;
10882        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10883        if (isSystemApp(ps)) {
10884            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10885            // When an updated system application is deleted we delete the existing resources as well and
10886            // fall back to existing code in system partition
10887            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10888                    flags, outInfo, writeSettings);
10889        } else {
10890            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10891            // Kill application pre-emptively especially for apps on sd.
10892            killApplication(packageName, ps.appId, "uninstall pkg");
10893            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10894                    allUserHandles, perUserInstalled,
10895                    outInfo, writeSettings);
10896        }
10897
10898        return ret;
10899    }
10900
10901    private final class ClearStorageConnection implements ServiceConnection {
10902        IMediaContainerService mContainerService;
10903
10904        @Override
10905        public void onServiceConnected(ComponentName name, IBinder service) {
10906            synchronized (this) {
10907                mContainerService = IMediaContainerService.Stub.asInterface(service);
10908                notifyAll();
10909            }
10910        }
10911
10912        @Override
10913        public void onServiceDisconnected(ComponentName name) {
10914        }
10915    }
10916
10917    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10918        final boolean mounted;
10919        if (Environment.isExternalStorageEmulated()) {
10920            mounted = true;
10921        } else {
10922            final String status = Environment.getExternalStorageState();
10923
10924            mounted = status.equals(Environment.MEDIA_MOUNTED)
10925                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10926        }
10927
10928        if (!mounted) {
10929            return;
10930        }
10931
10932        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10933        int[] users;
10934        if (userId == UserHandle.USER_ALL) {
10935            users = sUserManager.getUserIds();
10936        } else {
10937            users = new int[] { userId };
10938        }
10939        final ClearStorageConnection conn = new ClearStorageConnection();
10940        if (mContext.bindServiceAsUser(
10941                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10942            try {
10943                for (int curUser : users) {
10944                    long timeout = SystemClock.uptimeMillis() + 5000;
10945                    synchronized (conn) {
10946                        long now = SystemClock.uptimeMillis();
10947                        while (conn.mContainerService == null && now < timeout) {
10948                            try {
10949                                conn.wait(timeout - now);
10950                            } catch (InterruptedException e) {
10951                            }
10952                        }
10953                    }
10954                    if (conn.mContainerService == null) {
10955                        return;
10956                    }
10957
10958                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10959                    clearDirectory(conn.mContainerService,
10960                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10961                    if (allData) {
10962                        clearDirectory(conn.mContainerService,
10963                                userEnv.buildExternalStorageAppDataDirs(packageName));
10964                        clearDirectory(conn.mContainerService,
10965                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10966                    }
10967                }
10968            } finally {
10969                mContext.unbindService(conn);
10970            }
10971        }
10972    }
10973
10974    @Override
10975    public void clearApplicationUserData(final String packageName,
10976            final IPackageDataObserver observer, final int userId) {
10977        mContext.enforceCallingOrSelfPermission(
10978                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10979        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10980        // Queue up an async operation since the package deletion may take a little while.
10981        mHandler.post(new Runnable() {
10982            public void run() {
10983                mHandler.removeCallbacks(this);
10984                final boolean succeeded;
10985                synchronized (mInstallLock) {
10986                    succeeded = clearApplicationUserDataLI(packageName, userId);
10987                }
10988                clearExternalStorageDataSync(packageName, userId, true);
10989                if (succeeded) {
10990                    // invoke DeviceStorageMonitor's update method to clear any notifications
10991                    DeviceStorageMonitorInternal
10992                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10993                    if (dsm != null) {
10994                        dsm.checkMemory();
10995                    }
10996                }
10997                if(observer != null) {
10998                    try {
10999                        observer.onRemoveCompleted(packageName, succeeded);
11000                    } catch (RemoteException e) {
11001                        Log.i(TAG, "Observer no longer exists.");
11002                    }
11003                } //end if observer
11004            } //end run
11005        });
11006    }
11007
11008    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11009        if (packageName == null) {
11010            Slog.w(TAG, "Attempt to delete null packageName.");
11011            return false;
11012        }
11013        PackageParser.Package p;
11014        boolean dataOnly = false;
11015        final int appId;
11016        synchronized (mPackages) {
11017            p = mPackages.get(packageName);
11018            if (p == null) {
11019                dataOnly = true;
11020                PackageSetting ps = mSettings.mPackages.get(packageName);
11021                if ((ps == null) || (ps.pkg == null)) {
11022                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11023                    return false;
11024                }
11025                p = ps.pkg;
11026            }
11027            if (!dataOnly) {
11028                // need to check this only for fully installed applications
11029                if (p == null) {
11030                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11031                    return false;
11032                }
11033                final ApplicationInfo applicationInfo = p.applicationInfo;
11034                if (applicationInfo == null) {
11035                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11036                    return false;
11037                }
11038            }
11039            if (p != null && p.applicationInfo != null) {
11040                appId = p.applicationInfo.uid;
11041            } else {
11042                appId = -1;
11043            }
11044        }
11045        int retCode = mInstaller.clearUserData(packageName, userId);
11046        if (retCode < 0) {
11047            Slog.w(TAG, "Couldn't remove cache files for package: "
11048                    + packageName);
11049            return false;
11050        }
11051        removeKeystoreDataIfNeeded(userId, appId);
11052        return true;
11053    }
11054
11055    /**
11056     * Remove entries from the keystore daemon. Will only remove it if the
11057     * {@code appId} is valid.
11058     */
11059    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11060        if (appId < 0) {
11061            return;
11062        }
11063
11064        final KeyStore keyStore = KeyStore.getInstance();
11065        if (keyStore != null) {
11066            if (userId == UserHandle.USER_ALL) {
11067                for (final int individual : sUserManager.getUserIds()) {
11068                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11069                }
11070            } else {
11071                keyStore.clearUid(UserHandle.getUid(userId, appId));
11072            }
11073        } else {
11074            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11075        }
11076    }
11077
11078    @Override
11079    public void deleteApplicationCacheFiles(final String packageName,
11080            final IPackageDataObserver observer) {
11081        mContext.enforceCallingOrSelfPermission(
11082                android.Manifest.permission.DELETE_CACHE_FILES, null);
11083        // Queue up an async operation since the package deletion may take a little while.
11084        final int userId = UserHandle.getCallingUserId();
11085        mHandler.post(new Runnable() {
11086            public void run() {
11087                mHandler.removeCallbacks(this);
11088                final boolean succeded;
11089                synchronized (mInstallLock) {
11090                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11091                }
11092                clearExternalStorageDataSync(packageName, userId, false);
11093                if(observer != null) {
11094                    try {
11095                        observer.onRemoveCompleted(packageName, succeded);
11096                    } catch (RemoteException e) {
11097                        Log.i(TAG, "Observer no longer exists.");
11098                    }
11099                } //end if observer
11100            } //end run
11101        });
11102    }
11103
11104    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11105        if (packageName == null) {
11106            Slog.w(TAG, "Attempt to delete null packageName.");
11107            return false;
11108        }
11109        PackageParser.Package p;
11110        synchronized (mPackages) {
11111            p = mPackages.get(packageName);
11112        }
11113        if (p == null) {
11114            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11115            return false;
11116        }
11117        final ApplicationInfo applicationInfo = p.applicationInfo;
11118        if (applicationInfo == null) {
11119            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11120            return false;
11121        }
11122        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11123        if (retCode < 0) {
11124            Slog.w(TAG, "Couldn't remove cache files for package: "
11125                       + packageName + " u" + userId);
11126            return false;
11127        }
11128        return true;
11129    }
11130
11131    @Override
11132    public void getPackageSizeInfo(final String packageName, int userHandle,
11133            final IPackageStatsObserver observer) {
11134        mContext.enforceCallingOrSelfPermission(
11135                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11136        if (packageName == null) {
11137            throw new IllegalArgumentException("Attempt to get size of null packageName");
11138        }
11139
11140        PackageStats stats = new PackageStats(packageName, userHandle);
11141
11142        /*
11143         * Queue up an async operation since the package measurement may take a
11144         * little while.
11145         */
11146        Message msg = mHandler.obtainMessage(INIT_COPY);
11147        msg.obj = new MeasureParams(stats, observer);
11148        mHandler.sendMessage(msg);
11149    }
11150
11151    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11152            PackageStats pStats) {
11153        if (packageName == null) {
11154            Slog.w(TAG, "Attempt to get size of null packageName.");
11155            return false;
11156        }
11157        PackageParser.Package p;
11158        boolean dataOnly = false;
11159        String libDirPath = null;
11160        String asecPath = null;
11161        PackageSetting ps = null;
11162        synchronized (mPackages) {
11163            p = mPackages.get(packageName);
11164            ps = mSettings.mPackages.get(packageName);
11165            if(p == null) {
11166                dataOnly = true;
11167                if((ps == null) || (ps.pkg == null)) {
11168                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11169                    return false;
11170                }
11171                p = ps.pkg;
11172            }
11173            if (ps != null) {
11174                libDirPath = ps.nativeLibraryPathString;
11175            }
11176            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11177                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11178                if (secureContainerId != null) {
11179                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11180                }
11181            }
11182        }
11183        String publicSrcDir = null;
11184        if(!dataOnly) {
11185            final ApplicationInfo applicationInfo = p.applicationInfo;
11186            if (applicationInfo == null) {
11187                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11188                return false;
11189            }
11190            if (isForwardLocked(p)) {
11191                publicSrcDir = applicationInfo.publicSourceDir;
11192            }
11193        }
11194        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11195                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11196                pStats);
11197        if (res < 0) {
11198            return false;
11199        }
11200
11201        // Fix-up for forward-locked applications in ASEC containers.
11202        if (!isExternal(p)) {
11203            pStats.codeSize += pStats.externalCodeSize;
11204            pStats.externalCodeSize = 0L;
11205        }
11206
11207        return true;
11208    }
11209
11210
11211    @Override
11212    public void addPackageToPreferred(String packageName) {
11213        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11214    }
11215
11216    @Override
11217    public void removePackageFromPreferred(String packageName) {
11218        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11219    }
11220
11221    @Override
11222    public List<PackageInfo> getPreferredPackages(int flags) {
11223        return new ArrayList<PackageInfo>();
11224    }
11225
11226    private int getUidTargetSdkVersionLockedLPr(int uid) {
11227        Object obj = mSettings.getUserIdLPr(uid);
11228        if (obj instanceof SharedUserSetting) {
11229            final SharedUserSetting sus = (SharedUserSetting) obj;
11230            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11231            final Iterator<PackageSetting> it = sus.packages.iterator();
11232            while (it.hasNext()) {
11233                final PackageSetting ps = it.next();
11234                if (ps.pkg != null) {
11235                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11236                    if (v < vers) vers = v;
11237                }
11238            }
11239            return vers;
11240        } else if (obj instanceof PackageSetting) {
11241            final PackageSetting ps = (PackageSetting) obj;
11242            if (ps.pkg != null) {
11243                return ps.pkg.applicationInfo.targetSdkVersion;
11244            }
11245        }
11246        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11247    }
11248
11249    @Override
11250    public void addPreferredActivity(IntentFilter filter, int match,
11251            ComponentName[] set, ComponentName activity, int userId) {
11252        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11253    }
11254
11255    private void addPreferredActivityInternal(IntentFilter filter, int match,
11256            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11257        // writer
11258        int callingUid = Binder.getCallingUid();
11259        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11260        if (filter.countActions() == 0) {
11261            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11262            return;
11263        }
11264        synchronized (mPackages) {
11265            if (mContext.checkCallingOrSelfPermission(
11266                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11267                    != PackageManager.PERMISSION_GRANTED) {
11268                if (getUidTargetSdkVersionLockedLPr(callingUid)
11269                        < Build.VERSION_CODES.FROYO) {
11270                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11271                            + callingUid);
11272                    return;
11273                }
11274                mContext.enforceCallingOrSelfPermission(
11275                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11276            }
11277
11278            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11279            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11280            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11281                    new PreferredActivity(filter, match, set, activity, always));
11282            mSettings.writePackageRestrictionsLPr(userId);
11283        }
11284    }
11285
11286    @Override
11287    public void replacePreferredActivity(IntentFilter filter, int match,
11288            ComponentName[] set, ComponentName activity) {
11289        if (filter.countActions() != 1) {
11290            throw new IllegalArgumentException(
11291                    "replacePreferredActivity expects filter to have only 1 action.");
11292        }
11293        if (filter.countDataAuthorities() != 0
11294                || filter.countDataPaths() != 0
11295                || filter.countDataSchemes() > 1
11296                || filter.countDataTypes() != 0) {
11297            throw new IllegalArgumentException(
11298                    "replacePreferredActivity expects filter to have no data authorities, " +
11299                    "paths, or types; and at most one scheme.");
11300        }
11301        synchronized (mPackages) {
11302            if (mContext.checkCallingOrSelfPermission(
11303                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11304                    != PackageManager.PERMISSION_GRANTED) {
11305                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11306                        < Build.VERSION_CODES.FROYO) {
11307                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11308                            + Binder.getCallingUid());
11309                    return;
11310                }
11311                mContext.enforceCallingOrSelfPermission(
11312                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11313            }
11314
11315            final int callingUserId = UserHandle.getCallingUserId();
11316            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11317            if (pir != null) {
11318                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11319                if (filter.countDataSchemes() == 1) {
11320                    Uri.Builder builder = new Uri.Builder();
11321                    builder.scheme(filter.getDataScheme(0));
11322                    intent.setData(builder.build());
11323                }
11324                List<PreferredActivity> matches = pir.queryIntent(
11325                        intent, null, true, callingUserId);
11326                if (DEBUG_PREFERRED) {
11327                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11328                }
11329                for (int i = 0; i < matches.size(); i++) {
11330                    PreferredActivity pa = matches.get(i);
11331                    if (DEBUG_PREFERRED) {
11332                        Slog.i(TAG, "Removing preferred activity "
11333                                + pa.mPref.mComponent + ":");
11334                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11335                    }
11336                    pir.removeFilter(pa);
11337                }
11338            }
11339            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11340        }
11341    }
11342
11343    @Override
11344    public void clearPackagePreferredActivities(String packageName) {
11345        final int uid = Binder.getCallingUid();
11346        // writer
11347        synchronized (mPackages) {
11348            PackageParser.Package pkg = mPackages.get(packageName);
11349            if (pkg == null || pkg.applicationInfo.uid != uid) {
11350                if (mContext.checkCallingOrSelfPermission(
11351                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11352                        != PackageManager.PERMISSION_GRANTED) {
11353                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11354                            < Build.VERSION_CODES.FROYO) {
11355                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11356                                + Binder.getCallingUid());
11357                        return;
11358                    }
11359                    mContext.enforceCallingOrSelfPermission(
11360                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11361                }
11362            }
11363
11364            int user = UserHandle.getCallingUserId();
11365            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11366                mSettings.writePackageRestrictionsLPr(user);
11367                scheduleWriteSettingsLocked();
11368            }
11369        }
11370    }
11371
11372    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11373    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11374        ArrayList<PreferredActivity> removed = null;
11375        boolean changed = false;
11376        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11377            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11378            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11379            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11380                continue;
11381            }
11382            Iterator<PreferredActivity> it = pir.filterIterator();
11383            while (it.hasNext()) {
11384                PreferredActivity pa = it.next();
11385                // Mark entry for removal only if it matches the package name
11386                // and the entry is of type "always".
11387                if (packageName == null ||
11388                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11389                                && pa.mPref.mAlways)) {
11390                    if (removed == null) {
11391                        removed = new ArrayList<PreferredActivity>();
11392                    }
11393                    removed.add(pa);
11394                }
11395            }
11396            if (removed != null) {
11397                for (int j=0; j<removed.size(); j++) {
11398                    PreferredActivity pa = removed.get(j);
11399                    pir.removeFilter(pa);
11400                }
11401                changed = true;
11402            }
11403        }
11404        return changed;
11405    }
11406
11407    @Override
11408    public void resetPreferredActivities(int userId) {
11409        mContext.enforceCallingOrSelfPermission(
11410                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11411        // writer
11412        synchronized (mPackages) {
11413            int user = UserHandle.getCallingUserId();
11414            clearPackagePreferredActivitiesLPw(null, user);
11415            mSettings.readDefaultPreferredAppsLPw(this, user);
11416            mSettings.writePackageRestrictionsLPr(user);
11417            scheduleWriteSettingsLocked();
11418        }
11419    }
11420
11421    @Override
11422    public int getPreferredActivities(List<IntentFilter> outFilters,
11423            List<ComponentName> outActivities, String packageName) {
11424
11425        int num = 0;
11426        final int userId = UserHandle.getCallingUserId();
11427        // reader
11428        synchronized (mPackages) {
11429            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11430            if (pir != null) {
11431                final Iterator<PreferredActivity> it = pir.filterIterator();
11432                while (it.hasNext()) {
11433                    final PreferredActivity pa = it.next();
11434                    if (packageName == null
11435                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11436                                    && pa.mPref.mAlways)) {
11437                        if (outFilters != null) {
11438                            outFilters.add(new IntentFilter(pa));
11439                        }
11440                        if (outActivities != null) {
11441                            outActivities.add(pa.mPref.mComponent);
11442                        }
11443                    }
11444                }
11445            }
11446        }
11447
11448        return num;
11449    }
11450
11451    @Override
11452    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11453            int userId) {
11454        int callingUid = Binder.getCallingUid();
11455        if (callingUid != Process.SYSTEM_UID) {
11456            throw new SecurityException(
11457                    "addPersistentPreferredActivity can only be run by the system");
11458        }
11459        if (filter.countActions() == 0) {
11460            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11461            return;
11462        }
11463        synchronized (mPackages) {
11464            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11465                    " :");
11466            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11467            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11468                    new PersistentPreferredActivity(filter, activity));
11469            mSettings.writePackageRestrictionsLPr(userId);
11470        }
11471    }
11472
11473    @Override
11474    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11475        int callingUid = Binder.getCallingUid();
11476        if (callingUid != Process.SYSTEM_UID) {
11477            throw new SecurityException(
11478                    "clearPackagePersistentPreferredActivities can only be run by the system");
11479        }
11480        ArrayList<PersistentPreferredActivity> removed = null;
11481        boolean changed = false;
11482        synchronized (mPackages) {
11483            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11484                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11485                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11486                        .valueAt(i);
11487                if (userId != thisUserId) {
11488                    continue;
11489                }
11490                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11491                while (it.hasNext()) {
11492                    PersistentPreferredActivity ppa = it.next();
11493                    // Mark entry for removal only if it matches the package name.
11494                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11495                        if (removed == null) {
11496                            removed = new ArrayList<PersistentPreferredActivity>();
11497                        }
11498                        removed.add(ppa);
11499                    }
11500                }
11501                if (removed != null) {
11502                    for (int j=0; j<removed.size(); j++) {
11503                        PersistentPreferredActivity ppa = removed.get(j);
11504                        ppir.removeFilter(ppa);
11505                    }
11506                    changed = true;
11507                }
11508            }
11509
11510            if (changed) {
11511                mSettings.writePackageRestrictionsLPr(userId);
11512            }
11513        }
11514    }
11515
11516    @Override
11517    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11518            int targetUserId, int flags) {
11519        mContext.enforceCallingOrSelfPermission(
11520                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11521        if (intentFilter.countActions() == 0) {
11522            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11523            return;
11524        }
11525        synchronized (mPackages) {
11526            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11527                    targetUserId, flags);
11528            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11529            mSettings.writePackageRestrictionsLPr(sourceUserId);
11530        }
11531    }
11532
11533    public void addCrossProfileIntentsForPackage(String packageName,
11534            int sourceUserId, int targetUserId) {
11535        mContext.enforceCallingOrSelfPermission(
11536                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11537        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11538        mSettings.writePackageRestrictionsLPr(sourceUserId);
11539    }
11540
11541    public void removeCrossProfileIntentsForPackage(String packageName,
11542            int sourceUserId, int targetUserId) {
11543        mContext.enforceCallingOrSelfPermission(
11544                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11545        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11546        mSettings.writePackageRestrictionsLPr(sourceUserId);
11547    }
11548
11549    @Override
11550    public void clearCrossProfileIntentFilters(int sourceUserId) {
11551        mContext.enforceCallingOrSelfPermission(
11552                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11553        synchronized (mPackages) {
11554            CrossProfileIntentResolver resolver =
11555                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11556            HashSet<CrossProfileIntentFilter> set =
11557                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11558            for (CrossProfileIntentFilter filter : set) {
11559                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11560                    resolver.removeFilter(filter);
11561                }
11562            }
11563            mSettings.writePackageRestrictionsLPr(sourceUserId);
11564        }
11565    }
11566
11567    @Override
11568    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11569        Intent intent = new Intent(Intent.ACTION_MAIN);
11570        intent.addCategory(Intent.CATEGORY_HOME);
11571
11572        final int callingUserId = UserHandle.getCallingUserId();
11573        List<ResolveInfo> list = queryIntentActivities(intent, null,
11574                PackageManager.GET_META_DATA, callingUserId);
11575        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11576                true, false, false, callingUserId);
11577
11578        allHomeCandidates.clear();
11579        if (list != null) {
11580            for (ResolveInfo ri : list) {
11581                allHomeCandidates.add(ri);
11582            }
11583        }
11584        return (preferred == null || preferred.activityInfo == null)
11585                ? null
11586                : new ComponentName(preferred.activityInfo.packageName,
11587                        preferred.activityInfo.name);
11588    }
11589
11590    @Override
11591    public void setApplicationEnabledSetting(String appPackageName,
11592            int newState, int flags, int userId, String callingPackage) {
11593        if (!sUserManager.exists(userId)) return;
11594        if (callingPackage == null) {
11595            callingPackage = Integer.toString(Binder.getCallingUid());
11596        }
11597        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11598    }
11599
11600    @Override
11601    public void setComponentEnabledSetting(ComponentName componentName,
11602            int newState, int flags, int userId) {
11603        if (!sUserManager.exists(userId)) return;
11604        setEnabledSetting(componentName.getPackageName(),
11605                componentName.getClassName(), newState, flags, userId, null);
11606    }
11607
11608    private void setEnabledSetting(final String packageName, String className, int newState,
11609            final int flags, int userId, String callingPackage) {
11610        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11611              || newState == COMPONENT_ENABLED_STATE_ENABLED
11612              || newState == COMPONENT_ENABLED_STATE_DISABLED
11613              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11614              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11615            throw new IllegalArgumentException("Invalid new component state: "
11616                    + newState);
11617        }
11618        PackageSetting pkgSetting;
11619        final int uid = Binder.getCallingUid();
11620        final int permission = mContext.checkCallingOrSelfPermission(
11621                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11622        enforceCrossUserPermission(uid, userId, false, "set enabled");
11623        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11624        boolean sendNow = false;
11625        boolean isApp = (className == null);
11626        String componentName = isApp ? packageName : className;
11627        int packageUid = -1;
11628        ArrayList<String> components;
11629
11630        // writer
11631        synchronized (mPackages) {
11632            pkgSetting = mSettings.mPackages.get(packageName);
11633            if (pkgSetting == null) {
11634                if (className == null) {
11635                    throw new IllegalArgumentException(
11636                            "Unknown package: " + packageName);
11637                }
11638                throw new IllegalArgumentException(
11639                        "Unknown component: " + packageName
11640                        + "/" + className);
11641            }
11642            // Allow root and verify that userId is not being specified by a different user
11643            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11644                throw new SecurityException(
11645                        "Permission Denial: attempt to change component state from pid="
11646                        + Binder.getCallingPid()
11647                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11648            }
11649            if (className == null) {
11650                // We're dealing with an application/package level state change
11651                if (pkgSetting.getEnabled(userId) == newState) {
11652                    // Nothing to do
11653                    return;
11654                }
11655                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11656                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11657                    // Don't care about who enables an app.
11658                    callingPackage = null;
11659                }
11660                pkgSetting.setEnabled(newState, userId, callingPackage);
11661                // pkgSetting.pkg.mSetEnabled = newState;
11662            } else {
11663                // We're dealing with a component level state change
11664                // First, verify that this is a valid class name.
11665                PackageParser.Package pkg = pkgSetting.pkg;
11666                if (pkg == null || !pkg.hasComponentClassName(className)) {
11667                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11668                        throw new IllegalArgumentException("Component class " + className
11669                                + " does not exist in " + packageName);
11670                    } else {
11671                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11672                                + className + " does not exist in " + packageName);
11673                    }
11674                }
11675                switch (newState) {
11676                case COMPONENT_ENABLED_STATE_ENABLED:
11677                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11678                        return;
11679                    }
11680                    break;
11681                case COMPONENT_ENABLED_STATE_DISABLED:
11682                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11683                        return;
11684                    }
11685                    break;
11686                case COMPONENT_ENABLED_STATE_DEFAULT:
11687                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11688                        return;
11689                    }
11690                    break;
11691                default:
11692                    Slog.e(TAG, "Invalid new component state: " + newState);
11693                    return;
11694                }
11695            }
11696            mSettings.writePackageRestrictionsLPr(userId);
11697            components = mPendingBroadcasts.get(userId, packageName);
11698            final boolean newPackage = components == null;
11699            if (newPackage) {
11700                components = new ArrayList<String>();
11701            }
11702            if (!components.contains(componentName)) {
11703                components.add(componentName);
11704            }
11705            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11706                sendNow = true;
11707                // Purge entry from pending broadcast list if another one exists already
11708                // since we are sending one right away.
11709                mPendingBroadcasts.remove(userId, packageName);
11710            } else {
11711                if (newPackage) {
11712                    mPendingBroadcasts.put(userId, packageName, components);
11713                }
11714                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11715                    // Schedule a message
11716                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11717                }
11718            }
11719        }
11720
11721        long callingId = Binder.clearCallingIdentity();
11722        try {
11723            if (sendNow) {
11724                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11725                sendPackageChangedBroadcast(packageName,
11726                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11727            }
11728        } finally {
11729            Binder.restoreCallingIdentity(callingId);
11730        }
11731    }
11732
11733    private void sendPackageChangedBroadcast(String packageName,
11734            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11735        if (DEBUG_INSTALL)
11736            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11737                    + componentNames);
11738        Bundle extras = new Bundle(4);
11739        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11740        String nameList[] = new String[componentNames.size()];
11741        componentNames.toArray(nameList);
11742        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11743        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11744        extras.putInt(Intent.EXTRA_UID, packageUid);
11745        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11746                new int[] {UserHandle.getUserId(packageUid)});
11747    }
11748
11749    @Override
11750    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11751        if (!sUserManager.exists(userId)) return;
11752        final int uid = Binder.getCallingUid();
11753        final int permission = mContext.checkCallingOrSelfPermission(
11754                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11755        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11756        enforceCrossUserPermission(uid, userId, true, "stop package");
11757        // writer
11758        synchronized (mPackages) {
11759            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11760                    uid, userId)) {
11761                scheduleWritePackageRestrictionsLocked(userId);
11762            }
11763        }
11764    }
11765
11766    @Override
11767    public String getInstallerPackageName(String packageName) {
11768        // reader
11769        synchronized (mPackages) {
11770            return mSettings.getInstallerPackageNameLPr(packageName);
11771        }
11772    }
11773
11774    @Override
11775    public int getApplicationEnabledSetting(String packageName, int userId) {
11776        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11777        int uid = Binder.getCallingUid();
11778        enforceCrossUserPermission(uid, userId, false, "get enabled");
11779        // reader
11780        synchronized (mPackages) {
11781            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11782        }
11783    }
11784
11785    @Override
11786    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11787        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11788        int uid = Binder.getCallingUid();
11789        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11790        // reader
11791        synchronized (mPackages) {
11792            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11793        }
11794    }
11795
11796    @Override
11797    public void enterSafeMode() {
11798        enforceSystemOrRoot("Only the system can request entering safe mode");
11799
11800        if (!mSystemReady) {
11801            mSafeMode = true;
11802        }
11803    }
11804
11805    @Override
11806    public void systemReady() {
11807        mSystemReady = true;
11808
11809        // Read the compatibilty setting when the system is ready.
11810        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11811                mContext.getContentResolver(),
11812                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11813        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11814        if (DEBUG_SETTINGS) {
11815            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11816        }
11817
11818        synchronized (mPackages) {
11819            // Verify that all of the preferred activity components actually
11820            // exist.  It is possible for applications to be updated and at
11821            // that point remove a previously declared activity component that
11822            // had been set as a preferred activity.  We try to clean this up
11823            // the next time we encounter that preferred activity, but it is
11824            // possible for the user flow to never be able to return to that
11825            // situation so here we do a sanity check to make sure we haven't
11826            // left any junk around.
11827            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11828            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11829                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11830                removed.clear();
11831                for (PreferredActivity pa : pir.filterSet()) {
11832                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11833                        removed.add(pa);
11834                    }
11835                }
11836                if (removed.size() > 0) {
11837                    for (int r=0; r<removed.size(); r++) {
11838                        PreferredActivity pa = removed.get(r);
11839                        Slog.w(TAG, "Removing dangling preferred activity: "
11840                                + pa.mPref.mComponent);
11841                        pir.removeFilter(pa);
11842                    }
11843                    mSettings.writePackageRestrictionsLPr(
11844                            mSettings.mPreferredActivities.keyAt(i));
11845                }
11846            }
11847        }
11848        sUserManager.systemReady();
11849    }
11850
11851    @Override
11852    public boolean isSafeMode() {
11853        return mSafeMode;
11854    }
11855
11856    @Override
11857    public boolean hasSystemUidErrors() {
11858        return mHasSystemUidErrors;
11859    }
11860
11861    static String arrayToString(int[] array) {
11862        StringBuffer buf = new StringBuffer(128);
11863        buf.append('[');
11864        if (array != null) {
11865            for (int i=0; i<array.length; i++) {
11866                if (i > 0) buf.append(", ");
11867                buf.append(array[i]);
11868            }
11869        }
11870        buf.append(']');
11871        return buf.toString();
11872    }
11873
11874    static class DumpState {
11875        public static final int DUMP_LIBS = 1 << 0;
11876
11877        public static final int DUMP_FEATURES = 1 << 1;
11878
11879        public static final int DUMP_RESOLVERS = 1 << 2;
11880
11881        public static final int DUMP_PERMISSIONS = 1 << 3;
11882
11883        public static final int DUMP_PACKAGES = 1 << 4;
11884
11885        public static final int DUMP_SHARED_USERS = 1 << 5;
11886
11887        public static final int DUMP_MESSAGES = 1 << 6;
11888
11889        public static final int DUMP_PROVIDERS = 1 << 7;
11890
11891        public static final int DUMP_VERIFIERS = 1 << 8;
11892
11893        public static final int DUMP_PREFERRED = 1 << 9;
11894
11895        public static final int DUMP_PREFERRED_XML = 1 << 10;
11896
11897        public static final int DUMP_KEYSETS = 1 << 11;
11898
11899        public static final int DUMP_VERSION = 1 << 12;
11900
11901        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11902
11903        private int mTypes;
11904
11905        private int mOptions;
11906
11907        private boolean mTitlePrinted;
11908
11909        private SharedUserSetting mSharedUser;
11910
11911        public boolean isDumping(int type) {
11912            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11913                return true;
11914            }
11915
11916            return (mTypes & type) != 0;
11917        }
11918
11919        public void setDump(int type) {
11920            mTypes |= type;
11921        }
11922
11923        public boolean isOptionEnabled(int option) {
11924            return (mOptions & option) != 0;
11925        }
11926
11927        public void setOptionEnabled(int option) {
11928            mOptions |= option;
11929        }
11930
11931        public boolean onTitlePrinted() {
11932            final boolean printed = mTitlePrinted;
11933            mTitlePrinted = true;
11934            return printed;
11935        }
11936
11937        public boolean getTitlePrinted() {
11938            return mTitlePrinted;
11939        }
11940
11941        public void setTitlePrinted(boolean enabled) {
11942            mTitlePrinted = enabled;
11943        }
11944
11945        public SharedUserSetting getSharedUser() {
11946            return mSharedUser;
11947        }
11948
11949        public void setSharedUser(SharedUserSetting user) {
11950            mSharedUser = user;
11951        }
11952    }
11953
11954    @Override
11955    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11956        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11957                != PackageManager.PERMISSION_GRANTED) {
11958            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11959                    + Binder.getCallingPid()
11960                    + ", uid=" + Binder.getCallingUid()
11961                    + " without permission "
11962                    + android.Manifest.permission.DUMP);
11963            return;
11964        }
11965
11966        DumpState dumpState = new DumpState();
11967        boolean fullPreferred = false;
11968        boolean checkin = false;
11969
11970        String packageName = null;
11971
11972        int opti = 0;
11973        while (opti < args.length) {
11974            String opt = args[opti];
11975            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11976                break;
11977            }
11978            opti++;
11979            if ("-a".equals(opt)) {
11980                // Right now we only know how to print all.
11981            } else if ("-h".equals(opt)) {
11982                pw.println("Package manager dump options:");
11983                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11984                pw.println("    --checkin: dump for a checkin");
11985                pw.println("    -f: print details of intent filters");
11986                pw.println("    -h: print this help");
11987                pw.println("  cmd may be one of:");
11988                pw.println("    l[ibraries]: list known shared libraries");
11989                pw.println("    f[ibraries]: list device features");
11990                pw.println("    k[eysets]: print known keysets");
11991                pw.println("    r[esolvers]: dump intent resolvers");
11992                pw.println("    perm[issions]: dump permissions");
11993                pw.println("    pref[erred]: print preferred package settings");
11994                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11995                pw.println("    prov[iders]: dump content providers");
11996                pw.println("    p[ackages]: dump installed packages");
11997                pw.println("    s[hared-users]: dump shared user IDs");
11998                pw.println("    m[essages]: print collected runtime messages");
11999                pw.println("    v[erifiers]: print package verifier info");
12000                pw.println("    version: print database version info");
12001                pw.println("    write: write current settings now");
12002                pw.println("    <package.name>: info about given package");
12003                return;
12004            } else if ("--checkin".equals(opt)) {
12005                checkin = true;
12006            } else if ("-f".equals(opt)) {
12007                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12008            } else {
12009                pw.println("Unknown argument: " + opt + "; use -h for help");
12010            }
12011        }
12012
12013        // Is the caller requesting to dump a particular piece of data?
12014        if (opti < args.length) {
12015            String cmd = args[opti];
12016            opti++;
12017            // Is this a package name?
12018            if ("android".equals(cmd) || cmd.contains(".")) {
12019                packageName = cmd;
12020                // When dumping a single package, we always dump all of its
12021                // filter information since the amount of data will be reasonable.
12022                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12023            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12024                dumpState.setDump(DumpState.DUMP_LIBS);
12025            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12026                dumpState.setDump(DumpState.DUMP_FEATURES);
12027            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12028                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12029            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12030                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12031            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12032                dumpState.setDump(DumpState.DUMP_PREFERRED);
12033            } else if ("preferred-xml".equals(cmd)) {
12034                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12035                if (opti < args.length && "--full".equals(args[opti])) {
12036                    fullPreferred = true;
12037                    opti++;
12038                }
12039            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12040                dumpState.setDump(DumpState.DUMP_PACKAGES);
12041            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12042                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12043            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12044                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12045            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12046                dumpState.setDump(DumpState.DUMP_MESSAGES);
12047            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12048                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12049            } else if ("version".equals(cmd)) {
12050                dumpState.setDump(DumpState.DUMP_VERSION);
12051            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12052                dumpState.setDump(DumpState.DUMP_KEYSETS);
12053            } else if ("write".equals(cmd)) {
12054                synchronized (mPackages) {
12055                    mSettings.writeLPr();
12056                    pw.println("Settings written.");
12057                    return;
12058                }
12059            }
12060        }
12061
12062        if (checkin) {
12063            pw.println("vers,1");
12064        }
12065
12066        // reader
12067        synchronized (mPackages) {
12068            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12069                if (!checkin) {
12070                    if (dumpState.onTitlePrinted())
12071                        pw.println();
12072                    pw.println("Database versions:");
12073                    pw.print("  SDK Version:");
12074                    pw.print(" internal=");
12075                    pw.print(mSettings.mInternalSdkPlatform);
12076                    pw.print(" external=");
12077                    pw.println(mSettings.mExternalSdkPlatform);
12078                    pw.print("  DB Version:");
12079                    pw.print(" internal=");
12080                    pw.print(mSettings.mInternalDatabaseVersion);
12081                    pw.print(" external=");
12082                    pw.println(mSettings.mExternalDatabaseVersion);
12083                }
12084            }
12085
12086            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12087                if (!checkin) {
12088                    if (dumpState.onTitlePrinted())
12089                        pw.println();
12090                    pw.println("Verifiers:");
12091                    pw.print("  Required: ");
12092                    pw.print(mRequiredVerifierPackage);
12093                    pw.print(" (uid=");
12094                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12095                    pw.println(")");
12096                } else if (mRequiredVerifierPackage != null) {
12097                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12098                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12099                }
12100            }
12101
12102            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12103                boolean printedHeader = false;
12104                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12105                while (it.hasNext()) {
12106                    String name = it.next();
12107                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12108                    if (!checkin) {
12109                        if (!printedHeader) {
12110                            if (dumpState.onTitlePrinted())
12111                                pw.println();
12112                            pw.println("Libraries:");
12113                            printedHeader = true;
12114                        }
12115                        pw.print("  ");
12116                    } else {
12117                        pw.print("lib,");
12118                    }
12119                    pw.print(name);
12120                    if (!checkin) {
12121                        pw.print(" -> ");
12122                    }
12123                    if (ent.path != null) {
12124                        if (!checkin) {
12125                            pw.print("(jar) ");
12126                            pw.print(ent.path);
12127                        } else {
12128                            pw.print(",jar,");
12129                            pw.print(ent.path);
12130                        }
12131                    } else {
12132                        if (!checkin) {
12133                            pw.print("(apk) ");
12134                            pw.print(ent.apk);
12135                        } else {
12136                            pw.print(",apk,");
12137                            pw.print(ent.apk);
12138                        }
12139                    }
12140                    pw.println();
12141                }
12142            }
12143
12144            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12145                if (dumpState.onTitlePrinted())
12146                    pw.println();
12147                if (!checkin) {
12148                    pw.println("Features:");
12149                }
12150                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12151                while (it.hasNext()) {
12152                    String name = it.next();
12153                    if (!checkin) {
12154                        pw.print("  ");
12155                    } else {
12156                        pw.print("feat,");
12157                    }
12158                    pw.println(name);
12159                }
12160            }
12161
12162            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12163                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12164                        : "Activity Resolver Table:", "  ", packageName,
12165                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12166                    dumpState.setTitlePrinted(true);
12167                }
12168                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12169                        : "Receiver Resolver Table:", "  ", packageName,
12170                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12171                    dumpState.setTitlePrinted(true);
12172                }
12173                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12174                        : "Service Resolver Table:", "  ", packageName,
12175                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12176                    dumpState.setTitlePrinted(true);
12177                }
12178                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12179                        : "Provider Resolver Table:", "  ", packageName,
12180                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12181                    dumpState.setTitlePrinted(true);
12182                }
12183            }
12184
12185            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12186                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12187                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12188                    int user = mSettings.mPreferredActivities.keyAt(i);
12189                    if (pir.dump(pw,
12190                            dumpState.getTitlePrinted()
12191                                ? "\nPreferred Activities User " + user + ":"
12192                                : "Preferred Activities User " + user + ":", "  ",
12193                            packageName, true)) {
12194                        dumpState.setTitlePrinted(true);
12195                    }
12196                }
12197            }
12198
12199            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12200                pw.flush();
12201                FileOutputStream fout = new FileOutputStream(fd);
12202                BufferedOutputStream str = new BufferedOutputStream(fout);
12203                XmlSerializer serializer = new FastXmlSerializer();
12204                try {
12205                    serializer.setOutput(str, "utf-8");
12206                    serializer.startDocument(null, true);
12207                    serializer.setFeature(
12208                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12209                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12210                    serializer.endDocument();
12211                    serializer.flush();
12212                } catch (IllegalArgumentException e) {
12213                    pw.println("Failed writing: " + e);
12214                } catch (IllegalStateException e) {
12215                    pw.println("Failed writing: " + e);
12216                } catch (IOException e) {
12217                    pw.println("Failed writing: " + e);
12218                }
12219            }
12220
12221            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12222                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12223            }
12224
12225            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12226                boolean printedSomething = false;
12227                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12228                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12229                        continue;
12230                    }
12231                    if (!printedSomething) {
12232                        if (dumpState.onTitlePrinted())
12233                            pw.println();
12234                        pw.println("Registered ContentProviders:");
12235                        printedSomething = true;
12236                    }
12237                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12238                    pw.print("    "); pw.println(p.toString());
12239                }
12240                printedSomething = false;
12241                for (Map.Entry<String, PackageParser.Provider> entry :
12242                        mProvidersByAuthority.entrySet()) {
12243                    PackageParser.Provider p = entry.getValue();
12244                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12245                        continue;
12246                    }
12247                    if (!printedSomething) {
12248                        if (dumpState.onTitlePrinted())
12249                            pw.println();
12250                        pw.println("ContentProvider Authorities:");
12251                        printedSomething = true;
12252                    }
12253                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12254                    pw.print("    "); pw.println(p.toString());
12255                    if (p.info != null && p.info.applicationInfo != null) {
12256                        final String appInfo = p.info.applicationInfo.toString();
12257                        pw.print("      applicationInfo="); pw.println(appInfo);
12258                    }
12259                }
12260            }
12261
12262            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12263                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12264            }
12265
12266            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12267                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12268            }
12269
12270            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12271                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12272            }
12273
12274            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12275                if (dumpState.onTitlePrinted())
12276                    pw.println();
12277                mSettings.dumpReadMessagesLPr(pw, dumpState);
12278
12279                pw.println();
12280                pw.println("Package warning messages:");
12281                final File fname = getSettingsProblemFile();
12282                FileInputStream in = null;
12283                try {
12284                    in = new FileInputStream(fname);
12285                    final int avail = in.available();
12286                    final byte[] data = new byte[avail];
12287                    in.read(data);
12288                    pw.print(new String(data));
12289                } catch (FileNotFoundException e) {
12290                } catch (IOException e) {
12291                } finally {
12292                    if (in != null) {
12293                        try {
12294                            in.close();
12295                        } catch (IOException e) {
12296                        }
12297                    }
12298                }
12299            }
12300        }
12301    }
12302
12303    // ------- apps on sdcard specific code -------
12304    static final boolean DEBUG_SD_INSTALL = false;
12305
12306    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12307
12308    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12309
12310    private boolean mMediaMounted = false;
12311
12312    private String getEncryptKey() {
12313        try {
12314            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12315                    SD_ENCRYPTION_KEYSTORE_NAME);
12316            if (sdEncKey == null) {
12317                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12318                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12319                if (sdEncKey == null) {
12320                    Slog.e(TAG, "Failed to create encryption keys");
12321                    return null;
12322                }
12323            }
12324            return sdEncKey;
12325        } catch (NoSuchAlgorithmException nsae) {
12326            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12327            return null;
12328        } catch (IOException ioe) {
12329            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12330            return null;
12331        }
12332
12333    }
12334
12335    /* package */static String getTempContainerId() {
12336        int tmpIdx = 1;
12337        String list[] = PackageHelper.getSecureContainerList();
12338        if (list != null) {
12339            for (final String name : list) {
12340                // Ignore null and non-temporary container entries
12341                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12342                    continue;
12343                }
12344
12345                String subStr = name.substring(mTempContainerPrefix.length());
12346                try {
12347                    int cid = Integer.parseInt(subStr);
12348                    if (cid >= tmpIdx) {
12349                        tmpIdx = cid + 1;
12350                    }
12351                } catch (NumberFormatException e) {
12352                }
12353            }
12354        }
12355        return mTempContainerPrefix + tmpIdx;
12356    }
12357
12358    /*
12359     * Update media status on PackageManager.
12360     */
12361    @Override
12362    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12363        int callingUid = Binder.getCallingUid();
12364        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12365            throw new SecurityException("Media status can only be updated by the system");
12366        }
12367        // reader; this apparently protects mMediaMounted, but should probably
12368        // be a different lock in that case.
12369        synchronized (mPackages) {
12370            Log.i(TAG, "Updating external media status from "
12371                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12372                    + (mediaStatus ? "mounted" : "unmounted"));
12373            if (DEBUG_SD_INSTALL)
12374                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12375                        + ", mMediaMounted=" + mMediaMounted);
12376            if (mediaStatus == mMediaMounted) {
12377                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12378                        : 0, -1);
12379                mHandler.sendMessage(msg);
12380                return;
12381            }
12382            mMediaMounted = mediaStatus;
12383        }
12384        // Queue up an async operation since the package installation may take a
12385        // little while.
12386        mHandler.post(new Runnable() {
12387            public void run() {
12388                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12389            }
12390        });
12391    }
12392
12393    /**
12394     * Called by MountService when the initial ASECs to scan are available.
12395     * Should block until all the ASEC containers are finished being scanned.
12396     */
12397    public void scanAvailableAsecs() {
12398        updateExternalMediaStatusInner(true, false, false);
12399        if (mShouldRestoreconData) {
12400            SELinuxMMAC.setRestoreconDone();
12401            mShouldRestoreconData = false;
12402        }
12403    }
12404
12405    /*
12406     * Collect information of applications on external media, map them against
12407     * existing containers and update information based on current mount status.
12408     * Please note that we always have to report status if reportStatus has been
12409     * set to true especially when unloading packages.
12410     */
12411    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12412            boolean externalStorage) {
12413        // Collection of uids
12414        int uidArr[] = null;
12415        // Collection of stale containers
12416        HashSet<String> removeCids = new HashSet<String>();
12417        // Collection of packages on external media with valid containers.
12418        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12419        // Get list of secure containers.
12420        final String list[] = PackageHelper.getSecureContainerList();
12421        if (list == null || list.length == 0) {
12422            Log.i(TAG, "No secure containers on sdcard");
12423        } else {
12424            // Process list of secure containers and categorize them
12425            // as active or stale based on their package internal state.
12426            int uidList[] = new int[list.length];
12427            int num = 0;
12428            // reader
12429            synchronized (mPackages) {
12430                for (String cid : list) {
12431                    if (DEBUG_SD_INSTALL)
12432                        Log.i(TAG, "Processing container " + cid);
12433                    String pkgName = getAsecPackageName(cid);
12434                    if (pkgName == null) {
12435                        if (DEBUG_SD_INSTALL)
12436                            Log.i(TAG, "Container : " + cid + " stale");
12437                        removeCids.add(cid);
12438                        continue;
12439                    }
12440                    if (DEBUG_SD_INSTALL)
12441                        Log.i(TAG, "Looking for pkg : " + pkgName);
12442
12443                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12444                    if (ps == null) {
12445                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12446                        removeCids.add(cid);
12447                        continue;
12448                    }
12449
12450                    /*
12451                     * Skip packages that are not external if we're unmounting
12452                     * external storage.
12453                     */
12454                    if (externalStorage && !isMounted && !isExternal(ps)) {
12455                        continue;
12456                    }
12457
12458                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12459                            getAppInstructionSetFromSettings(ps),
12460                            isForwardLocked(ps));
12461                    // The package status is changed only if the code path
12462                    // matches between settings and the container id.
12463                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12464                        if (DEBUG_SD_INSTALL) {
12465                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12466                                    + " at code path: " + ps.codePathString);
12467                        }
12468
12469                        // We do have a valid package installed on sdcard
12470                        processCids.put(args, ps.codePathString);
12471                        final int uid = ps.appId;
12472                        if (uid != -1) {
12473                            uidList[num++] = uid;
12474                        }
12475                    } else {
12476                        Log.i(TAG, "Deleting stale container for " + cid);
12477                        removeCids.add(cid);
12478                    }
12479                }
12480            }
12481
12482            if (num > 0) {
12483                // Sort uid list
12484                Arrays.sort(uidList, 0, num);
12485                // Throw away duplicates
12486                uidArr = new int[num];
12487                uidArr[0] = uidList[0];
12488                int di = 0;
12489                for (int i = 1; i < num; i++) {
12490                    if (uidList[i - 1] != uidList[i]) {
12491                        uidArr[di++] = uidList[i];
12492                    }
12493                }
12494            }
12495        }
12496        // Process packages with valid entries.
12497        if (isMounted) {
12498            if (DEBUG_SD_INSTALL)
12499                Log.i(TAG, "Loading packages");
12500            loadMediaPackages(processCids, uidArr, removeCids);
12501            startCleaningPackages();
12502        } else {
12503            if (DEBUG_SD_INSTALL)
12504                Log.i(TAG, "Unloading packages");
12505            unloadMediaPackages(processCids, uidArr, reportStatus);
12506        }
12507    }
12508
12509   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12510           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12511        int size = pkgList.size();
12512        if (size > 0) {
12513            // Send broadcasts here
12514            Bundle extras = new Bundle();
12515            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12516                    .toArray(new String[size]));
12517            if (uidArr != null) {
12518                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12519            }
12520            if (replacing) {
12521                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12522            }
12523            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12524                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12525            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12526        }
12527    }
12528
12529   /*
12530     * Look at potentially valid container ids from processCids If package
12531     * information doesn't match the one on record or package scanning fails,
12532     * the cid is added to list of removeCids. We currently don't delete stale
12533     * containers.
12534     */
12535   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12536            HashSet<String> removeCids) {
12537        ArrayList<String> pkgList = new ArrayList<String>();
12538        Set<AsecInstallArgs> keys = processCids.keySet();
12539        boolean doGc = false;
12540        for (AsecInstallArgs args : keys) {
12541            String codePath = processCids.get(args);
12542            if (DEBUG_SD_INSTALL)
12543                Log.i(TAG, "Loading container : " + args.cid);
12544            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12545            try {
12546                // Make sure there are no container errors first.
12547                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12548                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12549                            + " when installing from sdcard");
12550                    continue;
12551                }
12552                // Check code path here.
12553                if (codePath == null || !codePath.equals(args.getCodePath())) {
12554                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12555                            + " does not match one in settings " + codePath);
12556                    continue;
12557                }
12558                // Parse package
12559                int parseFlags = mDefParseFlags;
12560                if (args.isExternal()) {
12561                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12562                }
12563                if (args.isFwdLocked()) {
12564                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12565                }
12566
12567                doGc = true;
12568                synchronized (mInstallLock) {
12569                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12570                            0, 0, null, null);
12571                    // Scan the package
12572                    if (pkg != null) {
12573                        /*
12574                         * TODO why is the lock being held? doPostInstall is
12575                         * called in other places without the lock. This needs
12576                         * to be straightened out.
12577                         */
12578                        // writer
12579                        synchronized (mPackages) {
12580                            retCode = PackageManager.INSTALL_SUCCEEDED;
12581                            pkgList.add(pkg.packageName);
12582                            // Post process args
12583                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12584                                    pkg.applicationInfo.uid);
12585                        }
12586                    } else {
12587                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12588                    }
12589                }
12590
12591            } finally {
12592                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12593                    // Don't destroy container here. Wait till gc clears things
12594                    // up.
12595                    removeCids.add(args.cid);
12596                }
12597            }
12598        }
12599        // writer
12600        synchronized (mPackages) {
12601            // If the platform SDK has changed since the last time we booted,
12602            // we need to re-grant app permission to catch any new ones that
12603            // appear. This is really a hack, and means that apps can in some
12604            // cases get permissions that the user didn't initially explicitly
12605            // allow... it would be nice to have some better way to handle
12606            // this situation.
12607            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12608            if (regrantPermissions)
12609                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12610                        + mSdkVersion + "; regranting permissions for external storage");
12611            mSettings.mExternalSdkPlatform = mSdkVersion;
12612
12613            // Make sure group IDs have been assigned, and any permission
12614            // changes in other apps are accounted for
12615            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12616                    | (regrantPermissions
12617                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12618                            : 0));
12619
12620            mSettings.updateExternalDatabaseVersion();
12621
12622            // can downgrade to reader
12623            // Persist settings
12624            mSettings.writeLPr();
12625        }
12626        // Send a broadcast to let everyone know we are done processing
12627        if (pkgList.size() > 0) {
12628            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12629        }
12630        // Force gc to avoid any stale parser references that we might have.
12631        if (doGc) {
12632            Runtime.getRuntime().gc();
12633        }
12634        // List stale containers and destroy stale temporary containers.
12635        if (removeCids != null) {
12636            for (String cid : removeCids) {
12637                if (cid.startsWith(mTempContainerPrefix)) {
12638                    Log.i(TAG, "Destroying stale temporary container " + cid);
12639                    PackageHelper.destroySdDir(cid);
12640                } else {
12641                    Log.w(TAG, "Container " + cid + " is stale");
12642               }
12643           }
12644        }
12645    }
12646
12647   /*
12648     * Utility method to unload a list of specified containers
12649     */
12650    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12651        // Just unmount all valid containers.
12652        for (AsecInstallArgs arg : cidArgs) {
12653            synchronized (mInstallLock) {
12654                arg.doPostDeleteLI(false);
12655           }
12656       }
12657   }
12658
12659    /*
12660     * Unload packages mounted on external media. This involves deleting package
12661     * data from internal structures, sending broadcasts about diabled packages,
12662     * gc'ing to free up references, unmounting all secure containers
12663     * corresponding to packages on external media, and posting a
12664     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12665     * that we always have to post this message if status has been requested no
12666     * matter what.
12667     */
12668    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12669            final boolean reportStatus) {
12670        if (DEBUG_SD_INSTALL)
12671            Log.i(TAG, "unloading media packages");
12672        ArrayList<String> pkgList = new ArrayList<String>();
12673        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12674        final Set<AsecInstallArgs> keys = processCids.keySet();
12675        for (AsecInstallArgs args : keys) {
12676            String pkgName = args.getPackageName();
12677            if (DEBUG_SD_INSTALL)
12678                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12679            // Delete package internally
12680            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12681            synchronized (mInstallLock) {
12682                boolean res = deletePackageLI(pkgName, null, false, null, null,
12683                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12684                if (res) {
12685                    pkgList.add(pkgName);
12686                } else {
12687                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12688                    failedList.add(args);
12689                }
12690            }
12691        }
12692
12693        // reader
12694        synchronized (mPackages) {
12695            // We didn't update the settings after removing each package;
12696            // write them now for all packages.
12697            mSettings.writeLPr();
12698        }
12699
12700        // We have to absolutely send UPDATED_MEDIA_STATUS only
12701        // after confirming that all the receivers processed the ordered
12702        // broadcast when packages get disabled, force a gc to clean things up.
12703        // and unload all the containers.
12704        if (pkgList.size() > 0) {
12705            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12706                    new IIntentReceiver.Stub() {
12707                public void performReceive(Intent intent, int resultCode, String data,
12708                        Bundle extras, boolean ordered, boolean sticky,
12709                        int sendingUser) throws RemoteException {
12710                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12711                            reportStatus ? 1 : 0, 1, keys);
12712                    mHandler.sendMessage(msg);
12713                }
12714            });
12715        } else {
12716            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12717                    keys);
12718            mHandler.sendMessage(msg);
12719        }
12720    }
12721
12722    /** Binder call */
12723    @Override
12724    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12725            final int flags) {
12726        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12727        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12728        int returnCode = PackageManager.MOVE_SUCCEEDED;
12729        int currFlags = 0;
12730        int newFlags = 0;
12731        // reader
12732        synchronized (mPackages) {
12733            PackageParser.Package pkg = mPackages.get(packageName);
12734            if (pkg == null) {
12735                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12736            } else {
12737                // Disable moving fwd locked apps and system packages
12738                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12739                    Slog.w(TAG, "Cannot move system application");
12740                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12741                } else if (pkg.mOperationPending) {
12742                    Slog.w(TAG, "Attempt to move package which has pending operations");
12743                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12744                } else {
12745                    // Find install location first
12746                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12747                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12748                        Slog.w(TAG, "Ambigous flags specified for move location.");
12749                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12750                    } else {
12751                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12752                                : PackageManager.INSTALL_INTERNAL;
12753                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12754                                : PackageManager.INSTALL_INTERNAL;
12755
12756                        if (newFlags == currFlags) {
12757                            Slog.w(TAG, "No move required. Trying to move to same location");
12758                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12759                        } else {
12760                            if (isForwardLocked(pkg)) {
12761                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12762                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12763                            }
12764                        }
12765                    }
12766                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12767                        pkg.mOperationPending = true;
12768                    }
12769                }
12770            }
12771
12772            /*
12773             * TODO this next block probably shouldn't be inside the lock. We
12774             * can't guarantee these won't change after this is fired off
12775             * anyway.
12776             */
12777            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12778                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12779                        null, -1, user),
12780                        returnCode);
12781            } else {
12782                Message msg = mHandler.obtainMessage(INIT_COPY);
12783                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12784                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12785                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12786                        instructionSet);
12787                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12788                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12789                msg.obj = mp;
12790                mHandler.sendMessage(msg);
12791            }
12792        }
12793    }
12794
12795    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12796        // Queue up an async operation since the package deletion may take a
12797        // little while.
12798        mHandler.post(new Runnable() {
12799            public void run() {
12800                // TODO fix this; this does nothing.
12801                mHandler.removeCallbacks(this);
12802                int returnCode = currentStatus;
12803                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12804                    int uidArr[] = null;
12805                    ArrayList<String> pkgList = null;
12806                    synchronized (mPackages) {
12807                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12808                        if (pkg == null) {
12809                            Slog.w(TAG, " Package " + mp.packageName
12810                                    + " doesn't exist. Aborting move");
12811                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12812                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12813                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12814                                    + mp.srcArgs.getCodePath() + " to "
12815                                    + pkg.applicationInfo.sourceDir
12816                                    + " Aborting move and returning error");
12817                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12818                        } else {
12819                            uidArr = new int[] {
12820                                pkg.applicationInfo.uid
12821                            };
12822                            pkgList = new ArrayList<String>();
12823                            pkgList.add(mp.packageName);
12824                        }
12825                    }
12826                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12827                        // Send resources unavailable broadcast
12828                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12829                        // Update package code and resource paths
12830                        synchronized (mInstallLock) {
12831                            synchronized (mPackages) {
12832                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12833                                // Recheck for package again.
12834                                if (pkg == null) {
12835                                    Slog.w(TAG, " Package " + mp.packageName
12836                                            + " doesn't exist. Aborting move");
12837                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12838                                } else if (!mp.srcArgs.getCodePath().equals(
12839                                        pkg.applicationInfo.sourceDir)) {
12840                                    Slog.w(TAG, "Package " + mp.packageName
12841                                            + " code path changed from " + mp.srcArgs.getCodePath()
12842                                            + " to " + pkg.applicationInfo.sourceDir
12843                                            + " Aborting move and returning error");
12844                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12845                                } else {
12846                                    final String oldCodePath = pkg.codePath;
12847                                    final String newCodePath = mp.targetArgs.getCodePath();
12848                                    final String newResPath = mp.targetArgs.getResourcePath();
12849                                    final String newNativePath = mp.targetArgs
12850                                            .getNativeLibraryPath();
12851
12852                                    final File newNativeDir = new File(newNativePath);
12853
12854                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12855                                        // NOTE: We do not report any errors from the APK scan and library
12856                                        // copy at this point.
12857                                        NativeLibraryHelper.ApkHandle handle =
12858                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12859                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12860                                                handle, Build.SUPPORTED_ABIS);
12861                                        if (abi >= 0) {
12862                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12863                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12864                                        }
12865                                        handle.close();
12866                                    }
12867                                    final int[] users = sUserManager.getUserIds();
12868                                    for (int user : users) {
12869                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12870                                                newNativePath, user) < 0) {
12871                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12872                                        }
12873                                    }
12874
12875                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12876                                        pkg.codePath = newCodePath;
12877                                        // Move dex files around
12878                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12879                                            // Moving of dex files failed. Set
12880                                            // error code and abort move.
12881                                            pkg.codePath = oldCodePath;
12882                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12883                                        }
12884                                    }
12885
12886                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12887                                        pkg.applicationInfo.sourceDir = newCodePath;
12888                                        pkg.applicationInfo.publicSourceDir = newResPath;
12889                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12890                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12891                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12892                                        ps.codePathString = ps.codePath.getPath();
12893                                        ps.resourcePath = new File(
12894                                                pkg.applicationInfo.publicSourceDir);
12895                                        ps.resourcePathString = ps.resourcePath.getPath();
12896                                        ps.nativeLibraryPathString = newNativePath;
12897                                        // Set the application info flag
12898                                        // correctly.
12899                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12900                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12901                                        } else {
12902                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12903                                        }
12904                                        ps.setFlags(pkg.applicationInfo.flags);
12905                                        mAppDirs.remove(oldCodePath);
12906                                        mAppDirs.put(newCodePath, pkg);
12907                                        // Persist settings
12908                                        mSettings.writeLPr();
12909                                    }
12910                                }
12911                            }
12912                        }
12913                        // Send resources available broadcast
12914                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12915                    }
12916                }
12917                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12918                    // Clean up failed installation
12919                    if (mp.targetArgs != null) {
12920                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12921                                -1);
12922                    }
12923                } else {
12924                    // Force a gc to clear things up.
12925                    Runtime.getRuntime().gc();
12926                    // Delete older code
12927                    synchronized (mInstallLock) {
12928                        mp.srcArgs.doPostDeleteLI(true);
12929                    }
12930                }
12931
12932                // Allow more operations on this file if we didn't fail because
12933                // an operation was already pending for this package.
12934                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12935                    synchronized (mPackages) {
12936                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12937                        if (pkg != null) {
12938                            pkg.mOperationPending = false;
12939                       }
12940                   }
12941                }
12942
12943                IPackageMoveObserver observer = mp.observer;
12944                if (observer != null) {
12945                    try {
12946                        observer.packageMoved(mp.packageName, returnCode);
12947                    } catch (RemoteException e) {
12948                        Log.i(TAG, "Observer no longer exists.");
12949                    }
12950                }
12951            }
12952        });
12953    }
12954
12955    @Override
12956    public boolean setInstallLocation(int loc) {
12957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12958                null);
12959        if (getInstallLocation() == loc) {
12960            return true;
12961        }
12962        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12963                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12964            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12965                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12966            return true;
12967        }
12968        return false;
12969   }
12970
12971    @Override
12972    public int getInstallLocation() {
12973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12974                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12975                PackageHelper.APP_INSTALL_AUTO);
12976    }
12977
12978    /** Called by UserManagerService */
12979    void cleanUpUserLILPw(int userHandle) {
12980        mDirtyUsers.remove(userHandle);
12981        mSettings.removeUserLPr(userHandle);
12982        mPendingBroadcasts.remove(userHandle);
12983        if (mInstaller != null) {
12984            // Technically, we shouldn't be doing this with the package lock
12985            // held.  However, this is very rare, and there is already so much
12986            // other disk I/O going on, that we'll let it slide for now.
12987            mInstaller.removeUserDataDirs(userHandle);
12988        }
12989        mUserNeedsBadging.delete(userHandle);
12990    }
12991
12992    /** Called by UserManagerService */
12993    void createNewUserLILPw(int userHandle, File path) {
12994        if (mInstaller != null) {
12995            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12996        }
12997    }
12998
12999    @Override
13000    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13001        mContext.enforceCallingOrSelfPermission(
13002                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13003                "Only package verification agents can read the verifier device identity");
13004
13005        synchronized (mPackages) {
13006            return mSettings.getVerifierDeviceIdentityLPw();
13007        }
13008    }
13009
13010    @Override
13011    public void setPermissionEnforced(String permission, boolean enforced) {
13012        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13013        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13014            synchronized (mPackages) {
13015                if (mSettings.mReadExternalStorageEnforced == null
13016                        || mSettings.mReadExternalStorageEnforced != enforced) {
13017                    mSettings.mReadExternalStorageEnforced = enforced;
13018                    mSettings.writeLPr();
13019                }
13020            }
13021            // kill any non-foreground processes so we restart them and
13022            // grant/revoke the GID.
13023            final IActivityManager am = ActivityManagerNative.getDefault();
13024            if (am != null) {
13025                final long token = Binder.clearCallingIdentity();
13026                try {
13027                    am.killProcessesBelowForeground("setPermissionEnforcement");
13028                } catch (RemoteException e) {
13029                } finally {
13030                    Binder.restoreCallingIdentity(token);
13031                }
13032            }
13033        } else {
13034            throw new IllegalArgumentException("No selective enforcement for " + permission);
13035        }
13036    }
13037
13038    @Override
13039    @Deprecated
13040    public boolean isPermissionEnforced(String permission) {
13041        return true;
13042    }
13043
13044    @Override
13045    public boolean isStorageLow() {
13046        final long token = Binder.clearCallingIdentity();
13047        try {
13048            final DeviceStorageMonitorInternal
13049                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13050            if (dsm != null) {
13051                return dsm.isMemoryLow();
13052            } else {
13053                return false;
13054            }
13055        } finally {
13056            Binder.restoreCallingIdentity(token);
13057        }
13058    }
13059
13060    @Override
13061    public IPackageInstaller getPackageInstaller() {
13062        return mInstallerService;
13063    }
13064
13065    private boolean userNeedsBadging(int userId) {
13066        int index = mUserNeedsBadging.indexOfKey(userId);
13067        if (index < 0) {
13068            final UserInfo userInfo;
13069            final long token = Binder.clearCallingIdentity();
13070            try {
13071                userInfo = sUserManager.getUserInfo(userId);
13072            } finally {
13073                Binder.restoreCallingIdentity(token);
13074            }
13075            final boolean b;
13076            if (userInfo != null && userInfo.isManagedProfile()) {
13077                b = true;
13078            } else {
13079                b = false;
13080            }
13081            mUserNeedsBadging.put(userId, b);
13082            return b;
13083        }
13084        return mUserNeedsBadging.valueAt(index);
13085    }
13086}
13087