PackageManagerService.java revision 6728239cfe8a71d3294b9368a4af73e427a2341c
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            ApkHandle handle = null;
5343            try {
5344                handle = ApkHandle.create(scanFile.getPath());
5345                // Enable gross and lame hacks for apps that are built with old
5346                // SDK tools. We must scan their APKs for renderscript bitcode and
5347                // not launch them if it's present. Don't bother checking on devices
5348                // that don't have 64 bit support.
5349                String[] abiList = Build.SUPPORTED_ABIS;
5350                boolean hasLegacyRenderscriptBitcode = false;
5351                if (abiOverride != null) {
5352                    abiList = new String[] { abiOverride };
5353                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5354                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5355                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5356                    hasLegacyRenderscriptBitcode = true;
5357                }
5358
5359                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5360                final String dataPathString = dataPath.getCanonicalPath();
5361
5362                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5363                    /*
5364                     * Upgrading from a previous version of the OS sometimes
5365                     * leaves native libraries in the /data/data/<app>/lib
5366                     * directory for system apps even when they shouldn't be.
5367                     * Recent changes in the JNI library search path
5368                     * necessitates we remove those to match previous behavior.
5369                     */
5370                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5371                        Log.i(TAG, "removed obsolete native libraries for system package "
5372                                + path);
5373                    }
5374                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5375                        pkg.applicationInfo.cpuAbi = abiList[0];
5376                        pkgSetting.cpuAbiString = abiList[0];
5377                    } else {
5378                        setInternalAppAbi(pkg, pkgSetting);
5379                    }
5380                } else {
5381                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5382                        /*
5383                        * Update native library dir if it starts with
5384                        * /data/data
5385                        */
5386                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5387                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5388                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5389                        }
5390
5391                        try {
5392                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5393                                    nativeLibraryDir, abiList);
5394                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5395                                Slog.e(TAG, "Unable to copy native libraries");
5396                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5397                                return null;
5398                            }
5399
5400                            // We've successfully copied native libraries across, so we make a
5401                            // note of what ABI we're using
5402                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5403                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5404                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5405                                pkg.applicationInfo.cpuAbi = abiList[0];
5406                            } else {
5407                                pkg.applicationInfo.cpuAbi = null;
5408                            }
5409                        } catch (IOException e) {
5410                            Slog.e(TAG, "Unable to copy native libraries", e);
5411                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5412                            return null;
5413                        }
5414                    } else {
5415                        // We don't have to copy the shared libraries if we're in the ASEC container
5416                        // but we still need to scan the file to figure out what ABI the app needs.
5417                        //
5418                        // TODO: This duplicates work done in the default container service. It's possible
5419                        // to clean this up but we'll need to change the interface between this service
5420                        // and IMediaContainerService (but doing so will spread this logic out, rather
5421                        // than centralizing it).
5422                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5423                        if (abi >= 0) {
5424                            pkg.applicationInfo.cpuAbi = abiList[abi];
5425                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5426                            // Note that (non upgraded) system apps will not have any native
5427                            // libraries bundled in their APK, but we're guaranteed not to be
5428                            // such an app at this point.
5429                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5430                                pkg.applicationInfo.cpuAbi = abiList[0];
5431                            } else {
5432                                pkg.applicationInfo.cpuAbi = null;
5433                            }
5434                        } else {
5435                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5436                            return null;
5437                        }
5438                    }
5439
5440                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5441                    final int[] userIds = sUserManager.getUserIds();
5442                    synchronized (mInstallLock) {
5443                        for (int userId : userIds) {
5444                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5445                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5446                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5447                                        + ")");
5448                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5449                                return null;
5450                            }
5451                        }
5452                    }
5453                }
5454
5455                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5456            } catch (IOException ioe) {
5457                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5458            } finally {
5459                IoUtils.closeQuietly(handle);
5460            }
5461        }
5462
5463        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5464            // We don't do this here during boot because we can do it all
5465            // at once after scanning all existing packages.
5466            //
5467            // We also do this *before* we perform dexopt on this package, so that
5468            // we can avoid redundant dexopts, and also to make sure we've got the
5469            // code and package path correct.
5470            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5471                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5472                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5473                return null;
5474            }
5475        }
5476
5477        if ((scanMode&SCAN_NO_DEX) == 0) {
5478            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5479                    == DEX_OPT_FAILED) {
5480                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5481                    removeDataDirsLI(pkg.packageName);
5482                }
5483
5484                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5485                return null;
5486            }
5487        }
5488
5489        if (mFactoryTest && pkg.requestedPermissions.contains(
5490                android.Manifest.permission.FACTORY_TEST)) {
5491            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5492        }
5493
5494        ArrayList<PackageParser.Package> clientLibPkgs = null;
5495
5496        // writer
5497        synchronized (mPackages) {
5498            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5499                // Only system apps can add new shared libraries.
5500                if (pkg.libraryNames != null) {
5501                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5502                        String name = pkg.libraryNames.get(i);
5503                        boolean allowed = false;
5504                        if (isUpdatedSystemApp(pkg)) {
5505                            // New library entries can only be added through the
5506                            // system image.  This is important to get rid of a lot
5507                            // of nasty edge cases: for example if we allowed a non-
5508                            // system update of the app to add a library, then uninstalling
5509                            // the update would make the library go away, and assumptions
5510                            // we made such as through app install filtering would now
5511                            // have allowed apps on the device which aren't compatible
5512                            // with it.  Better to just have the restriction here, be
5513                            // conservative, and create many fewer cases that can negatively
5514                            // impact the user experience.
5515                            final PackageSetting sysPs = mSettings
5516                                    .getDisabledSystemPkgLPr(pkg.packageName);
5517                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5518                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5519                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5520                                        allowed = true;
5521                                        allowed = true;
5522                                        break;
5523                                    }
5524                                }
5525                            }
5526                        } else {
5527                            allowed = true;
5528                        }
5529                        if (allowed) {
5530                            if (!mSharedLibraries.containsKey(name)) {
5531                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5532                            } else if (!name.equals(pkg.packageName)) {
5533                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5534                                        + name + " already exists; skipping");
5535                            }
5536                        } else {
5537                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5538                                    + name + " that is not declared on system image; skipping");
5539                        }
5540                    }
5541                    if ((scanMode&SCAN_BOOTING) == 0) {
5542                        // If we are not booting, we need to update any applications
5543                        // that are clients of our shared library.  If we are booting,
5544                        // this will all be done once the scan is complete.
5545                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5546                    }
5547                }
5548            }
5549        }
5550
5551        // We also need to dexopt any apps that are dependent on this library.  Note that
5552        // if these fail, we should abort the install since installing the library will
5553        // result in some apps being broken.
5554        if (clientLibPkgs != null) {
5555            if ((scanMode&SCAN_NO_DEX) == 0) {
5556                for (int i=0; i<clientLibPkgs.size(); i++) {
5557                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5558                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5559                            == DEX_OPT_FAILED) {
5560                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5561                            removeDataDirsLI(pkg.packageName);
5562                        }
5563
5564                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5565                        return null;
5566                    }
5567                }
5568            }
5569        }
5570
5571        // Request the ActivityManager to kill the process(only for existing packages)
5572        // so that we do not end up in a confused state while the user is still using the older
5573        // version of the application while the new one gets installed.
5574        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5575            // If the package lives in an asec, tell everyone that the container is going
5576            // away so they can clean up any references to its resources (which would prevent
5577            // vold from being able to unmount the asec)
5578            if (isForwardLocked(pkg) || isExternal(pkg)) {
5579                if (DEBUG_INSTALL) {
5580                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5581                }
5582                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5583                final ArrayList<String> pkgList = new ArrayList<String>(1);
5584                pkgList.add(pkg.applicationInfo.packageName);
5585                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5586            }
5587
5588            // Post the request that it be killed now that the going-away broadcast is en route
5589            killApplication(pkg.applicationInfo.packageName,
5590                        pkg.applicationInfo.uid, "update pkg");
5591        }
5592
5593        // Also need to kill any apps that are dependent on the library.
5594        if (clientLibPkgs != null) {
5595            for (int i=0; i<clientLibPkgs.size(); i++) {
5596                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5597                killApplication(clientPkg.applicationInfo.packageName,
5598                        clientPkg.applicationInfo.uid, "update lib");
5599            }
5600        }
5601
5602        // writer
5603        synchronized (mPackages) {
5604            // We don't expect installation to fail beyond this point,
5605            if ((scanMode&SCAN_MONITOR) != 0) {
5606                mAppDirs.put(pkg.codePath, pkg);
5607            }
5608            // Add the new setting to mSettings
5609            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5610            // Add the new setting to mPackages
5611            mPackages.put(pkg.applicationInfo.packageName, pkg);
5612            // Make sure we don't accidentally delete its data.
5613            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5614            while (iter.hasNext()) {
5615                PackageCleanItem item = iter.next();
5616                if (pkgName.equals(item.packageName)) {
5617                    iter.remove();
5618                }
5619            }
5620
5621            // Take care of first install / last update times.
5622            if (currentTime != 0) {
5623                if (pkgSetting.firstInstallTime == 0) {
5624                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5625                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5626                    pkgSetting.lastUpdateTime = currentTime;
5627                }
5628            } else if (pkgSetting.firstInstallTime == 0) {
5629                // We need *something*.  Take time time stamp of the file.
5630                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5631            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5632                if (scanFileTime != pkgSetting.timeStamp) {
5633                    // A package on the system image has changed; consider this
5634                    // to be an update.
5635                    pkgSetting.lastUpdateTime = scanFileTime;
5636                }
5637            }
5638
5639            // Add the package's KeySets to the global KeySetManager
5640            KeySetManager ksm = mSettings.mKeySetManager;
5641            try {
5642                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5643                if (pkg.mKeySetMapping != null) {
5644                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5645                            pkg.mKeySetMapping.entrySet()) {
5646                        if (entry.getValue() != null) {
5647                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5648                                entry.getValue(), entry.getKey());
5649                        }
5650                    }
5651                }
5652            } catch (NullPointerException e) {
5653                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5654            } catch (IllegalArgumentException e) {
5655                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5656            }
5657
5658            int N = pkg.providers.size();
5659            StringBuilder r = null;
5660            int i;
5661            for (i=0; i<N; i++) {
5662                PackageParser.Provider p = pkg.providers.get(i);
5663                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5664                        p.info.processName, pkg.applicationInfo.uid);
5665                mProviders.addProvider(p);
5666                p.syncable = p.info.isSyncable;
5667                if (p.info.authority != null) {
5668                    String names[] = p.info.authority.split(";");
5669                    p.info.authority = null;
5670                    for (int j = 0; j < names.length; j++) {
5671                        if (j == 1 && p.syncable) {
5672                            // We only want the first authority for a provider to possibly be
5673                            // syncable, so if we already added this provider using a different
5674                            // authority clear the syncable flag. We copy the provider before
5675                            // changing it because the mProviders object contains a reference
5676                            // to a provider that we don't want to change.
5677                            // Only do this for the second authority since the resulting provider
5678                            // object can be the same for all future authorities for this provider.
5679                            p = new PackageParser.Provider(p);
5680                            p.syncable = false;
5681                        }
5682                        if (!mProvidersByAuthority.containsKey(names[j])) {
5683                            mProvidersByAuthority.put(names[j], p);
5684                            if (p.info.authority == null) {
5685                                p.info.authority = names[j];
5686                            } else {
5687                                p.info.authority = p.info.authority + ";" + names[j];
5688                            }
5689                            if (DEBUG_PACKAGE_SCANNING) {
5690                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5691                                    Log.d(TAG, "Registered content provider: " + names[j]
5692                                            + ", className = " + p.info.name + ", isSyncable = "
5693                                            + p.info.isSyncable);
5694                            }
5695                        } else {
5696                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5697                            Slog.w(TAG, "Skipping provider name " + names[j] +
5698                                    " (in package " + pkg.applicationInfo.packageName +
5699                                    "): name already used by "
5700                                    + ((other != null && other.getComponentName() != null)
5701                                            ? other.getComponentName().getPackageName() : "?"));
5702                        }
5703                    }
5704                }
5705                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5706                    if (r == null) {
5707                        r = new StringBuilder(256);
5708                    } else {
5709                        r.append(' ');
5710                    }
5711                    r.append(p.info.name);
5712                }
5713            }
5714            if (r != null) {
5715                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5716            }
5717
5718            N = pkg.services.size();
5719            r = null;
5720            for (i=0; i<N; i++) {
5721                PackageParser.Service s = pkg.services.get(i);
5722                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5723                        s.info.processName, pkg.applicationInfo.uid);
5724                mServices.addService(s);
5725                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5726                    if (r == null) {
5727                        r = new StringBuilder(256);
5728                    } else {
5729                        r.append(' ');
5730                    }
5731                    r.append(s.info.name);
5732                }
5733            }
5734            if (r != null) {
5735                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5736            }
5737
5738            N = pkg.receivers.size();
5739            r = null;
5740            for (i=0; i<N; i++) {
5741                PackageParser.Activity a = pkg.receivers.get(i);
5742                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5743                        a.info.processName, pkg.applicationInfo.uid);
5744                mReceivers.addActivity(a, "receiver");
5745                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5746                    if (r == null) {
5747                        r = new StringBuilder(256);
5748                    } else {
5749                        r.append(' ');
5750                    }
5751                    r.append(a.info.name);
5752                }
5753            }
5754            if (r != null) {
5755                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5756            }
5757
5758            N = pkg.activities.size();
5759            r = null;
5760            for (i=0; i<N; i++) {
5761                PackageParser.Activity a = pkg.activities.get(i);
5762                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5763                        a.info.processName, pkg.applicationInfo.uid);
5764                mActivities.addActivity(a, "activity");
5765                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5766                    if (r == null) {
5767                        r = new StringBuilder(256);
5768                    } else {
5769                        r.append(' ');
5770                    }
5771                    r.append(a.info.name);
5772                }
5773            }
5774            if (r != null) {
5775                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5776            }
5777
5778            N = pkg.permissionGroups.size();
5779            r = null;
5780            for (i=0; i<N; i++) {
5781                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5782                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5783                if (cur == null) {
5784                    mPermissionGroups.put(pg.info.name, pg);
5785                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5786                        if (r == null) {
5787                            r = new StringBuilder(256);
5788                        } else {
5789                            r.append(' ');
5790                        }
5791                        r.append(pg.info.name);
5792                    }
5793                } else {
5794                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5795                            + pg.info.packageName + " ignored: original from "
5796                            + cur.info.packageName);
5797                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5798                        if (r == null) {
5799                            r = new StringBuilder(256);
5800                        } else {
5801                            r.append(' ');
5802                        }
5803                        r.append("DUP:");
5804                        r.append(pg.info.name);
5805                    }
5806                }
5807            }
5808            if (r != null) {
5809                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5810            }
5811
5812            N = pkg.permissions.size();
5813            r = null;
5814            for (i=0; i<N; i++) {
5815                PackageParser.Permission p = pkg.permissions.get(i);
5816                HashMap<String, BasePermission> permissionMap =
5817                        p.tree ? mSettings.mPermissionTrees
5818                        : mSettings.mPermissions;
5819                p.group = mPermissionGroups.get(p.info.group);
5820                if (p.info.group == null || p.group != null) {
5821                    BasePermission bp = permissionMap.get(p.info.name);
5822                    if (bp == null) {
5823                        bp = new BasePermission(p.info.name, p.info.packageName,
5824                                BasePermission.TYPE_NORMAL);
5825                        permissionMap.put(p.info.name, bp);
5826                    }
5827                    if (bp.perm == null) {
5828                        if (bp.sourcePackage != null
5829                                && !bp.sourcePackage.equals(p.info.packageName)) {
5830                            // If this is a permission that was formerly defined by a non-system
5831                            // app, but is now defined by a system app (following an upgrade),
5832                            // discard the previous declaration and consider the system's to be
5833                            // canonical.
5834                            if (isSystemApp(p.owner)) {
5835                                String msg = "New decl " + p.owner + " of permission  "
5836                                        + p.info.name + " is system";
5837                                reportSettingsProblem(Log.WARN, msg);
5838                                bp.sourcePackage = null;
5839                            }
5840                        }
5841                        if (bp.sourcePackage == null
5842                                || bp.sourcePackage.equals(p.info.packageName)) {
5843                            BasePermission tree = findPermissionTreeLP(p.info.name);
5844                            if (tree == null
5845                                    || tree.sourcePackage.equals(p.info.packageName)) {
5846                                bp.packageSetting = pkgSetting;
5847                                bp.perm = p;
5848                                bp.uid = pkg.applicationInfo.uid;
5849                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5850                                    if (r == null) {
5851                                        r = new StringBuilder(256);
5852                                    } else {
5853                                        r.append(' ');
5854                                    }
5855                                    r.append(p.info.name);
5856                                }
5857                            } else {
5858                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5859                                        + p.info.packageName + " ignored: base tree "
5860                                        + tree.name + " is from package "
5861                                        + tree.sourcePackage);
5862                            }
5863                        } else {
5864                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5865                                    + p.info.packageName + " ignored: original from "
5866                                    + bp.sourcePackage);
5867                        }
5868                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5869                        if (r == null) {
5870                            r = new StringBuilder(256);
5871                        } else {
5872                            r.append(' ');
5873                        }
5874                        r.append("DUP:");
5875                        r.append(p.info.name);
5876                    }
5877                    if (bp.perm == p) {
5878                        bp.protectionLevel = p.info.protectionLevel;
5879                    }
5880                } else {
5881                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5882                            + p.info.packageName + " ignored: no group "
5883                            + p.group);
5884                }
5885            }
5886            if (r != null) {
5887                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5888            }
5889
5890            N = pkg.instrumentation.size();
5891            r = null;
5892            for (i=0; i<N; i++) {
5893                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5894                a.info.packageName = pkg.applicationInfo.packageName;
5895                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5896                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5897                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5898                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5899                a.info.dataDir = pkg.applicationInfo.dataDir;
5900                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5901                mInstrumentation.put(a.getComponentName(), a);
5902                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5903                    if (r == null) {
5904                        r = new StringBuilder(256);
5905                    } else {
5906                        r.append(' ');
5907                    }
5908                    r.append(a.info.name);
5909                }
5910            }
5911            if (r != null) {
5912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5913            }
5914
5915            if (pkg.protectedBroadcasts != null) {
5916                N = pkg.protectedBroadcasts.size();
5917                for (i=0; i<N; i++) {
5918                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5919                }
5920            }
5921
5922            pkgSetting.setTimeStamp(scanFileTime);
5923
5924            // Create idmap files for pairs of (packages, overlay packages).
5925            // Note: "android", ie framework-res.apk, is handled by native layers.
5926            if (pkg.mOverlayTarget != null) {
5927                // This is an overlay package.
5928                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5929                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5930                        mOverlays.put(pkg.mOverlayTarget,
5931                                new HashMap<String, PackageParser.Package>());
5932                    }
5933                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5934                    map.put(pkg.packageName, pkg);
5935                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5936                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5937                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5938                        return null;
5939                    }
5940                }
5941            } else if (mOverlays.containsKey(pkg.packageName) &&
5942                    !pkg.packageName.equals("android")) {
5943                // This is a regular package, with one or more known overlay packages.
5944                createIdmapsForPackageLI(pkg);
5945            }
5946        }
5947
5948        return pkg;
5949    }
5950
5951    /**
5952     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5953     * i.e, so that all packages can be run inside a single process if required.
5954     *
5955     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5956     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5957     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5958     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5959     * updating a package that belongs to a shared user.
5960     */
5961    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5962            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5963        String requiredInstructionSet = null;
5964        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5965            requiredInstructionSet = VMRuntime.getInstructionSet(
5966                     scannedPackage.applicationInfo.cpuAbi);
5967        }
5968
5969        PackageSetting requirer = null;
5970        for (PackageSetting ps : packagesForUser) {
5971            // If packagesForUser contains scannedPackage, we skip it. This will happen
5972            // when scannedPackage is an update of an existing package. Without this check,
5973            // we will never be able to change the ABI of any package belonging to a shared
5974            // user, even if it's compatible with other packages.
5975            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
5976                if (ps.cpuAbiString == null) {
5977                    continue;
5978                }
5979
5980                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5981                if (requiredInstructionSet != null) {
5982                    if (!instructionSet.equals(requiredInstructionSet)) {
5983                        // We have a mismatch between instruction sets (say arm vs arm64).
5984                        // bail out.
5985                        String errorMessage = "Instruction set mismatch, "
5986                                + ((requirer == null) ? "[caller]" : requirer)
5987                                + " requires " + requiredInstructionSet + " whereas " + ps
5988                                + " requires " + instructionSet;
5989                        Slog.e(TAG, errorMessage);
5990
5991                        reportSettingsProblem(Log.WARN, errorMessage);
5992                        // Give up, don't bother making any other changes to the package settings.
5993                        return false;
5994                    }
5995                } else {
5996                    requiredInstructionSet = instructionSet;
5997                    requirer = ps;
5998                }
5999            }
6000        }
6001
6002        if (requiredInstructionSet != null) {
6003            String adjustedAbi;
6004            if (requirer != null) {
6005                // requirer != null implies that either scannedPackage was null or that scannedPackage
6006                // did not require an ABI, in which case we have to adjust scannedPackage to match
6007                // the ABI of the set (which is the same as requirer's ABI)
6008                adjustedAbi = requirer.cpuAbiString;
6009                if (scannedPackage != null) {
6010                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6011                }
6012            } else {
6013                // requirer == null implies that we're updating all ABIs in the set to
6014                // match scannedPackage.
6015                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6016            }
6017
6018            for (PackageSetting ps : packagesForUser) {
6019                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6020                    if (ps.cpuAbiString != null) {
6021                        continue;
6022                    }
6023
6024                    ps.cpuAbiString = adjustedAbi;
6025                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6026                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6027                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6028
6029                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6030                            ps.cpuAbiString = null;
6031                            ps.pkg.applicationInfo.cpuAbi = null;
6032                            return false;
6033                        } else {
6034                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6035                        }
6036                    }
6037                }
6038            }
6039        }
6040
6041        return true;
6042    }
6043
6044    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6045        synchronized (mPackages) {
6046            mResolverReplaced = true;
6047            // Set up information for custom user intent resolution activity.
6048            mResolveActivity.applicationInfo = pkg.applicationInfo;
6049            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6050            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6051            mResolveActivity.processName = null;
6052            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6053            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6054                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6055            mResolveActivity.theme = 0;
6056            mResolveActivity.exported = true;
6057            mResolveActivity.enabled = true;
6058            mResolveInfo.activityInfo = mResolveActivity;
6059            mResolveInfo.priority = 0;
6060            mResolveInfo.preferredOrder = 0;
6061            mResolveInfo.match = 0;
6062            mResolveComponentName = mCustomResolverComponentName;
6063            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6064                    mResolveComponentName);
6065        }
6066    }
6067
6068    private String calculateApkRoot(final String codePathString) {
6069        final File codePath = new File(codePathString);
6070        final File codeRoot;
6071        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6072            codeRoot = Environment.getRootDirectory();
6073        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6074            codeRoot = Environment.getOemDirectory();
6075        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6076            codeRoot = Environment.getVendorDirectory();
6077        } else {
6078            // Unrecognized code path; take its top real segment as the apk root:
6079            // e.g. /something/app/blah.apk => /something
6080            try {
6081                File f = codePath.getCanonicalFile();
6082                File parent = f.getParentFile();    // non-null because codePath is a file
6083                File tmp;
6084                while ((tmp = parent.getParentFile()) != null) {
6085                    f = parent;
6086                    parent = tmp;
6087                }
6088                codeRoot = f;
6089                Slog.w(TAG, "Unrecognized code path "
6090                        + codePath + " - using " + codeRoot);
6091            } catch (IOException e) {
6092                // Can't canonicalize the lib path -- shenanigans?
6093                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6094                return Environment.getRootDirectory().getPath();
6095            }
6096        }
6097        return codeRoot.getPath();
6098    }
6099
6100    // This is the initial scan-time determination of how to handle a given
6101    // package for purposes of native library location.
6102    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6103            PackageSetting pkgSetting) {
6104        // "bundled" here means system-installed with no overriding update
6105        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6106        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6107        final File libDir;
6108        if (bundledApk) {
6109            // If "/system/lib64/apkname" exists, assume that is the per-package
6110            // native library directory to use; otherwise use "/system/lib/apkname".
6111            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6112            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6113            File packLib64 = new File(lib64, apkName);
6114            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6115        } else {
6116            libDir = mAppLibInstallDir;
6117        }
6118        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6119        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6120        // pkgSetting might be null during rescan following uninstall of updates
6121        // to a bundled app, so accommodate that possibility.  The settings in
6122        // that case will be established later from the parsed package.
6123        if (pkgSetting != null) {
6124            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6125        }
6126    }
6127
6128    // Deduces the required ABI of an upgraded system app.
6129    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6130        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6131        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6132
6133        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6134        // or similar.
6135        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6136        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6137
6138        // Assume that the bundled native libraries always correspond to the
6139        // most preferred 32 or 64 bit ABI.
6140        if (lib64.exists()) {
6141            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6142            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6143        } else if (lib.exists()) {
6144            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6145            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6146        } else {
6147            // This is the case where the app has no native code.
6148            pkg.applicationInfo.cpuAbi = null;
6149            pkgSetting.cpuAbiString = null;
6150        }
6151    }
6152
6153    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6154            final File nativeLibraryDir, String[] abiList) throws IOException {
6155        if (!nativeLibraryDir.isDirectory()) {
6156            nativeLibraryDir.delete();
6157
6158            if (!nativeLibraryDir.mkdir()) {
6159                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6160            }
6161
6162            try {
6163                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6164            } catch (ErrnoException e) {
6165                throw new IOException("Cannot chmod native library directory "
6166                        + nativeLibraryDir.getPath(), e);
6167            }
6168        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6169            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6170        }
6171
6172        /*
6173         * If this is an internal application or our nativeLibraryPath points to
6174         * the app-lib directory, unpack the libraries if necessary.
6175         */
6176        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6177        if (abi >= 0) {
6178            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6179                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6180            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6181                return copyRet;
6182            }
6183        }
6184
6185        return abi;
6186    }
6187
6188    private void killApplication(String pkgName, int appId, String reason) {
6189        // Request the ActivityManager to kill the process(only for existing packages)
6190        // so that we do not end up in a confused state while the user is still using the older
6191        // version of the application while the new one gets installed.
6192        IActivityManager am = ActivityManagerNative.getDefault();
6193        if (am != null) {
6194            try {
6195                am.killApplicationWithAppId(pkgName, appId, reason);
6196            } catch (RemoteException e) {
6197            }
6198        }
6199    }
6200
6201    void removePackageLI(PackageSetting ps, boolean chatty) {
6202        if (DEBUG_INSTALL) {
6203            if (chatty)
6204                Log.d(TAG, "Removing package " + ps.name);
6205        }
6206
6207        // writer
6208        synchronized (mPackages) {
6209            mPackages.remove(ps.name);
6210            if (ps.codePathString != null) {
6211                mAppDirs.remove(ps.codePathString);
6212            }
6213
6214            final PackageParser.Package pkg = ps.pkg;
6215            if (pkg != null) {
6216                cleanPackageDataStructuresLILPw(pkg, chatty);
6217            }
6218        }
6219    }
6220
6221    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6222        if (DEBUG_INSTALL) {
6223            if (chatty)
6224                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6225        }
6226
6227        // writer
6228        synchronized (mPackages) {
6229            mPackages.remove(pkg.applicationInfo.packageName);
6230            if (pkg.codePath != null) {
6231                mAppDirs.remove(pkg.codePath);
6232            }
6233            cleanPackageDataStructuresLILPw(pkg, chatty);
6234        }
6235    }
6236
6237    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6238        int N = pkg.providers.size();
6239        StringBuilder r = null;
6240        int i;
6241        for (i=0; i<N; i++) {
6242            PackageParser.Provider p = pkg.providers.get(i);
6243            mProviders.removeProvider(p);
6244            if (p.info.authority == null) {
6245
6246                /* There was another ContentProvider with this authority when
6247                 * this app was installed so this authority is null,
6248                 * Ignore it as we don't have to unregister the provider.
6249                 */
6250                continue;
6251            }
6252            String names[] = p.info.authority.split(";");
6253            for (int j = 0; j < names.length; j++) {
6254                if (mProvidersByAuthority.get(names[j]) == p) {
6255                    mProvidersByAuthority.remove(names[j]);
6256                    if (DEBUG_REMOVE) {
6257                        if (chatty)
6258                            Log.d(TAG, "Unregistered content provider: " + names[j]
6259                                    + ", className = " + p.info.name + ", isSyncable = "
6260                                    + p.info.isSyncable);
6261                    }
6262                }
6263            }
6264            if (DEBUG_REMOVE && chatty) {
6265                if (r == null) {
6266                    r = new StringBuilder(256);
6267                } else {
6268                    r.append(' ');
6269                }
6270                r.append(p.info.name);
6271            }
6272        }
6273        if (r != null) {
6274            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6275        }
6276
6277        N = pkg.services.size();
6278        r = null;
6279        for (i=0; i<N; i++) {
6280            PackageParser.Service s = pkg.services.get(i);
6281            mServices.removeService(s);
6282            if (chatty) {
6283                if (r == null) {
6284                    r = new StringBuilder(256);
6285                } else {
6286                    r.append(' ');
6287                }
6288                r.append(s.info.name);
6289            }
6290        }
6291        if (r != null) {
6292            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6293        }
6294
6295        N = pkg.receivers.size();
6296        r = null;
6297        for (i=0; i<N; i++) {
6298            PackageParser.Activity a = pkg.receivers.get(i);
6299            mReceivers.removeActivity(a, "receiver");
6300            if (DEBUG_REMOVE && chatty) {
6301                if (r == null) {
6302                    r = new StringBuilder(256);
6303                } else {
6304                    r.append(' ');
6305                }
6306                r.append(a.info.name);
6307            }
6308        }
6309        if (r != null) {
6310            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6311        }
6312
6313        N = pkg.activities.size();
6314        r = null;
6315        for (i=0; i<N; i++) {
6316            PackageParser.Activity a = pkg.activities.get(i);
6317            mActivities.removeActivity(a, "activity");
6318            if (DEBUG_REMOVE && chatty) {
6319                if (r == null) {
6320                    r = new StringBuilder(256);
6321                } else {
6322                    r.append(' ');
6323                }
6324                r.append(a.info.name);
6325            }
6326        }
6327        if (r != null) {
6328            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6329        }
6330
6331        N = pkg.permissions.size();
6332        r = null;
6333        for (i=0; i<N; i++) {
6334            PackageParser.Permission p = pkg.permissions.get(i);
6335            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6336            if (bp == null) {
6337                bp = mSettings.mPermissionTrees.get(p.info.name);
6338            }
6339            if (bp != null && bp.perm == p) {
6340                bp.perm = null;
6341                if (DEBUG_REMOVE && chatty) {
6342                    if (r == null) {
6343                        r = new StringBuilder(256);
6344                    } else {
6345                        r.append(' ');
6346                    }
6347                    r.append(p.info.name);
6348                }
6349            }
6350        }
6351        if (r != null) {
6352            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6353        }
6354
6355        N = pkg.instrumentation.size();
6356        r = null;
6357        for (i=0; i<N; i++) {
6358            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6359            mInstrumentation.remove(a.getComponentName());
6360            if (DEBUG_REMOVE && chatty) {
6361                if (r == null) {
6362                    r = new StringBuilder(256);
6363                } else {
6364                    r.append(' ');
6365                }
6366                r.append(a.info.name);
6367            }
6368        }
6369        if (r != null) {
6370            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6371        }
6372
6373        r = null;
6374        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6375            // Only system apps can hold shared libraries.
6376            if (pkg.libraryNames != null) {
6377                for (i=0; i<pkg.libraryNames.size(); i++) {
6378                    String name = pkg.libraryNames.get(i);
6379                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6380                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6381                        mSharedLibraries.remove(name);
6382                        if (DEBUG_REMOVE && chatty) {
6383                            if (r == null) {
6384                                r = new StringBuilder(256);
6385                            } else {
6386                                r.append(' ');
6387                            }
6388                            r.append(name);
6389                        }
6390                    }
6391                }
6392            }
6393        }
6394        if (r != null) {
6395            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6396        }
6397    }
6398
6399    private static final boolean isPackageFilename(String name) {
6400        return name != null && name.endsWith(".apk");
6401    }
6402
6403    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6404        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6405            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6406                return true;
6407            }
6408        }
6409        return false;
6410    }
6411
6412    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6413    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6414    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6415
6416    private void updatePermissionsLPw(String changingPkg,
6417            PackageParser.Package pkgInfo, int flags) {
6418        // Make sure there are no dangling permission trees.
6419        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6420        while (it.hasNext()) {
6421            final BasePermission bp = it.next();
6422            if (bp.packageSetting == null) {
6423                // We may not yet have parsed the package, so just see if
6424                // we still know about its settings.
6425                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6426            }
6427            if (bp.packageSetting == null) {
6428                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6429                        + " from package " + bp.sourcePackage);
6430                it.remove();
6431            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6432                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6433                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6434                            + " from package " + bp.sourcePackage);
6435                    flags |= UPDATE_PERMISSIONS_ALL;
6436                    it.remove();
6437                }
6438            }
6439        }
6440
6441        // Make sure all dynamic permissions have been assigned to a package,
6442        // and make sure there are no dangling permissions.
6443        it = mSettings.mPermissions.values().iterator();
6444        while (it.hasNext()) {
6445            final BasePermission bp = it.next();
6446            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6447                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6448                        + bp.name + " pkg=" + bp.sourcePackage
6449                        + " info=" + bp.pendingInfo);
6450                if (bp.packageSetting == null && bp.pendingInfo != null) {
6451                    final BasePermission tree = findPermissionTreeLP(bp.name);
6452                    if (tree != null && tree.perm != null) {
6453                        bp.packageSetting = tree.packageSetting;
6454                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6455                                new PermissionInfo(bp.pendingInfo));
6456                        bp.perm.info.packageName = tree.perm.info.packageName;
6457                        bp.perm.info.name = bp.name;
6458                        bp.uid = tree.uid;
6459                    }
6460                }
6461            }
6462            if (bp.packageSetting == null) {
6463                // We may not yet have parsed the package, so just see if
6464                // we still know about its settings.
6465                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6466            }
6467            if (bp.packageSetting == null) {
6468                Slog.w(TAG, "Removing dangling permission: " + bp.name
6469                        + " from package " + bp.sourcePackage);
6470                it.remove();
6471            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6472                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6473                    Slog.i(TAG, "Removing old permission: " + bp.name
6474                            + " from package " + bp.sourcePackage);
6475                    flags |= UPDATE_PERMISSIONS_ALL;
6476                    it.remove();
6477                }
6478            }
6479        }
6480
6481        // Now update the permissions for all packages, in particular
6482        // replace the granted permissions of the system packages.
6483        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6484            for (PackageParser.Package pkg : mPackages.values()) {
6485                if (pkg != pkgInfo) {
6486                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6487                }
6488            }
6489        }
6490
6491        if (pkgInfo != null) {
6492            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6493        }
6494    }
6495
6496    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6497        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6498        if (ps == null) {
6499            return;
6500        }
6501        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6502        HashSet<String> origPermissions = gp.grantedPermissions;
6503        boolean changedPermission = false;
6504
6505        if (replace) {
6506            ps.permissionsFixed = false;
6507            if (gp == ps) {
6508                origPermissions = new HashSet<String>(gp.grantedPermissions);
6509                gp.grantedPermissions.clear();
6510                gp.gids = mGlobalGids;
6511            }
6512        }
6513
6514        if (gp.gids == null) {
6515            gp.gids = mGlobalGids;
6516        }
6517
6518        final int N = pkg.requestedPermissions.size();
6519        for (int i=0; i<N; i++) {
6520            final String name = pkg.requestedPermissions.get(i);
6521            final boolean required = pkg.requestedPermissionsRequired.get(i);
6522            final BasePermission bp = mSettings.mPermissions.get(name);
6523            if (DEBUG_INSTALL) {
6524                if (gp != ps) {
6525                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6526                }
6527            }
6528
6529            if (bp == null || bp.packageSetting == null) {
6530                Slog.w(TAG, "Unknown permission " + name
6531                        + " in package " + pkg.packageName);
6532                continue;
6533            }
6534
6535            final String perm = bp.name;
6536            boolean allowed;
6537            boolean allowedSig = false;
6538            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6539            if (level == PermissionInfo.PROTECTION_NORMAL
6540                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6541                // We grant a normal or dangerous permission if any of the following
6542                // are true:
6543                // 1) The permission is required
6544                // 2) The permission is optional, but was granted in the past
6545                // 3) The permission is optional, but was requested by an
6546                //    app in /system (not /data)
6547                //
6548                // Otherwise, reject the permission.
6549                allowed = (required || origPermissions.contains(perm)
6550                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6551            } else if (bp.packageSetting == null) {
6552                // This permission is invalid; skip it.
6553                allowed = false;
6554            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6555                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6556                if (allowed) {
6557                    allowedSig = true;
6558                }
6559            } else {
6560                allowed = false;
6561            }
6562            if (DEBUG_INSTALL) {
6563                if (gp != ps) {
6564                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6565                }
6566            }
6567            if (allowed) {
6568                if (!isSystemApp(ps) && ps.permissionsFixed) {
6569                    // If this is an existing, non-system package, then
6570                    // we can't add any new permissions to it.
6571                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6572                        // Except...  if this is a permission that was added
6573                        // to the platform (note: need to only do this when
6574                        // updating the platform).
6575                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6576                    }
6577                }
6578                if (allowed) {
6579                    if (!gp.grantedPermissions.contains(perm)) {
6580                        changedPermission = true;
6581                        gp.grantedPermissions.add(perm);
6582                        gp.gids = appendInts(gp.gids, bp.gids);
6583                    } else if (!ps.haveGids) {
6584                        gp.gids = appendInts(gp.gids, bp.gids);
6585                    }
6586                } else {
6587                    Slog.w(TAG, "Not granting permission " + perm
6588                            + " to package " + pkg.packageName
6589                            + " because it was previously installed without");
6590                }
6591            } else {
6592                if (gp.grantedPermissions.remove(perm)) {
6593                    changedPermission = true;
6594                    gp.gids = removeInts(gp.gids, bp.gids);
6595                    Slog.i(TAG, "Un-granting permission " + perm
6596                            + " from package " + pkg.packageName
6597                            + " (protectionLevel=" + bp.protectionLevel
6598                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6599                            + ")");
6600                } else {
6601                    Slog.w(TAG, "Not granting permission " + perm
6602                            + " to package " + pkg.packageName
6603                            + " (protectionLevel=" + bp.protectionLevel
6604                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6605                            + ")");
6606                }
6607            }
6608        }
6609
6610        if ((changedPermission || replace) && !ps.permissionsFixed &&
6611                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6612            // This is the first that we have heard about this package, so the
6613            // permissions we have now selected are fixed until explicitly
6614            // changed.
6615            ps.permissionsFixed = true;
6616        }
6617        ps.haveGids = true;
6618    }
6619
6620    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6621        boolean allowed = false;
6622        final int NP = PackageParser.NEW_PERMISSIONS.length;
6623        for (int ip=0; ip<NP; ip++) {
6624            final PackageParser.NewPermissionInfo npi
6625                    = PackageParser.NEW_PERMISSIONS[ip];
6626            if (npi.name.equals(perm)
6627                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6628                allowed = true;
6629                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6630                        + pkg.packageName);
6631                break;
6632            }
6633        }
6634        return allowed;
6635    }
6636
6637    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6638                                          BasePermission bp, HashSet<String> origPermissions) {
6639        boolean allowed;
6640        allowed = (compareSignatures(
6641                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6642                        == PackageManager.SIGNATURE_MATCH)
6643                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6644                        == PackageManager.SIGNATURE_MATCH);
6645        if (!allowed && (bp.protectionLevel
6646                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6647            if (isSystemApp(pkg)) {
6648                // For updated system applications, a system permission
6649                // is granted only if it had been defined by the original application.
6650                if (isUpdatedSystemApp(pkg)) {
6651                    final PackageSetting sysPs = mSettings
6652                            .getDisabledSystemPkgLPr(pkg.packageName);
6653                    final GrantedPermissions origGp = sysPs.sharedUser != null
6654                            ? sysPs.sharedUser : sysPs;
6655
6656                    if (origGp.grantedPermissions.contains(perm)) {
6657                        // If the original was granted this permission, we take
6658                        // that grant decision as read and propagate it to the
6659                        // update.
6660                        allowed = true;
6661                    } else {
6662                        // The system apk may have been updated with an older
6663                        // version of the one on the data partition, but which
6664                        // granted a new system permission that it didn't have
6665                        // before.  In this case we do want to allow the app to
6666                        // now get the new permission if the ancestral apk is
6667                        // privileged to get it.
6668                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6669                            for (int j=0;
6670                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6671                                if (perm.equals(
6672                                        sysPs.pkg.requestedPermissions.get(j))) {
6673                                    allowed = true;
6674                                    break;
6675                                }
6676                            }
6677                        }
6678                    }
6679                } else {
6680                    allowed = isPrivilegedApp(pkg);
6681                }
6682            }
6683        }
6684        if (!allowed && (bp.protectionLevel
6685                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6686            // For development permissions, a development permission
6687            // is granted only if it was already granted.
6688            allowed = origPermissions.contains(perm);
6689        }
6690        return allowed;
6691    }
6692
6693    final class ActivityIntentResolver
6694            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6695        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6696                boolean defaultOnly, int userId) {
6697            if (!sUserManager.exists(userId)) return null;
6698            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6699            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6700        }
6701
6702        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6703                int userId) {
6704            if (!sUserManager.exists(userId)) return null;
6705            mFlags = flags;
6706            return super.queryIntent(intent, resolvedType,
6707                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6708        }
6709
6710        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6711                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6712            if (!sUserManager.exists(userId)) return null;
6713            if (packageActivities == null) {
6714                return null;
6715            }
6716            mFlags = flags;
6717            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6718            final int N = packageActivities.size();
6719            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6720                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6721
6722            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6723            for (int i = 0; i < N; ++i) {
6724                intentFilters = packageActivities.get(i).intents;
6725                if (intentFilters != null && intentFilters.size() > 0) {
6726                    PackageParser.ActivityIntentInfo[] array =
6727                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6728                    intentFilters.toArray(array);
6729                    listCut.add(array);
6730                }
6731            }
6732            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6733        }
6734
6735        public final void addActivity(PackageParser.Activity a, String type) {
6736            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6737            mActivities.put(a.getComponentName(), a);
6738            if (DEBUG_SHOW_INFO)
6739                Log.v(
6740                TAG, "  " + type + " " +
6741                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6742            if (DEBUG_SHOW_INFO)
6743                Log.v(TAG, "    Class=" + a.info.name);
6744            final int NI = a.intents.size();
6745            for (int j=0; j<NI; j++) {
6746                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6747                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6748                    intent.setPriority(0);
6749                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6750                            + a.className + " with priority > 0, forcing to 0");
6751                }
6752                if (DEBUG_SHOW_INFO) {
6753                    Log.v(TAG, "    IntentFilter:");
6754                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6755                }
6756                if (!intent.debugCheck()) {
6757                    Log.w(TAG, "==> For Activity " + a.info.name);
6758                }
6759                addFilter(intent);
6760            }
6761        }
6762
6763        public final void removeActivity(PackageParser.Activity a, String type) {
6764            mActivities.remove(a.getComponentName());
6765            if (DEBUG_SHOW_INFO) {
6766                Log.v(TAG, "  " + type + " "
6767                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6768                                : a.info.name) + ":");
6769                Log.v(TAG, "    Class=" + a.info.name);
6770            }
6771            final int NI = a.intents.size();
6772            for (int j=0; j<NI; j++) {
6773                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6774                if (DEBUG_SHOW_INFO) {
6775                    Log.v(TAG, "    IntentFilter:");
6776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6777                }
6778                removeFilter(intent);
6779            }
6780        }
6781
6782        @Override
6783        protected boolean allowFilterResult(
6784                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6785            ActivityInfo filterAi = filter.activity.info;
6786            for (int i=dest.size()-1; i>=0; i--) {
6787                ActivityInfo destAi = dest.get(i).activityInfo;
6788                if (destAi.name == filterAi.name
6789                        && destAi.packageName == filterAi.packageName) {
6790                    return false;
6791                }
6792            }
6793            return true;
6794        }
6795
6796        @Override
6797        protected ActivityIntentInfo[] newArray(int size) {
6798            return new ActivityIntentInfo[size];
6799        }
6800
6801        @Override
6802        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6803            if (!sUserManager.exists(userId)) return true;
6804            PackageParser.Package p = filter.activity.owner;
6805            if (p != null) {
6806                PackageSetting ps = (PackageSetting)p.mExtras;
6807                if (ps != null) {
6808                    // System apps are never considered stopped for purposes of
6809                    // filtering, because there may be no way for the user to
6810                    // actually re-launch them.
6811                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6812                            && ps.getStopped(userId);
6813                }
6814            }
6815            return false;
6816        }
6817
6818        @Override
6819        protected boolean isPackageForFilter(String packageName,
6820                PackageParser.ActivityIntentInfo info) {
6821            return packageName.equals(info.activity.owner.packageName);
6822        }
6823
6824        @Override
6825        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6826                int match, int userId) {
6827            if (!sUserManager.exists(userId)) return null;
6828            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6829                return null;
6830            }
6831            final PackageParser.Activity activity = info.activity;
6832            if (mSafeMode && (activity.info.applicationInfo.flags
6833                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6834                return null;
6835            }
6836            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6837            if (ps == null) {
6838                return null;
6839            }
6840            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6841                    ps.readUserState(userId), userId);
6842            if (ai == null) {
6843                return null;
6844            }
6845            final ResolveInfo res = new ResolveInfo();
6846            res.activityInfo = ai;
6847            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6848                res.filter = info;
6849            }
6850            res.priority = info.getPriority();
6851            res.preferredOrder = activity.owner.mPreferredOrder;
6852            //System.out.println("Result: " + res.activityInfo.className +
6853            //                   " = " + res.priority);
6854            res.match = match;
6855            res.isDefault = info.hasDefault;
6856            res.labelRes = info.labelRes;
6857            res.nonLocalizedLabel = info.nonLocalizedLabel;
6858            if (userNeedsBadging(userId)) {
6859                res.noResourceId = true;
6860            } else {
6861                res.icon = info.icon;
6862            }
6863            res.system = isSystemApp(res.activityInfo.applicationInfo);
6864            return res;
6865        }
6866
6867        @Override
6868        protected void sortResults(List<ResolveInfo> results) {
6869            Collections.sort(results, mResolvePrioritySorter);
6870        }
6871
6872        @Override
6873        protected void dumpFilter(PrintWriter out, String prefix,
6874                PackageParser.ActivityIntentInfo filter) {
6875            out.print(prefix); out.print(
6876                    Integer.toHexString(System.identityHashCode(filter.activity)));
6877                    out.print(' ');
6878                    filter.activity.printComponentShortName(out);
6879                    out.print(" filter ");
6880                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6881        }
6882
6883//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6884//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6885//            final List<ResolveInfo> retList = Lists.newArrayList();
6886//            while (i.hasNext()) {
6887//                final ResolveInfo resolveInfo = i.next();
6888//                if (isEnabledLP(resolveInfo.activityInfo)) {
6889//                    retList.add(resolveInfo);
6890//                }
6891//            }
6892//            return retList;
6893//        }
6894
6895        // Keys are String (activity class name), values are Activity.
6896        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6897                = new HashMap<ComponentName, PackageParser.Activity>();
6898        private int mFlags;
6899    }
6900
6901    private final class ServiceIntentResolver
6902            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6903        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6904                boolean defaultOnly, int userId) {
6905            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6906            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6907        }
6908
6909        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6910                int userId) {
6911            if (!sUserManager.exists(userId)) return null;
6912            mFlags = flags;
6913            return super.queryIntent(intent, resolvedType,
6914                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6915        }
6916
6917        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6918                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6919            if (!sUserManager.exists(userId)) return null;
6920            if (packageServices == null) {
6921                return null;
6922            }
6923            mFlags = flags;
6924            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6925            final int N = packageServices.size();
6926            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6927                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6928
6929            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6930            for (int i = 0; i < N; ++i) {
6931                intentFilters = packageServices.get(i).intents;
6932                if (intentFilters != null && intentFilters.size() > 0) {
6933                    PackageParser.ServiceIntentInfo[] array =
6934                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6935                    intentFilters.toArray(array);
6936                    listCut.add(array);
6937                }
6938            }
6939            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6940        }
6941
6942        public final void addService(PackageParser.Service s) {
6943            mServices.put(s.getComponentName(), s);
6944            if (DEBUG_SHOW_INFO) {
6945                Log.v(TAG, "  "
6946                        + (s.info.nonLocalizedLabel != null
6947                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6948                Log.v(TAG, "    Class=" + s.info.name);
6949            }
6950            final int NI = s.intents.size();
6951            int j;
6952            for (j=0; j<NI; j++) {
6953                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6954                if (DEBUG_SHOW_INFO) {
6955                    Log.v(TAG, "    IntentFilter:");
6956                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6957                }
6958                if (!intent.debugCheck()) {
6959                    Log.w(TAG, "==> For Service " + s.info.name);
6960                }
6961                addFilter(intent);
6962            }
6963        }
6964
6965        public final void removeService(PackageParser.Service s) {
6966            mServices.remove(s.getComponentName());
6967            if (DEBUG_SHOW_INFO) {
6968                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6969                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6970                Log.v(TAG, "    Class=" + s.info.name);
6971            }
6972            final int NI = s.intents.size();
6973            int j;
6974            for (j=0; j<NI; j++) {
6975                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6976                if (DEBUG_SHOW_INFO) {
6977                    Log.v(TAG, "    IntentFilter:");
6978                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6979                }
6980                removeFilter(intent);
6981            }
6982        }
6983
6984        @Override
6985        protected boolean allowFilterResult(
6986                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6987            ServiceInfo filterSi = filter.service.info;
6988            for (int i=dest.size()-1; i>=0; i--) {
6989                ServiceInfo destAi = dest.get(i).serviceInfo;
6990                if (destAi.name == filterSi.name
6991                        && destAi.packageName == filterSi.packageName) {
6992                    return false;
6993                }
6994            }
6995            return true;
6996        }
6997
6998        @Override
6999        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7000            return new PackageParser.ServiceIntentInfo[size];
7001        }
7002
7003        @Override
7004        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7005            if (!sUserManager.exists(userId)) return true;
7006            PackageParser.Package p = filter.service.owner;
7007            if (p != null) {
7008                PackageSetting ps = (PackageSetting)p.mExtras;
7009                if (ps != null) {
7010                    // System apps are never considered stopped for purposes of
7011                    // filtering, because there may be no way for the user to
7012                    // actually re-launch them.
7013                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7014                            && ps.getStopped(userId);
7015                }
7016            }
7017            return false;
7018        }
7019
7020        @Override
7021        protected boolean isPackageForFilter(String packageName,
7022                PackageParser.ServiceIntentInfo info) {
7023            return packageName.equals(info.service.owner.packageName);
7024        }
7025
7026        @Override
7027        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7028                int match, int userId) {
7029            if (!sUserManager.exists(userId)) return null;
7030            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7031            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7032                return null;
7033            }
7034            final PackageParser.Service service = info.service;
7035            if (mSafeMode && (service.info.applicationInfo.flags
7036                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7037                return null;
7038            }
7039            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7040            if (ps == null) {
7041                return null;
7042            }
7043            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7044                    ps.readUserState(userId), userId);
7045            if (si == null) {
7046                return null;
7047            }
7048            final ResolveInfo res = new ResolveInfo();
7049            res.serviceInfo = si;
7050            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7051                res.filter = filter;
7052            }
7053            res.priority = info.getPriority();
7054            res.preferredOrder = service.owner.mPreferredOrder;
7055            //System.out.println("Result: " + res.activityInfo.className +
7056            //                   " = " + res.priority);
7057            res.match = match;
7058            res.isDefault = info.hasDefault;
7059            res.labelRes = info.labelRes;
7060            res.nonLocalizedLabel = info.nonLocalizedLabel;
7061            res.icon = info.icon;
7062            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7063            return res;
7064        }
7065
7066        @Override
7067        protected void sortResults(List<ResolveInfo> results) {
7068            Collections.sort(results, mResolvePrioritySorter);
7069        }
7070
7071        @Override
7072        protected void dumpFilter(PrintWriter out, String prefix,
7073                PackageParser.ServiceIntentInfo filter) {
7074            out.print(prefix); out.print(
7075                    Integer.toHexString(System.identityHashCode(filter.service)));
7076                    out.print(' ');
7077                    filter.service.printComponentShortName(out);
7078                    out.print(" filter ");
7079                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7080        }
7081
7082//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7083//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7084//            final List<ResolveInfo> retList = Lists.newArrayList();
7085//            while (i.hasNext()) {
7086//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7087//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7088//                    retList.add(resolveInfo);
7089//                }
7090//            }
7091//            return retList;
7092//        }
7093
7094        // Keys are String (activity class name), values are Activity.
7095        private final HashMap<ComponentName, PackageParser.Service> mServices
7096                = new HashMap<ComponentName, PackageParser.Service>();
7097        private int mFlags;
7098    };
7099
7100    private final class ProviderIntentResolver
7101            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7102        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7103                boolean defaultOnly, int userId) {
7104            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7105            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7106        }
7107
7108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7109                int userId) {
7110            if (!sUserManager.exists(userId))
7111                return null;
7112            mFlags = flags;
7113            return super.queryIntent(intent, resolvedType,
7114                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7115        }
7116
7117        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7118                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7119            if (!sUserManager.exists(userId))
7120                return null;
7121            if (packageProviders == null) {
7122                return null;
7123            }
7124            mFlags = flags;
7125            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7126            final int N = packageProviders.size();
7127            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7128                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7129
7130            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7131            for (int i = 0; i < N; ++i) {
7132                intentFilters = packageProviders.get(i).intents;
7133                if (intentFilters != null && intentFilters.size() > 0) {
7134                    PackageParser.ProviderIntentInfo[] array =
7135                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7136                    intentFilters.toArray(array);
7137                    listCut.add(array);
7138                }
7139            }
7140            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7141        }
7142
7143        public final void addProvider(PackageParser.Provider p) {
7144            if (mProviders.containsKey(p.getComponentName())) {
7145                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7146                return;
7147            }
7148
7149            mProviders.put(p.getComponentName(), p);
7150            if (DEBUG_SHOW_INFO) {
7151                Log.v(TAG, "  "
7152                        + (p.info.nonLocalizedLabel != null
7153                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7154                Log.v(TAG, "    Class=" + p.info.name);
7155            }
7156            final int NI = p.intents.size();
7157            int j;
7158            for (j = 0; j < NI; j++) {
7159                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7160                if (DEBUG_SHOW_INFO) {
7161                    Log.v(TAG, "    IntentFilter:");
7162                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7163                }
7164                if (!intent.debugCheck()) {
7165                    Log.w(TAG, "==> For Provider " + p.info.name);
7166                }
7167                addFilter(intent);
7168            }
7169        }
7170
7171        public final void removeProvider(PackageParser.Provider p) {
7172            mProviders.remove(p.getComponentName());
7173            if (DEBUG_SHOW_INFO) {
7174                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7175                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7176                Log.v(TAG, "    Class=" + p.info.name);
7177            }
7178            final int NI = p.intents.size();
7179            int j;
7180            for (j = 0; j < NI; j++) {
7181                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7182                if (DEBUG_SHOW_INFO) {
7183                    Log.v(TAG, "    IntentFilter:");
7184                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7185                }
7186                removeFilter(intent);
7187            }
7188        }
7189
7190        @Override
7191        protected boolean allowFilterResult(
7192                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7193            ProviderInfo filterPi = filter.provider.info;
7194            for (int i = dest.size() - 1; i >= 0; i--) {
7195                ProviderInfo destPi = dest.get(i).providerInfo;
7196                if (destPi.name == filterPi.name
7197                        && destPi.packageName == filterPi.packageName) {
7198                    return false;
7199                }
7200            }
7201            return true;
7202        }
7203
7204        @Override
7205        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7206            return new PackageParser.ProviderIntentInfo[size];
7207        }
7208
7209        @Override
7210        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7211            if (!sUserManager.exists(userId))
7212                return true;
7213            PackageParser.Package p = filter.provider.owner;
7214            if (p != null) {
7215                PackageSetting ps = (PackageSetting) p.mExtras;
7216                if (ps != null) {
7217                    // System apps are never considered stopped for purposes of
7218                    // filtering, because there may be no way for the user to
7219                    // actually re-launch them.
7220                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7221                            && ps.getStopped(userId);
7222                }
7223            }
7224            return false;
7225        }
7226
7227        @Override
7228        protected boolean isPackageForFilter(String packageName,
7229                PackageParser.ProviderIntentInfo info) {
7230            return packageName.equals(info.provider.owner.packageName);
7231        }
7232
7233        @Override
7234        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7235                int match, int userId) {
7236            if (!sUserManager.exists(userId))
7237                return null;
7238            final PackageParser.ProviderIntentInfo info = filter;
7239            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7240                return null;
7241            }
7242            final PackageParser.Provider provider = info.provider;
7243            if (mSafeMode && (provider.info.applicationInfo.flags
7244                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7245                return null;
7246            }
7247            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7248            if (ps == null) {
7249                return null;
7250            }
7251            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7252                    ps.readUserState(userId), userId);
7253            if (pi == null) {
7254                return null;
7255            }
7256            final ResolveInfo res = new ResolveInfo();
7257            res.providerInfo = pi;
7258            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7259                res.filter = filter;
7260            }
7261            res.priority = info.getPriority();
7262            res.preferredOrder = provider.owner.mPreferredOrder;
7263            res.match = match;
7264            res.isDefault = info.hasDefault;
7265            res.labelRes = info.labelRes;
7266            res.nonLocalizedLabel = info.nonLocalizedLabel;
7267            res.icon = info.icon;
7268            res.system = isSystemApp(res.providerInfo.applicationInfo);
7269            return res;
7270        }
7271
7272        @Override
7273        protected void sortResults(List<ResolveInfo> results) {
7274            Collections.sort(results, mResolvePrioritySorter);
7275        }
7276
7277        @Override
7278        protected void dumpFilter(PrintWriter out, String prefix,
7279                PackageParser.ProviderIntentInfo filter) {
7280            out.print(prefix);
7281            out.print(
7282                    Integer.toHexString(System.identityHashCode(filter.provider)));
7283            out.print(' ');
7284            filter.provider.printComponentShortName(out);
7285            out.print(" filter ");
7286            out.println(Integer.toHexString(System.identityHashCode(filter)));
7287        }
7288
7289        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7290                = new HashMap<ComponentName, PackageParser.Provider>();
7291        private int mFlags;
7292    };
7293
7294    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7295            new Comparator<ResolveInfo>() {
7296        public int compare(ResolveInfo r1, ResolveInfo r2) {
7297            int v1 = r1.priority;
7298            int v2 = r2.priority;
7299            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7300            if (v1 != v2) {
7301                return (v1 > v2) ? -1 : 1;
7302            }
7303            v1 = r1.preferredOrder;
7304            v2 = r2.preferredOrder;
7305            if (v1 != v2) {
7306                return (v1 > v2) ? -1 : 1;
7307            }
7308            if (r1.isDefault != r2.isDefault) {
7309                return r1.isDefault ? -1 : 1;
7310            }
7311            v1 = r1.match;
7312            v2 = r2.match;
7313            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7314            if (v1 != v2) {
7315                return (v1 > v2) ? -1 : 1;
7316            }
7317            if (r1.system != r2.system) {
7318                return r1.system ? -1 : 1;
7319            }
7320            return 0;
7321        }
7322    };
7323
7324    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7325            new Comparator<ProviderInfo>() {
7326        public int compare(ProviderInfo p1, ProviderInfo p2) {
7327            final int v1 = p1.initOrder;
7328            final int v2 = p2.initOrder;
7329            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7330        }
7331    };
7332
7333    static final void sendPackageBroadcast(String action, String pkg,
7334            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7335            int[] userIds) {
7336        IActivityManager am = ActivityManagerNative.getDefault();
7337        if (am != null) {
7338            try {
7339                if (userIds == null) {
7340                    userIds = am.getRunningUserIds();
7341                }
7342                for (int id : userIds) {
7343                    final Intent intent = new Intent(action,
7344                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7345                    if (extras != null) {
7346                        intent.putExtras(extras);
7347                    }
7348                    if (targetPkg != null) {
7349                        intent.setPackage(targetPkg);
7350                    }
7351                    // Modify the UID when posting to other users
7352                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7353                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7354                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7355                        intent.putExtra(Intent.EXTRA_UID, uid);
7356                    }
7357                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7358                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7359                    if (DEBUG_BROADCASTS) {
7360                        RuntimeException here = new RuntimeException("here");
7361                        here.fillInStackTrace();
7362                        Slog.d(TAG, "Sending to user " + id + ": "
7363                                + intent.toShortString(false, true, false, false)
7364                                + " " + intent.getExtras(), here);
7365                    }
7366                    am.broadcastIntent(null, intent, null, finishedReceiver,
7367                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7368                            finishedReceiver != null, false, id);
7369                }
7370            } catch (RemoteException ex) {
7371            }
7372        }
7373    }
7374
7375    /**
7376     * Check if the external storage media is available. This is true if there
7377     * is a mounted external storage medium or if the external storage is
7378     * emulated.
7379     */
7380    private boolean isExternalMediaAvailable() {
7381        return mMediaMounted || Environment.isExternalStorageEmulated();
7382    }
7383
7384    @Override
7385    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7386        // writer
7387        synchronized (mPackages) {
7388            if (!isExternalMediaAvailable()) {
7389                // If the external storage is no longer mounted at this point,
7390                // the caller may not have been able to delete all of this
7391                // packages files and can not delete any more.  Bail.
7392                return null;
7393            }
7394            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7395            if (lastPackage != null) {
7396                pkgs.remove(lastPackage);
7397            }
7398            if (pkgs.size() > 0) {
7399                return pkgs.get(0);
7400            }
7401        }
7402        return null;
7403    }
7404
7405    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7406        if (false) {
7407            RuntimeException here = new RuntimeException("here");
7408            here.fillInStackTrace();
7409            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7410                    + " andCode=" + andCode, here);
7411        }
7412        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7413                userId, andCode ? 1 : 0, packageName));
7414    }
7415
7416    void startCleaningPackages() {
7417        // reader
7418        synchronized (mPackages) {
7419            if (!isExternalMediaAvailable()) {
7420                return;
7421            }
7422            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7423                return;
7424            }
7425        }
7426        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7427        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7428        IActivityManager am = ActivityManagerNative.getDefault();
7429        if (am != null) {
7430            try {
7431                am.startService(null, intent, null, UserHandle.USER_OWNER);
7432            } catch (RemoteException e) {
7433            }
7434        }
7435    }
7436
7437    private final class AppDirObserver extends FileObserver {
7438        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7439            super(path, mask);
7440            mRootDir = path;
7441            mIsRom = isrom;
7442            mIsPrivileged = isPrivileged;
7443        }
7444
7445        public void onEvent(int event, String path) {
7446            String removedPackage = null;
7447            int removedAppId = -1;
7448            int[] removedUsers = null;
7449            String addedPackage = null;
7450            int addedAppId = -1;
7451            int[] addedUsers = null;
7452
7453            // TODO post a message to the handler to obtain serial ordering
7454            synchronized (mInstallLock) {
7455                String fullPathStr = null;
7456                File fullPath = null;
7457                if (path != null) {
7458                    fullPath = new File(mRootDir, path);
7459                    fullPathStr = fullPath.getPath();
7460                }
7461
7462                if (DEBUG_APP_DIR_OBSERVER)
7463                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7464
7465                if (!isPackageFilename(path)) {
7466                    if (DEBUG_APP_DIR_OBSERVER)
7467                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7468                    return;
7469                }
7470
7471                // Ignore packages that are being installed or
7472                // have just been installed.
7473                if (ignoreCodePath(fullPathStr)) {
7474                    return;
7475                }
7476                PackageParser.Package p = null;
7477                PackageSetting ps = null;
7478                // reader
7479                synchronized (mPackages) {
7480                    p = mAppDirs.get(fullPathStr);
7481                    if (p != null) {
7482                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7483                        if (ps != null) {
7484                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7485                        } else {
7486                            removedUsers = sUserManager.getUserIds();
7487                        }
7488                    }
7489                    addedUsers = sUserManager.getUserIds();
7490                }
7491                if ((event&REMOVE_EVENTS) != 0) {
7492                    if (ps != null) {
7493                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7494                        removePackageLI(ps, true);
7495                        removedPackage = ps.name;
7496                        removedAppId = ps.appId;
7497                    }
7498                }
7499
7500                if ((event&ADD_EVENTS) != 0) {
7501                    if (p == null) {
7502                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7503                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7504                        if (mIsRom) {
7505                            flags |= PackageParser.PARSE_IS_SYSTEM
7506                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7507                            if (mIsPrivileged) {
7508                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7509                            }
7510                        }
7511                        p = scanPackageLI(fullPath, flags,
7512                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7513                                System.currentTimeMillis(), UserHandle.ALL, null);
7514                        if (p != null) {
7515                            /*
7516                             * TODO this seems dangerous as the package may have
7517                             * changed since we last acquired the mPackages
7518                             * lock.
7519                             */
7520                            // writer
7521                            synchronized (mPackages) {
7522                                updatePermissionsLPw(p.packageName, p,
7523                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7524                            }
7525                            addedPackage = p.applicationInfo.packageName;
7526                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7527                        }
7528                    }
7529                }
7530
7531                // reader
7532                synchronized (mPackages) {
7533                    mSettings.writeLPr();
7534                }
7535            }
7536
7537            if (removedPackage != null) {
7538                Bundle extras = new Bundle(1);
7539                extras.putInt(Intent.EXTRA_UID, removedAppId);
7540                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7541                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7542                        extras, null, null, removedUsers);
7543            }
7544            if (addedPackage != null) {
7545                Bundle extras = new Bundle(1);
7546                extras.putInt(Intent.EXTRA_UID, addedAppId);
7547                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7548                        extras, null, null, addedUsers);
7549            }
7550        }
7551
7552        private final String mRootDir;
7553        private final boolean mIsRom;
7554        private final boolean mIsPrivileged;
7555    }
7556
7557    /*
7558     * The old-style observer methods all just trampoline to the newer signature with
7559     * expanded install observer API.  The older API continues to work but does not
7560     * supply the additional details of the Observer2 API.
7561     */
7562
7563    /* Called when a downloaded package installation has been confirmed by the user */
7564    public void installPackage(
7565            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7566        installPackageEtc(packageURI, observer, null, flags, null);
7567    }
7568
7569    /* Called when a downloaded package installation has been confirmed by the user */
7570    @Override
7571    public void installPackage(
7572            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7573            final String installerPackageName) {
7574        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7575                installerPackageName, null, null, null);
7576    }
7577
7578    @Override
7579    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7580            int flags, String installerPackageName, Uri verificationURI,
7581            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7582        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7583                VerificationParams.NO_UID, manifestDigest);
7584        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7585                installerPackageName, verificationParams, encryptionParams);
7586    }
7587
7588    @Override
7589    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7590            IPackageInstallObserver observer, int flags, String installerPackageName,
7591            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7592        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7593                installerPackageName, verificationParams, encryptionParams);
7594    }
7595
7596    /*
7597     * And here are the "live" versions that take both observer arguments
7598     */
7599    public void installPackageEtc(
7600            final Uri packageURI, final IPackageInstallObserver observer,
7601            IPackageInstallObserver2 observer2, final int flags) {
7602        installPackageEtc(packageURI, observer, observer2, flags, null);
7603    }
7604
7605    public void installPackageEtc(
7606            final Uri packageURI, final IPackageInstallObserver observer,
7607            final IPackageInstallObserver2 observer2, final int flags,
7608            final String installerPackageName) {
7609        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7610                installerPackageName, null, null, null);
7611    }
7612
7613    @Override
7614    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7615            IPackageInstallObserver2 observer2,
7616            int flags, String installerPackageName, Uri verificationURI,
7617            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7618        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7619                VerificationParams.NO_UID, manifestDigest);
7620        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7621                installerPackageName, verificationParams, encryptionParams);
7622    }
7623
7624    /*
7625     * All of the installPackage...*() methods redirect to this one for the master implementation
7626     */
7627    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7628            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7629            int flags, String installerPackageName,
7630            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7631        if (observer == null && observer2 == null) {
7632            throw new IllegalArgumentException("No install observer supplied");
7633        }
7634        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7635                flags, installerPackageName, verificationParams, encryptionParams, null);
7636    }
7637
7638    @Override
7639    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7640            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7641            int flags, String installerPackageName,
7642            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7643            String packageAbiOverride) {
7644        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7645                null);
7646
7647        final int uid = Binder.getCallingUid();
7648        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7649            try {
7650                if (observer != null) {
7651                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7652                }
7653                if (observer2 != null) {
7654                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7655                }
7656            } catch (RemoteException re) {
7657            }
7658            return;
7659        }
7660
7661        UserHandle user;
7662        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7663            user = UserHandle.ALL;
7664        } else {
7665            user = new UserHandle(UserHandle.getUserId(uid));
7666        }
7667
7668        final int filteredFlags;
7669
7670        if (uid == Process.SHELL_UID || uid == 0) {
7671            if (DEBUG_INSTALL) {
7672                Slog.v(TAG, "Install from ADB");
7673            }
7674            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7675        } else {
7676            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7677        }
7678
7679        verificationParams.setInstallerUid(uid);
7680
7681        final Message msg = mHandler.obtainMessage(INIT_COPY);
7682        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7683                installerPackageName, verificationParams, encryptionParams, user,
7684                packageAbiOverride);
7685        mHandler.sendMessage(msg);
7686    }
7687
7688    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7689        Bundle extras = new Bundle(1);
7690        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7691
7692        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7693                packageName, extras, null, null, new int[] {userId});
7694        try {
7695            IActivityManager am = ActivityManagerNative.getDefault();
7696            final boolean isSystem =
7697                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7698            if (isSystem && am.isUserRunning(userId, false)) {
7699                // The just-installed/enabled app is bundled on the system, so presumed
7700                // to be able to run automatically without needing an explicit launch.
7701                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7702                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7703                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7704                        .setPackage(packageName);
7705                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7706                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7707            }
7708        } catch (RemoteException e) {
7709            // shouldn't happen
7710            Slog.w(TAG, "Unable to bootstrap installed package", e);
7711        }
7712    }
7713
7714    @Override
7715    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7716            int userId) {
7717        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7718        PackageSetting pkgSetting;
7719        final int uid = Binder.getCallingUid();
7720        if (UserHandle.getUserId(uid) != userId) {
7721            mContext.enforceCallingOrSelfPermission(
7722                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7723                    "setApplicationBlockedSetting for user " + userId);
7724        }
7725
7726        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7727            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7728            return false;
7729        }
7730
7731        long callingId = Binder.clearCallingIdentity();
7732        try {
7733            boolean sendAdded = false;
7734            boolean sendRemoved = false;
7735            // writer
7736            synchronized (mPackages) {
7737                pkgSetting = mSettings.mPackages.get(packageName);
7738                if (pkgSetting == null) {
7739                    return false;
7740                }
7741                if (pkgSetting.getBlocked(userId) != blocked) {
7742                    pkgSetting.setBlocked(blocked, userId);
7743                    mSettings.writePackageRestrictionsLPr(userId);
7744                    if (blocked) {
7745                        sendRemoved = true;
7746                    } else {
7747                        sendAdded = true;
7748                    }
7749                }
7750            }
7751            if (sendAdded) {
7752                sendPackageAddedForUser(packageName, pkgSetting, userId);
7753                return true;
7754            }
7755            if (sendRemoved) {
7756                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7757                        "blocking pkg");
7758                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7759            }
7760        } finally {
7761            Binder.restoreCallingIdentity(callingId);
7762        }
7763        return false;
7764    }
7765
7766    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7767            int userId) {
7768        final PackageRemovedInfo info = new PackageRemovedInfo();
7769        info.removedPackage = packageName;
7770        info.removedUsers = new int[] {userId};
7771        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7772        info.sendBroadcast(false, false, false);
7773    }
7774
7775    /**
7776     * Returns true if application is not found or there was an error. Otherwise it returns
7777     * the blocked state of the package for the given user.
7778     */
7779    @Override
7780    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7781        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7782        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7783                "getApplicationBlocked for user " + userId);
7784        PackageSetting pkgSetting;
7785        long callingId = Binder.clearCallingIdentity();
7786        try {
7787            // writer
7788            synchronized (mPackages) {
7789                pkgSetting = mSettings.mPackages.get(packageName);
7790                if (pkgSetting == null) {
7791                    return true;
7792                }
7793                return pkgSetting.getBlocked(userId);
7794            }
7795        } finally {
7796            Binder.restoreCallingIdentity(callingId);
7797        }
7798    }
7799
7800    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7801            int flags) {
7802        // TODO: install stage!
7803        try {
7804            observer.packageInstalled(basePackageName, null,
7805                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7806        } catch (RemoteException ignored) {
7807        }
7808    }
7809
7810    /**
7811     * @hide
7812     */
7813    @Override
7814    public int installExistingPackageAsUser(String packageName, int userId) {
7815        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7816                null);
7817        PackageSetting pkgSetting;
7818        final int uid = Binder.getCallingUid();
7819        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7820        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7821            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7822        }
7823
7824        long callingId = Binder.clearCallingIdentity();
7825        try {
7826            boolean sendAdded = false;
7827            Bundle extras = new Bundle(1);
7828
7829            // writer
7830            synchronized (mPackages) {
7831                pkgSetting = mSettings.mPackages.get(packageName);
7832                if (pkgSetting == null) {
7833                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7834                }
7835                if (!pkgSetting.getInstalled(userId)) {
7836                    pkgSetting.setInstalled(true, userId);
7837                    pkgSetting.setBlocked(false, userId);
7838                    mSettings.writePackageRestrictionsLPr(userId);
7839                    sendAdded = true;
7840                }
7841            }
7842
7843            if (sendAdded) {
7844                sendPackageAddedForUser(packageName, pkgSetting, userId);
7845            }
7846        } finally {
7847            Binder.restoreCallingIdentity(callingId);
7848        }
7849
7850        return PackageManager.INSTALL_SUCCEEDED;
7851    }
7852
7853    boolean isUserRestricted(int userId, String restrictionKey) {
7854        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7855        if (restrictions.getBoolean(restrictionKey, false)) {
7856            Log.w(TAG, "User is restricted: " + restrictionKey);
7857            return true;
7858        }
7859        return false;
7860    }
7861
7862    @Override
7863    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7864        mContext.enforceCallingOrSelfPermission(
7865                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7866                "Only package verification agents can verify applications");
7867
7868        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7869        final PackageVerificationResponse response = new PackageVerificationResponse(
7870                verificationCode, Binder.getCallingUid());
7871        msg.arg1 = id;
7872        msg.obj = response;
7873        mHandler.sendMessage(msg);
7874    }
7875
7876    @Override
7877    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7878            long millisecondsToDelay) {
7879        mContext.enforceCallingOrSelfPermission(
7880                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7881                "Only package verification agents can extend verification timeouts");
7882
7883        final PackageVerificationState state = mPendingVerification.get(id);
7884        final PackageVerificationResponse response = new PackageVerificationResponse(
7885                verificationCodeAtTimeout, Binder.getCallingUid());
7886
7887        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7888            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7889        }
7890        if (millisecondsToDelay < 0) {
7891            millisecondsToDelay = 0;
7892        }
7893        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7894                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7895            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7896        }
7897
7898        if ((state != null) && !state.timeoutExtended()) {
7899            state.extendTimeout();
7900
7901            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7902            msg.arg1 = id;
7903            msg.obj = response;
7904            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7905        }
7906    }
7907
7908    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7909            int verificationCode, UserHandle user) {
7910        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7911        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7912        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7913        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7914        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7915
7916        mContext.sendBroadcastAsUser(intent, user,
7917                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7918    }
7919
7920    private ComponentName matchComponentForVerifier(String packageName,
7921            List<ResolveInfo> receivers) {
7922        ActivityInfo targetReceiver = null;
7923
7924        final int NR = receivers.size();
7925        for (int i = 0; i < NR; i++) {
7926            final ResolveInfo info = receivers.get(i);
7927            if (info.activityInfo == null) {
7928                continue;
7929            }
7930
7931            if (packageName.equals(info.activityInfo.packageName)) {
7932                targetReceiver = info.activityInfo;
7933                break;
7934            }
7935        }
7936
7937        if (targetReceiver == null) {
7938            return null;
7939        }
7940
7941        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7942    }
7943
7944    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7945            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7946        if (pkgInfo.verifiers.length == 0) {
7947            return null;
7948        }
7949
7950        final int N = pkgInfo.verifiers.length;
7951        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7952        for (int i = 0; i < N; i++) {
7953            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7954
7955            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7956                    receivers);
7957            if (comp == null) {
7958                continue;
7959            }
7960
7961            final int verifierUid = getUidForVerifier(verifierInfo);
7962            if (verifierUid == -1) {
7963                continue;
7964            }
7965
7966            if (DEBUG_VERIFY) {
7967                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7968                        + " with the correct signature");
7969            }
7970            sufficientVerifiers.add(comp);
7971            verificationState.addSufficientVerifier(verifierUid);
7972        }
7973
7974        return sufficientVerifiers;
7975    }
7976
7977    private int getUidForVerifier(VerifierInfo verifierInfo) {
7978        synchronized (mPackages) {
7979            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7980            if (pkg == null) {
7981                return -1;
7982            } else if (pkg.mSignatures.length != 1) {
7983                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7984                        + " has more than one signature; ignoring");
7985                return -1;
7986            }
7987
7988            /*
7989             * If the public key of the package's signature does not match
7990             * our expected public key, then this is a different package and
7991             * we should skip.
7992             */
7993
7994            final byte[] expectedPublicKey;
7995            try {
7996                final Signature verifierSig = pkg.mSignatures[0];
7997                final PublicKey publicKey = verifierSig.getPublicKey();
7998                expectedPublicKey = publicKey.getEncoded();
7999            } catch (CertificateException e) {
8000                return -1;
8001            }
8002
8003            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8004
8005            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8006                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8007                        + " does not have the expected public key; ignoring");
8008                return -1;
8009            }
8010
8011            return pkg.applicationInfo.uid;
8012        }
8013    }
8014
8015    @Override
8016    public void finishPackageInstall(int token) {
8017        enforceSystemOrRoot("Only the system is allowed to finish installs");
8018
8019        if (DEBUG_INSTALL) {
8020            Slog.v(TAG, "BM finishing package install for " + token);
8021        }
8022
8023        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8024        mHandler.sendMessage(msg);
8025    }
8026
8027    /**
8028     * Get the verification agent timeout.
8029     *
8030     * @return verification timeout in milliseconds
8031     */
8032    private long getVerificationTimeout() {
8033        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8034                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8035                DEFAULT_VERIFICATION_TIMEOUT);
8036    }
8037
8038    /**
8039     * Get the default verification agent response code.
8040     *
8041     * @return default verification response code
8042     */
8043    private int getDefaultVerificationResponse() {
8044        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8045                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8046                DEFAULT_VERIFICATION_RESPONSE);
8047    }
8048
8049    /**
8050     * Check whether or not package verification has been enabled.
8051     *
8052     * @return true if verification should be performed
8053     */
8054    private boolean isVerificationEnabled(int userId, int flags) {
8055        if (!DEFAULT_VERIFY_ENABLE) {
8056            return false;
8057        }
8058
8059        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8060
8061        // Check if installing from ADB
8062        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8063            // Do not run verification in a test harness environment
8064            if (ActivityManager.isRunningInTestHarness()) {
8065                return false;
8066            }
8067            if (ensureVerifyAppsEnabled) {
8068                return true;
8069            }
8070            // Check if the developer does not want package verification for ADB installs
8071            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8072                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8073                return false;
8074            }
8075        }
8076
8077        if (ensureVerifyAppsEnabled) {
8078            return true;
8079        }
8080
8081        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8082                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8083    }
8084
8085    /**
8086     * Get the "allow unknown sources" setting.
8087     *
8088     * @return the current "allow unknown sources" setting
8089     */
8090    private int getUnknownSourcesSettings() {
8091        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8092                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8093                -1);
8094    }
8095
8096    @Override
8097    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8098        final int uid = Binder.getCallingUid();
8099        // writer
8100        synchronized (mPackages) {
8101            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8102            if (targetPackageSetting == null) {
8103                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8104            }
8105
8106            PackageSetting installerPackageSetting;
8107            if (installerPackageName != null) {
8108                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8109                if (installerPackageSetting == null) {
8110                    throw new IllegalArgumentException("Unknown installer package: "
8111                            + installerPackageName);
8112                }
8113            } else {
8114                installerPackageSetting = null;
8115            }
8116
8117            Signature[] callerSignature;
8118            Object obj = mSettings.getUserIdLPr(uid);
8119            if (obj != null) {
8120                if (obj instanceof SharedUserSetting) {
8121                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8122                } else if (obj instanceof PackageSetting) {
8123                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8124                } else {
8125                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8126                }
8127            } else {
8128                throw new SecurityException("Unknown calling uid " + uid);
8129            }
8130
8131            // Verify: can't set installerPackageName to a package that is
8132            // not signed with the same cert as the caller.
8133            if (installerPackageSetting != null) {
8134                if (compareSignatures(callerSignature,
8135                        installerPackageSetting.signatures.mSignatures)
8136                        != PackageManager.SIGNATURE_MATCH) {
8137                    throw new SecurityException(
8138                            "Caller does not have same cert as new installer package "
8139                            + installerPackageName);
8140                }
8141            }
8142
8143            // Verify: if target already has an installer package, it must
8144            // be signed with the same cert as the caller.
8145            if (targetPackageSetting.installerPackageName != null) {
8146                PackageSetting setting = mSettings.mPackages.get(
8147                        targetPackageSetting.installerPackageName);
8148                // If the currently set package isn't valid, then it's always
8149                // okay to change it.
8150                if (setting != null) {
8151                    if (compareSignatures(callerSignature,
8152                            setting.signatures.mSignatures)
8153                            != PackageManager.SIGNATURE_MATCH) {
8154                        throw new SecurityException(
8155                                "Caller does not have same cert as old installer package "
8156                                + targetPackageSetting.installerPackageName);
8157                    }
8158                }
8159            }
8160
8161            // Okay!
8162            targetPackageSetting.installerPackageName = installerPackageName;
8163            scheduleWriteSettingsLocked();
8164        }
8165    }
8166
8167    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8168        // Queue up an async operation since the package installation may take a little while.
8169        mHandler.post(new Runnable() {
8170            public void run() {
8171                mHandler.removeCallbacks(this);
8172                 // Result object to be returned
8173                PackageInstalledInfo res = new PackageInstalledInfo();
8174                res.returnCode = currentStatus;
8175                res.uid = -1;
8176                res.pkg = null;
8177                res.removedInfo = new PackageRemovedInfo();
8178                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8179                    args.doPreInstall(res.returnCode);
8180                    synchronized (mInstallLock) {
8181                        installPackageLI(args, true, res);
8182                    }
8183                    args.doPostInstall(res.returnCode, res.uid);
8184                }
8185
8186                // A restore should be performed at this point if (a) the install
8187                // succeeded, (b) the operation is not an update, and (c) the new
8188                // package has a backupAgent defined.
8189                final boolean update = res.removedInfo.removedPackage != null;
8190                boolean doRestore = (!update
8191                        && res.pkg != null
8192                        && res.pkg.applicationInfo.backupAgentName != null);
8193
8194                // Set up the post-install work request bookkeeping.  This will be used
8195                // and cleaned up by the post-install event handling regardless of whether
8196                // there's a restore pass performed.  Token values are >= 1.
8197                int token;
8198                if (mNextInstallToken < 0) mNextInstallToken = 1;
8199                token = mNextInstallToken++;
8200
8201                PostInstallData data = new PostInstallData(args, res);
8202                mRunningInstalls.put(token, data);
8203                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8204
8205                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8206                    // Pass responsibility to the Backup Manager.  It will perform a
8207                    // restore if appropriate, then pass responsibility back to the
8208                    // Package Manager to run the post-install observer callbacks
8209                    // and broadcasts.
8210                    IBackupManager bm = IBackupManager.Stub.asInterface(
8211                            ServiceManager.getService(Context.BACKUP_SERVICE));
8212                    if (bm != null) {
8213                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8214                                + " to BM for possible restore");
8215                        try {
8216                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8217                        } catch (RemoteException e) {
8218                            // can't happen; the backup manager is local
8219                        } catch (Exception e) {
8220                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8221                            doRestore = false;
8222                        }
8223                    } else {
8224                        Slog.e(TAG, "Backup Manager not found!");
8225                        doRestore = false;
8226                    }
8227                }
8228
8229                if (!doRestore) {
8230                    // No restore possible, or the Backup Manager was mysteriously not
8231                    // available -- just fire the post-install work request directly.
8232                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8233                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8234                    mHandler.sendMessage(msg);
8235                }
8236            }
8237        });
8238    }
8239
8240    private abstract class HandlerParams {
8241        private static final int MAX_RETRIES = 4;
8242
8243        /**
8244         * Number of times startCopy() has been attempted and had a non-fatal
8245         * error.
8246         */
8247        private int mRetries = 0;
8248
8249        /** User handle for the user requesting the information or installation. */
8250        private final UserHandle mUser;
8251
8252        HandlerParams(UserHandle user) {
8253            mUser = user;
8254        }
8255
8256        UserHandle getUser() {
8257            return mUser;
8258        }
8259
8260        final boolean startCopy() {
8261            boolean res;
8262            try {
8263                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8264
8265                if (++mRetries > MAX_RETRIES) {
8266                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8267                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8268                    handleServiceError();
8269                    return false;
8270                } else {
8271                    handleStartCopy();
8272                    res = true;
8273                }
8274            } catch (RemoteException e) {
8275                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8276                mHandler.sendEmptyMessage(MCS_RECONNECT);
8277                res = false;
8278            }
8279            handleReturnCode();
8280            return res;
8281        }
8282
8283        final void serviceError() {
8284            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8285            handleServiceError();
8286            handleReturnCode();
8287        }
8288
8289        abstract void handleStartCopy() throws RemoteException;
8290        abstract void handleServiceError();
8291        abstract void handleReturnCode();
8292    }
8293
8294    class MeasureParams extends HandlerParams {
8295        private final PackageStats mStats;
8296        private boolean mSuccess;
8297
8298        private final IPackageStatsObserver mObserver;
8299
8300        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8301            super(new UserHandle(stats.userHandle));
8302            mObserver = observer;
8303            mStats = stats;
8304        }
8305
8306        @Override
8307        public String toString() {
8308            return "MeasureParams{"
8309                + Integer.toHexString(System.identityHashCode(this))
8310                + " " + mStats.packageName + "}";
8311        }
8312
8313        @Override
8314        void handleStartCopy() throws RemoteException {
8315            synchronized (mInstallLock) {
8316                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8317            }
8318
8319            if (mSuccess) {
8320                final boolean mounted;
8321                if (Environment.isExternalStorageEmulated()) {
8322                    mounted = true;
8323                } else {
8324                    final String status = Environment.getExternalStorageState();
8325                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8326                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8327                }
8328
8329                if (mounted) {
8330                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8331
8332                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8333                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8334
8335                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8336                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8337
8338                    // Always subtract cache size, since it's a subdirectory
8339                    mStats.externalDataSize -= mStats.externalCacheSize;
8340
8341                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8342                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8343
8344                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8345                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8346                }
8347            }
8348        }
8349
8350        @Override
8351        void handleReturnCode() {
8352            if (mObserver != null) {
8353                try {
8354                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8355                } catch (RemoteException e) {
8356                    Slog.i(TAG, "Observer no longer exists.");
8357                }
8358            }
8359        }
8360
8361        @Override
8362        void handleServiceError() {
8363            Slog.e(TAG, "Could not measure application " + mStats.packageName
8364                            + " external storage");
8365        }
8366    }
8367
8368    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8369            throws RemoteException {
8370        long result = 0;
8371        for (File path : paths) {
8372            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8373        }
8374        return result;
8375    }
8376
8377    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8378        for (File path : paths) {
8379            try {
8380                mcs.clearDirectory(path.getAbsolutePath());
8381            } catch (RemoteException e) {
8382            }
8383        }
8384    }
8385
8386    class InstallParams extends HandlerParams {
8387        final IPackageInstallObserver observer;
8388        final IPackageInstallObserver2 observer2;
8389        int flags;
8390
8391        private final Uri mPackageURI;
8392        final String installerPackageName;
8393        final VerificationParams verificationParams;
8394        private InstallArgs mArgs;
8395        private int mRet;
8396        private File mTempPackage;
8397        final ContainerEncryptionParams encryptionParams;
8398        final String packageAbiOverride;
8399        final String packageInstructionSetOverride;
8400
8401        InstallParams(Uri packageURI,
8402                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8403                int flags, String installerPackageName, VerificationParams verificationParams,
8404                ContainerEncryptionParams encryptionParams, UserHandle user,
8405                String packageAbiOverride) {
8406            super(user);
8407            this.mPackageURI = packageURI;
8408            this.flags = flags;
8409            this.observer = observer;
8410            this.observer2 = observer2;
8411            this.installerPackageName = installerPackageName;
8412            this.verificationParams = verificationParams;
8413            this.encryptionParams = encryptionParams;
8414            this.packageAbiOverride = packageAbiOverride;
8415            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8416                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8417        }
8418
8419        @Override
8420        public String toString() {
8421            return "InstallParams{"
8422                + Integer.toHexString(System.identityHashCode(this))
8423                + " " + mPackageURI + "}";
8424        }
8425
8426        public ManifestDigest getManifestDigest() {
8427            if (verificationParams == null) {
8428                return null;
8429            }
8430            return verificationParams.getManifestDigest();
8431        }
8432
8433        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8434            String packageName = pkgLite.packageName;
8435            int installLocation = pkgLite.installLocation;
8436            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8437            // reader
8438            synchronized (mPackages) {
8439                PackageParser.Package pkg = mPackages.get(packageName);
8440                if (pkg != null) {
8441                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8442                        // Check for downgrading.
8443                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8444                            if (pkgLite.versionCode < pkg.mVersionCode) {
8445                                Slog.w(TAG, "Can't install update of " + packageName
8446                                        + " update version " + pkgLite.versionCode
8447                                        + " is older than installed version "
8448                                        + pkg.mVersionCode);
8449                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8450                            }
8451                        }
8452                        // Check for updated system application.
8453                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8454                            if (onSd) {
8455                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8456                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8457                            }
8458                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8459                        } else {
8460                            if (onSd) {
8461                                // Install flag overrides everything.
8462                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8463                            }
8464                            // If current upgrade specifies particular preference
8465                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8466                                // Application explicitly specified internal.
8467                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8468                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8469                                // App explictly prefers external. Let policy decide
8470                            } else {
8471                                // Prefer previous location
8472                                if (isExternal(pkg)) {
8473                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8474                                }
8475                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8476                            }
8477                        }
8478                    } else {
8479                        // Invalid install. Return error code
8480                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8481                    }
8482                }
8483            }
8484            // All the special cases have been taken care of.
8485            // Return result based on recommended install location.
8486            if (onSd) {
8487                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8488            }
8489            return pkgLite.recommendedInstallLocation;
8490        }
8491
8492        private long getMemoryLowThreshold() {
8493            final DeviceStorageMonitorInternal
8494                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8495            if (dsm == null) {
8496                return 0L;
8497            }
8498            return dsm.getMemoryLowThreshold();
8499        }
8500
8501        /*
8502         * Invoke remote method to get package information and install
8503         * location values. Override install location based on default
8504         * policy if needed and then create install arguments based
8505         * on the install location.
8506         */
8507        public void handleStartCopy() throws RemoteException {
8508            int ret = PackageManager.INSTALL_SUCCEEDED;
8509            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8510            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8511            PackageInfoLite pkgLite = null;
8512
8513            if (onInt && onSd) {
8514                // Check if both bits are set.
8515                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8516                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8517            } else {
8518                final long lowThreshold = getMemoryLowThreshold();
8519                if (lowThreshold == 0L) {
8520                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8521                }
8522
8523                try {
8524                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8525                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8526
8527                    final File packageFile;
8528                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8529                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8530                        if (mTempPackage != null) {
8531                            ParcelFileDescriptor out;
8532                            try {
8533                                out = ParcelFileDescriptor.open(mTempPackage,
8534                                        ParcelFileDescriptor.MODE_READ_WRITE);
8535                            } catch (FileNotFoundException e) {
8536                                out = null;
8537                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8538                            }
8539
8540                            // Make a temporary file for decryption.
8541                            ret = mContainerService
8542                                    .copyResource(mPackageURI, encryptionParams, out);
8543                            IoUtils.closeQuietly(out);
8544
8545                            packageFile = mTempPackage;
8546
8547                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8548                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8549                                            | FileUtils.S_IROTH,
8550                                    -1, -1);
8551                        } else {
8552                            packageFile = null;
8553                        }
8554                    } else {
8555                        packageFile = new File(mPackageURI.getPath());
8556                    }
8557
8558                    if (packageFile != null) {
8559                        // Remote call to find out default install location
8560                        final String packageFilePath = packageFile.getAbsolutePath();
8561                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8562                                lowThreshold, packageAbiOverride);
8563
8564                        /*
8565                         * If we have too little free space, try to free cache
8566                         * before giving up.
8567                         */
8568                        if (pkgLite.recommendedInstallLocation
8569                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8570                            final long size = mContainerService.calculateInstalledSize(
8571                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8572                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8573                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8574                                        flags, lowThreshold, packageAbiOverride);
8575                            }
8576                            /*
8577                             * The cache free must have deleted the file we
8578                             * downloaded to install.
8579                             *
8580                             * TODO: fix the "freeCache" call to not delete
8581                             *       the file we care about.
8582                             */
8583                            if (pkgLite.recommendedInstallLocation
8584                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8585                                pkgLite.recommendedInstallLocation
8586                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8587                            }
8588                        }
8589                    }
8590                } finally {
8591                    mContext.revokeUriPermission(mPackageURI,
8592                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8593                }
8594            }
8595
8596            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8597                int loc = pkgLite.recommendedInstallLocation;
8598                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8599                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8600                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8601                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8602                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8603                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8604                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8605                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8606                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8607                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8608                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8609                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8610                } else {
8611                    // Override with defaults if needed.
8612                    loc = installLocationPolicy(pkgLite, flags);
8613                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8614                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8615                    } else if (!onSd && !onInt) {
8616                        // Override install location with flags
8617                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8618                            // Set the flag to install on external media.
8619                            flags |= PackageManager.INSTALL_EXTERNAL;
8620                            flags &= ~PackageManager.INSTALL_INTERNAL;
8621                        } else {
8622                            // Make sure the flag for installing on external
8623                            // media is unset
8624                            flags |= PackageManager.INSTALL_INTERNAL;
8625                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8626                        }
8627                    }
8628                }
8629            }
8630
8631            final InstallArgs args = createInstallArgs(this);
8632            mArgs = args;
8633
8634            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8635                 /*
8636                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8637                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8638                 */
8639                int userIdentifier = getUser().getIdentifier();
8640                if (userIdentifier == UserHandle.USER_ALL
8641                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8642                    userIdentifier = UserHandle.USER_OWNER;
8643                }
8644
8645                /*
8646                 * Determine if we have any installed package verifiers. If we
8647                 * do, then we'll defer to them to verify the packages.
8648                 */
8649                final int requiredUid = mRequiredVerifierPackage == null ? -1
8650                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8651                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8652                    final Intent verification = new Intent(
8653                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8654                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8655                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8656
8657                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8658                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8659                            0 /* TODO: Which userId? */);
8660
8661                    if (DEBUG_VERIFY) {
8662                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8663                                + verification.toString() + " with " + pkgLite.verifiers.length
8664                                + " optional verifiers");
8665                    }
8666
8667                    final int verificationId = mPendingVerificationToken++;
8668
8669                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8670
8671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8672                            installerPackageName);
8673
8674                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8675
8676                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8677                            pkgLite.packageName);
8678
8679                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8680                            pkgLite.versionCode);
8681
8682                    if (verificationParams != null) {
8683                        if (verificationParams.getVerificationURI() != null) {
8684                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8685                                 verificationParams.getVerificationURI());
8686                        }
8687                        if (verificationParams.getOriginatingURI() != null) {
8688                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8689                                  verificationParams.getOriginatingURI());
8690                        }
8691                        if (verificationParams.getReferrer() != null) {
8692                            verification.putExtra(Intent.EXTRA_REFERRER,
8693                                  verificationParams.getReferrer());
8694                        }
8695                        if (verificationParams.getOriginatingUid() >= 0) {
8696                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8697                                  verificationParams.getOriginatingUid());
8698                        }
8699                        if (verificationParams.getInstallerUid() >= 0) {
8700                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8701                                  verificationParams.getInstallerUid());
8702                        }
8703                    }
8704
8705                    final PackageVerificationState verificationState = new PackageVerificationState(
8706                            requiredUid, args);
8707
8708                    mPendingVerification.append(verificationId, verificationState);
8709
8710                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8711                            receivers, verificationState);
8712
8713                    /*
8714                     * If any sufficient verifiers were listed in the package
8715                     * manifest, attempt to ask them.
8716                     */
8717                    if (sufficientVerifiers != null) {
8718                        final int N = sufficientVerifiers.size();
8719                        if (N == 0) {
8720                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8721                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8722                        } else {
8723                            for (int i = 0; i < N; i++) {
8724                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8725
8726                                final Intent sufficientIntent = new Intent(verification);
8727                                sufficientIntent.setComponent(verifierComponent);
8728
8729                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8730                            }
8731                        }
8732                    }
8733
8734                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8735                            mRequiredVerifierPackage, receivers);
8736                    if (ret == PackageManager.INSTALL_SUCCEEDED
8737                            && mRequiredVerifierPackage != null) {
8738                        /*
8739                         * Send the intent to the required verification agent,
8740                         * but only start the verification timeout after the
8741                         * target BroadcastReceivers have run.
8742                         */
8743                        verification.setComponent(requiredVerifierComponent);
8744                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8745                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8746                                new BroadcastReceiver() {
8747                                    @Override
8748                                    public void onReceive(Context context, Intent intent) {
8749                                        final Message msg = mHandler
8750                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8751                                        msg.arg1 = verificationId;
8752                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8753                                    }
8754                                }, null, 0, null, null);
8755
8756                        /*
8757                         * We don't want the copy to proceed until verification
8758                         * succeeds, so null out this field.
8759                         */
8760                        mArgs = null;
8761                    }
8762                } else {
8763                    /*
8764                     * No package verification is enabled, so immediately start
8765                     * the remote call to initiate copy using temporary file.
8766                     */
8767                    ret = args.copyApk(mContainerService, true);
8768                }
8769            }
8770
8771            mRet = ret;
8772        }
8773
8774        @Override
8775        void handleReturnCode() {
8776            // If mArgs is null, then MCS couldn't be reached. When it
8777            // reconnects, it will try again to install. At that point, this
8778            // will succeed.
8779            if (mArgs != null) {
8780                processPendingInstall(mArgs, mRet);
8781
8782                if (mTempPackage != null) {
8783                    if (!mTempPackage.delete()) {
8784                        Slog.w(TAG, "Couldn't delete temporary file: " +
8785                                mTempPackage.getAbsolutePath());
8786                    }
8787                }
8788            }
8789        }
8790
8791        @Override
8792        void handleServiceError() {
8793            mArgs = createInstallArgs(this);
8794            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8795        }
8796
8797        public boolean isForwardLocked() {
8798            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8799        }
8800
8801        public Uri getPackageUri() {
8802            if (mTempPackage != null) {
8803                return Uri.fromFile(mTempPackage);
8804            } else {
8805                return mPackageURI;
8806            }
8807        }
8808    }
8809
8810    /*
8811     * Utility class used in movePackage api.
8812     * srcArgs and targetArgs are not set for invalid flags and make
8813     * sure to do null checks when invoking methods on them.
8814     * We probably want to return ErrorPrams for both failed installs
8815     * and moves.
8816     */
8817    class MoveParams extends HandlerParams {
8818        final IPackageMoveObserver observer;
8819        final int flags;
8820        final String packageName;
8821        final InstallArgs srcArgs;
8822        final InstallArgs targetArgs;
8823        int uid;
8824        int mRet;
8825
8826        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8827                String packageName, String dataDir, String instructionSet,
8828                int uid, UserHandle user) {
8829            super(user);
8830            this.srcArgs = srcArgs;
8831            this.observer = observer;
8832            this.flags = flags;
8833            this.packageName = packageName;
8834            this.uid = uid;
8835            if (srcArgs != null) {
8836                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8837                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8838            } else {
8839                targetArgs = null;
8840            }
8841        }
8842
8843        @Override
8844        public String toString() {
8845            return "MoveParams{"
8846                + Integer.toHexString(System.identityHashCode(this))
8847                + " " + packageName + "}";
8848        }
8849
8850        public void handleStartCopy() throws RemoteException {
8851            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8852            // Check for storage space on target medium
8853            if (!targetArgs.checkFreeStorage(mContainerService)) {
8854                Log.w(TAG, "Insufficient storage to install");
8855                return;
8856            }
8857
8858            mRet = srcArgs.doPreCopy();
8859            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8860                return;
8861            }
8862
8863            mRet = targetArgs.copyApk(mContainerService, false);
8864            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8865                srcArgs.doPostCopy(uid);
8866                return;
8867            }
8868
8869            mRet = srcArgs.doPostCopy(uid);
8870            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8871                return;
8872            }
8873
8874            mRet = targetArgs.doPreInstall(mRet);
8875            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8876                return;
8877            }
8878
8879            if (DEBUG_SD_INSTALL) {
8880                StringBuilder builder = new StringBuilder();
8881                if (srcArgs != null) {
8882                    builder.append("src: ");
8883                    builder.append(srcArgs.getCodePath());
8884                }
8885                if (targetArgs != null) {
8886                    builder.append(" target : ");
8887                    builder.append(targetArgs.getCodePath());
8888                }
8889                Log.i(TAG, builder.toString());
8890            }
8891        }
8892
8893        @Override
8894        void handleReturnCode() {
8895            targetArgs.doPostInstall(mRet, uid);
8896            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8897            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8898                currentStatus = PackageManager.MOVE_SUCCEEDED;
8899            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8900                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8901            }
8902            processPendingMove(this, currentStatus);
8903        }
8904
8905        @Override
8906        void handleServiceError() {
8907            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8908        }
8909    }
8910
8911    /**
8912     * Used during creation of InstallArgs
8913     *
8914     * @param flags package installation flags
8915     * @return true if should be installed on external storage
8916     */
8917    private static boolean installOnSd(int flags) {
8918        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8919            return false;
8920        }
8921        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8922            return true;
8923        }
8924        return false;
8925    }
8926
8927    /**
8928     * Used during creation of InstallArgs
8929     *
8930     * @param flags package installation flags
8931     * @return true if should be installed as forward locked
8932     */
8933    private static boolean installForwardLocked(int flags) {
8934        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8935    }
8936
8937    private InstallArgs createInstallArgs(InstallParams params) {
8938        if (installOnSd(params.flags) || params.isForwardLocked()) {
8939            return new AsecInstallArgs(params);
8940        } else {
8941            return new FileInstallArgs(params);
8942        }
8943    }
8944
8945    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8946            String nativeLibraryPath, String instructionSet) {
8947        final boolean isInAsec;
8948        if (installOnSd(flags)) {
8949            /* Apps on SD card are always in ASEC containers. */
8950            isInAsec = true;
8951        } else if (installForwardLocked(flags)
8952                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8953            /*
8954             * Forward-locked apps are only in ASEC containers if they're the
8955             * new style
8956             */
8957            isInAsec = true;
8958        } else {
8959            isInAsec = false;
8960        }
8961
8962        if (isInAsec) {
8963            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8964                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8965        } else {
8966            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8967                    instructionSet);
8968        }
8969    }
8970
8971    // Used by package mover
8972    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8973            String instructionSet) {
8974        if (installOnSd(flags) || installForwardLocked(flags)) {
8975            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8976                    + AsecInstallArgs.RES_FILE_NAME);
8977            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8978                    installForwardLocked(flags));
8979        } else {
8980            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8981        }
8982    }
8983
8984    static abstract class InstallArgs {
8985        final IPackageInstallObserver observer;
8986        final IPackageInstallObserver2 observer2;
8987        // Always refers to PackageManager flags only
8988        final int flags;
8989        final Uri packageURI;
8990        final String installerPackageName;
8991        final ManifestDigest manifestDigest;
8992        final UserHandle user;
8993        final String instructionSet;
8994        final String abiOverride;
8995
8996        InstallArgs(Uri packageURI,
8997                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8998                int flags, String installerPackageName, ManifestDigest manifestDigest,
8999                UserHandle user, String instructionSet, String abiOverride) {
9000            this.packageURI = packageURI;
9001            this.flags = flags;
9002            this.observer = observer;
9003            this.observer2 = observer2;
9004            this.installerPackageName = installerPackageName;
9005            this.manifestDigest = manifestDigest;
9006            this.user = user;
9007            this.instructionSet = instructionSet;
9008            this.abiOverride = abiOverride;
9009        }
9010
9011        abstract void createCopyFile();
9012        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9013        abstract int doPreInstall(int status);
9014        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9015
9016        abstract int doPostInstall(int status, int uid);
9017        abstract String getCodePath();
9018        abstract String getResourcePath();
9019        abstract String getNativeLibraryPath();
9020        // Need installer lock especially for dex file removal.
9021        abstract void cleanUpResourcesLI();
9022        abstract boolean doPostDeleteLI(boolean delete);
9023        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9024
9025        String[] getSplitCodePaths() {
9026            return null;
9027        }
9028
9029        /**
9030         * Called before the source arguments are copied. This is used mostly
9031         * for MoveParams when it needs to read the source file to put it in the
9032         * destination.
9033         */
9034        int doPreCopy() {
9035            return PackageManager.INSTALL_SUCCEEDED;
9036        }
9037
9038        /**
9039         * Called after the source arguments are copied. This is used mostly for
9040         * MoveParams when it needs to read the source file to put it in the
9041         * destination.
9042         *
9043         * @return
9044         */
9045        int doPostCopy(int uid) {
9046            return PackageManager.INSTALL_SUCCEEDED;
9047        }
9048
9049        protected boolean isFwdLocked() {
9050            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9051        }
9052
9053        UserHandle getUser() {
9054            return user;
9055        }
9056    }
9057
9058    class FileInstallArgs extends InstallArgs {
9059        File installDir;
9060        String codeFileName;
9061        String resourceFileName;
9062        String libraryPath;
9063        boolean created = false;
9064
9065        FileInstallArgs(InstallParams params) {
9066            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9067                    params.installerPackageName, params.getManifestDigest(),
9068                    params.getUser(), params.packageInstructionSetOverride,
9069                    params.packageAbiOverride);
9070        }
9071
9072        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9073                String instructionSet) {
9074            super(null, null, null, 0, null, null, null, instructionSet, null);
9075            File codeFile = new File(fullCodePath);
9076            installDir = codeFile.getParentFile();
9077            codeFileName = fullCodePath;
9078            resourceFileName = fullResourcePath;
9079            libraryPath = nativeLibraryPath;
9080        }
9081
9082        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9083            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9084            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9085            String apkName = getNextCodePath(null, pkgName, ".apk");
9086            codeFileName = new File(installDir, apkName + ".apk").getPath();
9087            resourceFileName = getResourcePathFromCodePath();
9088            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9089        }
9090
9091        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9092            final long lowThreshold;
9093
9094            final DeviceStorageMonitorInternal
9095                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9096            if (dsm == null) {
9097                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9098                lowThreshold = 0L;
9099            } else {
9100                if (dsm.isMemoryLow()) {
9101                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9102                    return false;
9103                }
9104
9105                lowThreshold = dsm.getMemoryLowThreshold();
9106            }
9107
9108            try {
9109                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9110                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9111                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9112            } finally {
9113                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9114            }
9115        }
9116
9117        void createCopyFile() {
9118            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9119            codeFileName = createTempPackageFile(installDir).getPath();
9120            resourceFileName = getResourcePathFromCodePath();
9121            libraryPath = getLibraryPathFromCodePath();
9122            created = true;
9123        }
9124
9125        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9126            if (temp) {
9127                // Generate temp file name
9128                createCopyFile();
9129            }
9130            // Get a ParcelFileDescriptor to write to the output file
9131            File codeFile = new File(codeFileName);
9132            if (!created) {
9133                try {
9134                    codeFile.createNewFile();
9135                    // Set permissions
9136                    if (!setPermissions()) {
9137                        // Failed setting permissions.
9138                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9139                    }
9140                } catch (IOException e) {
9141                   Slog.w(TAG, "Failed to create file " + codeFile);
9142                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9143                }
9144            }
9145            ParcelFileDescriptor out = null;
9146            try {
9147                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9148            } catch (FileNotFoundException e) {
9149                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9150                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9151            }
9152            // Copy the resource now
9153            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9154            try {
9155                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9156                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9157                ret = imcs.copyResource(packageURI, null, out);
9158            } finally {
9159                IoUtils.closeQuietly(out);
9160                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9161            }
9162
9163            if (isFwdLocked()) {
9164                final File destResourceFile = new File(getResourcePath());
9165
9166                // Copy the public files
9167                try {
9168                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9169                } catch (IOException e) {
9170                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9171                            + " forward-locked app.");
9172                    destResourceFile.delete();
9173                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9174                }
9175            }
9176
9177            final File nativeLibraryFile = new File(getNativeLibraryPath());
9178            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9179            if (nativeLibraryFile.exists()) {
9180                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9181                nativeLibraryFile.delete();
9182            }
9183
9184            String[] abiList = (abiOverride != null) ?
9185                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9186            ApkHandle handle = null;
9187            try {
9188                handle = ApkHandle.create(codeFile);
9189                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9190                        abiOverride == null &&
9191                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9192                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9193                }
9194
9195                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9196                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9197                    return copyRet;
9198                }
9199            } catch (IOException e) {
9200                Slog.e(TAG, "Copying native libraries failed", e);
9201                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9202            } finally {
9203                IoUtils.closeQuietly(handle);
9204            }
9205
9206            return ret;
9207        }
9208
9209        int doPreInstall(int status) {
9210            if (status != PackageManager.INSTALL_SUCCEEDED) {
9211                cleanUp();
9212            }
9213            return status;
9214        }
9215
9216        boolean doRename(int status, final String pkgName, String oldCodePath) {
9217            if (status != PackageManager.INSTALL_SUCCEEDED) {
9218                cleanUp();
9219                return false;
9220            } else {
9221                final File oldCodeFile = new File(getCodePath());
9222                final File oldResourceFile = new File(getResourcePath());
9223                final File oldLibraryFile = new File(getNativeLibraryPath());
9224
9225                // Rename APK file based on packageName
9226                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9227                final File newCodeFile = new File(installDir, apkName + ".apk");
9228                if (!oldCodeFile.renameTo(newCodeFile)) {
9229                    return false;
9230                }
9231                codeFileName = newCodeFile.getPath();
9232
9233                // Rename public resource file if it's forward-locked.
9234                final File newResFile = new File(getResourcePathFromCodePath());
9235                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9236                    return false;
9237                }
9238                resourceFileName = newResFile.getPath();
9239
9240                // Rename library path
9241                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9242                if (newLibraryFile.exists()) {
9243                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9244                    newLibraryFile.delete();
9245                }
9246                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9247                    Slog.e(TAG, "Cannot rename native library directory "
9248                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9249                    return false;
9250                }
9251                libraryPath = newLibraryFile.getPath();
9252
9253                // Attempt to set permissions
9254                if (!setPermissions()) {
9255                    return false;
9256                }
9257
9258                if (!SELinux.restorecon(newCodeFile)) {
9259                    return false;
9260                }
9261
9262                return true;
9263            }
9264        }
9265
9266        int doPostInstall(int status, int uid) {
9267            if (status != PackageManager.INSTALL_SUCCEEDED) {
9268                cleanUp();
9269            }
9270            return status;
9271        }
9272
9273        private String getResourcePathFromCodePath() {
9274            final String codePath = getCodePath();
9275            if (isFwdLocked()) {
9276                final StringBuilder sb = new StringBuilder();
9277
9278                sb.append(mAppInstallDir.getPath());
9279                sb.append('/');
9280                sb.append(getApkName(codePath));
9281                sb.append(".zip");
9282
9283                /*
9284                 * If our APK is a temporary file, mark the resource as a
9285                 * temporary file as well so it can be cleaned up after
9286                 * catastrophic failure.
9287                 */
9288                if (codePath.endsWith(".tmp")) {
9289                    sb.append(".tmp");
9290                }
9291
9292                return sb.toString();
9293            } else {
9294                return codePath;
9295            }
9296        }
9297
9298        private String getLibraryPathFromCodePath() {
9299            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9300        }
9301
9302        @Override
9303        String getCodePath() {
9304            return codeFileName;
9305        }
9306
9307        @Override
9308        String getResourcePath() {
9309            return resourceFileName;
9310        }
9311
9312        @Override
9313        String getNativeLibraryPath() {
9314            if (libraryPath == null) {
9315                libraryPath = getLibraryPathFromCodePath();
9316            }
9317            return libraryPath;
9318        }
9319
9320        private boolean cleanUp() {
9321            boolean ret = true;
9322            String sourceDir = getCodePath();
9323            String publicSourceDir = getResourcePath();
9324            if (sourceDir != null) {
9325                File sourceFile = new File(sourceDir);
9326                if (!sourceFile.exists()) {
9327                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9328                    ret = false;
9329                }
9330                // Delete application's code and resources
9331                sourceFile.delete();
9332            }
9333            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9334                final File publicSourceFile = new File(publicSourceDir);
9335                if (!publicSourceFile.exists()) {
9336                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9337                }
9338                if (publicSourceFile.exists()) {
9339                    publicSourceFile.delete();
9340                }
9341            }
9342
9343            if (libraryPath != null) {
9344                File nativeLibraryFile = new File(libraryPath);
9345                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9346                if (!nativeLibraryFile.delete()) {
9347                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9348                }
9349            }
9350
9351            return ret;
9352        }
9353
9354        void cleanUpResourcesLI() {
9355            String sourceDir = getCodePath();
9356            if (cleanUp()) {
9357                if (instructionSet == null) {
9358                    throw new IllegalStateException("instructionSet == null");
9359                }
9360                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9361                if (retCode < 0) {
9362                    Slog.w(TAG, "Couldn't remove dex file for package: "
9363                            +  " at location "
9364                            + sourceDir + ", retcode=" + retCode);
9365                    // we don't consider this to be a failure of the core package deletion
9366                }
9367            }
9368        }
9369
9370        private boolean setPermissions() {
9371            // TODO Do this in a more elegant way later on. for now just a hack
9372            if (!isFwdLocked()) {
9373                final int filePermissions =
9374                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9375                    |FileUtils.S_IROTH;
9376                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9377                if (retCode != 0) {
9378                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9379                            getCodePath()
9380                            + ". The return code was: " + retCode);
9381                    // TODO Define new internal error
9382                    return false;
9383                }
9384                return true;
9385            }
9386            return true;
9387        }
9388
9389        boolean doPostDeleteLI(boolean delete) {
9390            // XXX err, shouldn't we respect the delete flag?
9391            cleanUpResourcesLI();
9392            return true;
9393        }
9394    }
9395
9396    private boolean isAsecExternal(String cid) {
9397        final String asecPath = PackageHelper.getSdFilesystem(cid);
9398        return !asecPath.startsWith(mAsecInternalPath);
9399    }
9400
9401    /**
9402     * Extract the MountService "container ID" from the full code path of an
9403     * .apk.
9404     */
9405    static String cidFromCodePath(String fullCodePath) {
9406        int eidx = fullCodePath.lastIndexOf("/");
9407        String subStr1 = fullCodePath.substring(0, eidx);
9408        int sidx = subStr1.lastIndexOf("/");
9409        return subStr1.substring(sidx+1, eidx);
9410    }
9411
9412    class AsecInstallArgs extends InstallArgs {
9413        static final String RES_FILE_NAME = "pkg.apk";
9414        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9415
9416        String cid;
9417        String packagePath;
9418        String resourcePath;
9419        String libraryPath;
9420
9421        AsecInstallArgs(InstallParams params) {
9422            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9423                    params.installerPackageName, params.getManifestDigest(),
9424                    params.getUser(), params.packageInstructionSetOverride,
9425                    params.packageAbiOverride);
9426        }
9427
9428        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9429                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9430            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9431                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9432                    null, null, null, instructionSet, null);
9433            // Extract cid from fullCodePath
9434            int eidx = fullCodePath.lastIndexOf("/");
9435            String subStr1 = fullCodePath.substring(0, eidx);
9436            int sidx = subStr1.lastIndexOf("/");
9437            cid = subStr1.substring(sidx+1, eidx);
9438            setCachePath(subStr1);
9439        }
9440
9441        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9442            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9443                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9444                    null, null, null, instructionSet, null);
9445            this.cid = cid;
9446            setCachePath(PackageHelper.getSdDir(cid));
9447        }
9448
9449        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9450                boolean isExternal, boolean isForwardLocked) {
9451            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9452                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9453                    null, null, null, instructionSet, null);
9454            this.cid = cid;
9455        }
9456
9457        void createCopyFile() {
9458            cid = getTempContainerId();
9459        }
9460
9461        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9462            try {
9463                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9464                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9465                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9466            } finally {
9467                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9468            }
9469        }
9470
9471        private final boolean isExternal() {
9472            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9473        }
9474
9475        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9476            if (temp) {
9477                createCopyFile();
9478            } else {
9479                /*
9480                 * Pre-emptively destroy the container since it's destroyed if
9481                 * copying fails due to it existing anyway.
9482                 */
9483                PackageHelper.destroySdDir(cid);
9484            }
9485
9486            final String newCachePath;
9487            try {
9488                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9489                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9490                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9491                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9492                        abiOverride);
9493            } finally {
9494                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9495            }
9496
9497            if (newCachePath != null) {
9498                setCachePath(newCachePath);
9499                return PackageManager.INSTALL_SUCCEEDED;
9500            } else {
9501                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9502            }
9503        }
9504
9505        @Override
9506        String getCodePath() {
9507            return packagePath;
9508        }
9509
9510        @Override
9511        String getResourcePath() {
9512            return resourcePath;
9513        }
9514
9515        @Override
9516        String getNativeLibraryPath() {
9517            return libraryPath;
9518        }
9519
9520        int doPreInstall(int status) {
9521            if (status != PackageManager.INSTALL_SUCCEEDED) {
9522                // Destroy container
9523                PackageHelper.destroySdDir(cid);
9524            } else {
9525                boolean mounted = PackageHelper.isContainerMounted(cid);
9526                if (!mounted) {
9527                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9528                            Process.SYSTEM_UID);
9529                    if (newCachePath != null) {
9530                        setCachePath(newCachePath);
9531                    } else {
9532                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9533                    }
9534                }
9535            }
9536            return status;
9537        }
9538
9539        boolean doRename(int status, final String pkgName,
9540                String oldCodePath) {
9541            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9542            String newCachePath = null;
9543            if (PackageHelper.isContainerMounted(cid)) {
9544                // Unmount the container
9545                if (!PackageHelper.unMountSdDir(cid)) {
9546                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9547                    return false;
9548                }
9549            }
9550            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9551                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9552                        " which might be stale. Will try to clean up.");
9553                // Clean up the stale container and proceed to recreate.
9554                if (!PackageHelper.destroySdDir(newCacheId)) {
9555                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9556                    return false;
9557                }
9558                // Successfully cleaned up stale container. Try to rename again.
9559                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9560                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9561                            + " inspite of cleaning it up.");
9562                    return false;
9563                }
9564            }
9565            if (!PackageHelper.isContainerMounted(newCacheId)) {
9566                Slog.w(TAG, "Mounting container " + newCacheId);
9567                newCachePath = PackageHelper.mountSdDir(newCacheId,
9568                        getEncryptKey(), Process.SYSTEM_UID);
9569            } else {
9570                newCachePath = PackageHelper.getSdDir(newCacheId);
9571            }
9572            if (newCachePath == null) {
9573                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9574                return false;
9575            }
9576            Log.i(TAG, "Succesfully renamed " + cid +
9577                    " to " + newCacheId +
9578                    " at new path: " + newCachePath);
9579            cid = newCacheId;
9580            setCachePath(newCachePath);
9581            return true;
9582        }
9583
9584        private void setCachePath(String newCachePath) {
9585            File cachePath = new File(newCachePath);
9586            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9587            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9588
9589            if (isFwdLocked()) {
9590                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9591            } else {
9592                resourcePath = packagePath;
9593            }
9594        }
9595
9596        int doPostInstall(int status, int uid) {
9597            if (status != PackageManager.INSTALL_SUCCEEDED) {
9598                cleanUp();
9599            } else {
9600                final int groupOwner;
9601                final String protectedFile;
9602                if (isFwdLocked()) {
9603                    groupOwner = UserHandle.getSharedAppGid(uid);
9604                    protectedFile = RES_FILE_NAME;
9605                } else {
9606                    groupOwner = -1;
9607                    protectedFile = null;
9608                }
9609
9610                if (uid < Process.FIRST_APPLICATION_UID
9611                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9612                    Slog.e(TAG, "Failed to finalize " + cid);
9613                    PackageHelper.destroySdDir(cid);
9614                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9615                }
9616
9617                boolean mounted = PackageHelper.isContainerMounted(cid);
9618                if (!mounted) {
9619                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9620                }
9621            }
9622            return status;
9623        }
9624
9625        private void cleanUp() {
9626            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9627
9628            // Destroy secure container
9629            PackageHelper.destroySdDir(cid);
9630        }
9631
9632        void cleanUpResourcesLI() {
9633            String sourceFile = getCodePath();
9634            // Remove dex file
9635            if (instructionSet == null) {
9636                throw new IllegalStateException("instructionSet == null");
9637            }
9638            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9639            if (retCode < 0) {
9640                Slog.w(TAG, "Couldn't remove dex file for package: "
9641                        + " at location "
9642                        + sourceFile.toString() + ", retcode=" + retCode);
9643                // we don't consider this to be a failure of the core package deletion
9644            }
9645            cleanUp();
9646        }
9647
9648        boolean matchContainer(String app) {
9649            if (cid.startsWith(app)) {
9650                return true;
9651            }
9652            return false;
9653        }
9654
9655        String getPackageName() {
9656            return getAsecPackageName(cid);
9657        }
9658
9659        boolean doPostDeleteLI(boolean delete) {
9660            boolean ret = false;
9661            boolean mounted = PackageHelper.isContainerMounted(cid);
9662            if (mounted) {
9663                // Unmount first
9664                ret = PackageHelper.unMountSdDir(cid);
9665            }
9666            if (ret && delete) {
9667                cleanUpResourcesLI();
9668            }
9669            return ret;
9670        }
9671
9672        @Override
9673        int doPreCopy() {
9674            if (isFwdLocked()) {
9675                if (!PackageHelper.fixSdPermissions(cid,
9676                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9677                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9678                }
9679            }
9680
9681            return PackageManager.INSTALL_SUCCEEDED;
9682        }
9683
9684        @Override
9685        int doPostCopy(int uid) {
9686            if (isFwdLocked()) {
9687                if (uid < Process.FIRST_APPLICATION_UID
9688                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9689                                RES_FILE_NAME)) {
9690                    Slog.e(TAG, "Failed to finalize " + cid);
9691                    PackageHelper.destroySdDir(cid);
9692                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9693                }
9694            }
9695
9696            return PackageManager.INSTALL_SUCCEEDED;
9697        }
9698    }
9699
9700    static String getAsecPackageName(String packageCid) {
9701        int idx = packageCid.lastIndexOf("-");
9702        if (idx == -1) {
9703            return packageCid;
9704        }
9705        return packageCid.substring(0, idx);
9706    }
9707
9708    // Utility method used to create code paths based on package name and available index.
9709    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9710        String idxStr = "";
9711        int idx = 1;
9712        // Fall back to default value of idx=1 if prefix is not
9713        // part of oldCodePath
9714        if (oldCodePath != null) {
9715            String subStr = oldCodePath;
9716            // Drop the suffix right away
9717            if (subStr.endsWith(suffix)) {
9718                subStr = subStr.substring(0, subStr.length() - suffix.length());
9719            }
9720            // If oldCodePath already contains prefix find out the
9721            // ending index to either increment or decrement.
9722            int sidx = subStr.lastIndexOf(prefix);
9723            if (sidx != -1) {
9724                subStr = subStr.substring(sidx + prefix.length());
9725                if (subStr != null) {
9726                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9727                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9728                    }
9729                    try {
9730                        idx = Integer.parseInt(subStr);
9731                        if (idx <= 1) {
9732                            idx++;
9733                        } else {
9734                            idx--;
9735                        }
9736                    } catch(NumberFormatException e) {
9737                    }
9738                }
9739            }
9740        }
9741        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9742        return prefix + idxStr;
9743    }
9744
9745    // Utility method used to ignore ADD/REMOVE events
9746    // by directory observer.
9747    private static boolean ignoreCodePath(String fullPathStr) {
9748        String apkName = getApkName(fullPathStr);
9749        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9750        if (idx != -1 && ((idx+1) < apkName.length())) {
9751            // Make sure the package ends with a numeral
9752            String version = apkName.substring(idx+1);
9753            try {
9754                Integer.parseInt(version);
9755                return true;
9756            } catch (NumberFormatException e) {}
9757        }
9758        return false;
9759    }
9760
9761    // Utility method that returns the relative package path with respect
9762    // to the installation directory. Like say for /data/data/com.test-1.apk
9763    // string com.test-1 is returned.
9764    static String getApkName(String codePath) {
9765        if (codePath == null) {
9766            return null;
9767        }
9768        int sidx = codePath.lastIndexOf("/");
9769        int eidx = codePath.lastIndexOf(".");
9770        if (eidx == -1) {
9771            eidx = codePath.length();
9772        } else if (eidx == 0) {
9773            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9774            return null;
9775        }
9776        return codePath.substring(sidx+1, eidx);
9777    }
9778
9779    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9780        String[] splitResPaths = null;
9781        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9782            splitResPaths = new String[splitCodePaths.length];
9783            for (int i = 0; i < splitCodePaths.length; i++) {
9784                final String splitCodePath = splitCodePaths[i];
9785                final String resName = getApkName(splitCodePath) + ".zip";
9786                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9787                        resName).getAbsolutePath();
9788            }
9789        }
9790        return splitResPaths;
9791    }
9792
9793    class PackageInstalledInfo {
9794        String name;
9795        int uid;
9796        // The set of users that originally had this package installed.
9797        int[] origUsers;
9798        // The set of users that now have this package installed.
9799        int[] newUsers;
9800        PackageParser.Package pkg;
9801        int returnCode;
9802        PackageRemovedInfo removedInfo;
9803
9804        // In some error cases we want to convey more info back to the observer
9805        String origPackage;
9806        String origPermission;
9807    }
9808
9809    /*
9810     * Install a non-existing package.
9811     */
9812    private void installNewPackageLI(PackageParser.Package pkg,
9813            int parseFlags, int scanMode, UserHandle user,
9814            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9815        // Remember this for later, in case we need to rollback this install
9816        String pkgName = pkg.packageName;
9817
9818        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9819        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9820        synchronized(mPackages) {
9821            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9822                // A package with the same name is already installed, though
9823                // it has been renamed to an older name.  The package we
9824                // are trying to install should be installed as an update to
9825                // the existing one, but that has not been requested, so bail.
9826                Slog.w(TAG, "Attempt to re-install " + pkgName
9827                        + " without first uninstalling package running as "
9828                        + mSettings.mRenamedPackages.get(pkgName));
9829                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9830                return;
9831            }
9832            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9833                // Don't allow installation over an existing package with the same name.
9834                Slog.w(TAG, "Attempt to re-install " + pkgName
9835                        + " without first uninstalling.");
9836                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9837                return;
9838            }
9839        }
9840        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9841        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9842                System.currentTimeMillis(), user, abiOverride);
9843        if (newPackage == null) {
9844            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9845            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9846                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9847            }
9848        } else {
9849            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9850            // delete the partially installed application. the data directory will have to be
9851            // restored if it was already existing
9852            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9853                // remove package from internal structures.  Note that we want deletePackageX to
9854                // delete the package data and cache directories that it created in
9855                // scanPackageLocked, unless those directories existed before we even tried to
9856                // install.
9857                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9858                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9859                                res.removedInfo, true);
9860            }
9861        }
9862    }
9863
9864    private void replacePackageLI(PackageParser.Package pkg,
9865            int parseFlags, int scanMode, UserHandle user,
9866            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9867
9868        PackageParser.Package oldPackage;
9869        String pkgName = pkg.packageName;
9870        int[] allUsers;
9871        boolean[] perUserInstalled;
9872
9873        // First find the old package info and check signatures
9874        synchronized(mPackages) {
9875            oldPackage = mPackages.get(pkgName);
9876            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9877            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9878                    != PackageManager.SIGNATURE_MATCH) {
9879                Slog.w(TAG, "New package has a different signature: " + pkgName);
9880                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9881                return;
9882            }
9883
9884            // In case of rollback, remember per-user/profile install state
9885            PackageSetting ps = mSettings.mPackages.get(pkgName);
9886            allUsers = sUserManager.getUserIds();
9887            perUserInstalled = new boolean[allUsers.length];
9888            for (int i = 0; i < allUsers.length; i++) {
9889                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9890            }
9891        }
9892        boolean sysPkg = (isSystemApp(oldPackage));
9893        if (sysPkg) {
9894            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9895                    user, allUsers, perUserInstalled, installerPackageName, res,
9896                    abiOverride);
9897        } else {
9898            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9899                    user, allUsers, perUserInstalled, installerPackageName, res,
9900                    abiOverride);
9901        }
9902    }
9903
9904    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9905            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9906            int[] allUsers, boolean[] perUserInstalled,
9907            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9908        PackageParser.Package newPackage = null;
9909        String pkgName = deletedPackage.packageName;
9910        boolean deletedPkg = true;
9911        boolean updatedSettings = false;
9912
9913        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9914                + deletedPackage);
9915        long origUpdateTime;
9916        if (pkg.mExtras != null) {
9917            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9918        } else {
9919            origUpdateTime = 0;
9920        }
9921
9922        // First delete the existing package while retaining the data directory
9923        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9924                res.removedInfo, true)) {
9925            // If the existing package wasn't successfully deleted
9926            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9927            deletedPkg = false;
9928        } else {
9929            // Successfully deleted the old package. Now proceed with re-installation
9930            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9931            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9932                    System.currentTimeMillis(), user, abiOverride);
9933            if (newPackage == null) {
9934                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9935                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9936                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9937                }
9938            } else {
9939                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9940                updatedSettings = true;
9941            }
9942        }
9943
9944        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9945            // remove package from internal structures.  Note that we want deletePackageX to
9946            // delete the package data and cache directories that it created in
9947            // scanPackageLocked, unless those directories existed before we even tried to
9948            // install.
9949            if(updatedSettings) {
9950                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9951                deletePackageLI(
9952                        pkgName, null, true, allUsers, perUserInstalled,
9953                        PackageManager.DELETE_KEEP_DATA,
9954                                res.removedInfo, true);
9955            }
9956            // Since we failed to install the new package we need to restore the old
9957            // package that we deleted.
9958            if (deletedPkg) {
9959                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9960                File restoreFile = new File(deletedPackage.codePath);
9961                // Parse old package
9962                boolean oldOnSd = isExternal(deletedPackage);
9963                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9964                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9965                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9966                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9967                        | SCAN_UPDATE_TIME;
9968                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9969                        origUpdateTime, null, null) == null) {
9970                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9971                    return;
9972                }
9973                // Restore of old package succeeded. Update permissions.
9974                // writer
9975                synchronized (mPackages) {
9976                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9977                            UPDATE_PERMISSIONS_ALL);
9978                    // can downgrade to reader
9979                    mSettings.writeLPr();
9980                }
9981                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9982            }
9983        }
9984    }
9985
9986    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9987            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9988            int[] allUsers, boolean[] perUserInstalled,
9989            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9990        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9991                + ", old=" + deletedPackage);
9992        PackageParser.Package newPackage = null;
9993        boolean updatedSettings = false;
9994        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9995                PackageParser.PARSE_IS_SYSTEM;
9996        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9997            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9998        }
9999        String packageName = deletedPackage.packageName;
10000        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10001        if (packageName == null) {
10002            Slog.w(TAG, "Attempt to delete null packageName.");
10003            return;
10004        }
10005        PackageParser.Package oldPkg;
10006        PackageSetting oldPkgSetting;
10007        // reader
10008        synchronized (mPackages) {
10009            oldPkg = mPackages.get(packageName);
10010            oldPkgSetting = mSettings.mPackages.get(packageName);
10011            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10012                    (oldPkgSetting == null)) {
10013                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10014                return;
10015            }
10016        }
10017
10018        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10019
10020        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10021        res.removedInfo.removedPackage = packageName;
10022        // Remove existing system package
10023        removePackageLI(oldPkgSetting, true);
10024        // writer
10025        synchronized (mPackages) {
10026            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10027                // We didn't need to disable the .apk as a current system package,
10028                // which means we are replacing another update that is already
10029                // installed.  We need to make sure to delete the older one's .apk.
10030                res.removedInfo.args = createInstallArgs(0,
10031                        deletedPackage.applicationInfo.sourceDir,
10032                        deletedPackage.applicationInfo.publicSourceDir,
10033                        deletedPackage.applicationInfo.nativeLibraryDir,
10034                        getAppInstructionSet(deletedPackage.applicationInfo));
10035            } else {
10036                res.removedInfo.args = null;
10037            }
10038        }
10039
10040        // Successfully disabled the old package. Now proceed with re-installation
10041        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10042        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10043        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10044        if (newPackage == null) {
10045            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10046            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10047                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10048            }
10049        } else {
10050            if (newPackage.mExtras != null) {
10051                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10052                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10053                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10054
10055                // is the update attempting to change shared user? that isn't going to work...
10056                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10057                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10058                            + " to " + newPkgSetting.sharedUser);
10059                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10060                    updatedSettings = true;
10061                }
10062            }
10063
10064            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10065                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10066                updatedSettings = true;
10067            }
10068        }
10069
10070        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10071            // Re installation failed. Restore old information
10072            // Remove new pkg information
10073            if (newPackage != null) {
10074                removeInstalledPackageLI(newPackage, true);
10075            }
10076            // Add back the old system package
10077            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10078            // Restore the old system information in Settings
10079            synchronized(mPackages) {
10080                if (updatedSettings) {
10081                    mSettings.enableSystemPackageLPw(packageName);
10082                    mSettings.setInstallerPackageName(packageName,
10083                            oldPkgSetting.installerPackageName);
10084                }
10085                mSettings.writeLPr();
10086            }
10087        }
10088    }
10089
10090    // Utility method used to move dex files during install.
10091    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10092        // TODO: extend to move split APK dex files
10093        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10094            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10095            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10096                                             instructionSet);
10097            if (retCode != 0) {
10098                /*
10099                 * Programs may be lazily run through dexopt, so the
10100                 * source may not exist. However, something seems to
10101                 * have gone wrong, so note that dexopt needs to be
10102                 * run again and remove the source file. In addition,
10103                 * remove the target to make sure there isn't a stale
10104                 * file from a previous version of the package.
10105                 */
10106                newPackage.mDexOptNeeded = true;
10107                mInstaller.rmdex(oldCodePath, instructionSet);
10108                mInstaller.rmdex(newPackage.codePath, instructionSet);
10109            }
10110        }
10111        return PackageManager.INSTALL_SUCCEEDED;
10112    }
10113
10114    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10115            int[] allUsers, boolean[] perUserInstalled,
10116            PackageInstalledInfo res) {
10117        String pkgName = newPackage.packageName;
10118        synchronized (mPackages) {
10119            //write settings. the installStatus will be incomplete at this stage.
10120            //note that the new package setting would have already been
10121            //added to mPackages. It hasn't been persisted yet.
10122            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10123            mSettings.writeLPr();
10124        }
10125
10126        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10127
10128        synchronized (mPackages) {
10129            updatePermissionsLPw(newPackage.packageName, newPackage,
10130                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10131                            ? UPDATE_PERMISSIONS_ALL : 0));
10132            // For system-bundled packages, we assume that installing an upgraded version
10133            // of the package implies that the user actually wants to run that new code,
10134            // so we enable the package.
10135            if (isSystemApp(newPackage)) {
10136                // NB: implicit assumption that system package upgrades apply to all users
10137                if (DEBUG_INSTALL) {
10138                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10139                }
10140                PackageSetting ps = mSettings.mPackages.get(pkgName);
10141                if (ps != null) {
10142                    if (res.origUsers != null) {
10143                        for (int userHandle : res.origUsers) {
10144                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10145                                    userHandle, installerPackageName);
10146                        }
10147                    }
10148                    // Also convey the prior install/uninstall state
10149                    if (allUsers != null && perUserInstalled != null) {
10150                        for (int i = 0; i < allUsers.length; i++) {
10151                            if (DEBUG_INSTALL) {
10152                                Slog.d(TAG, "    user " + allUsers[i]
10153                                        + " => " + perUserInstalled[i]);
10154                            }
10155                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10156                        }
10157                        // these install state changes will be persisted in the
10158                        // upcoming call to mSettings.writeLPr().
10159                    }
10160                }
10161            }
10162            res.name = pkgName;
10163            res.uid = newPackage.applicationInfo.uid;
10164            res.pkg = newPackage;
10165            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10166            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10167            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10168            //to update install status
10169            mSettings.writeLPr();
10170        }
10171    }
10172
10173    private void installPackageLI(InstallArgs args,
10174            boolean newInstall, PackageInstalledInfo res) {
10175        int pFlags = args.flags;
10176        String installerPackageName = args.installerPackageName;
10177        File tmpPackageFile = new File(args.getCodePath());
10178        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10179        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10180        boolean replace = false;
10181        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10182                | (newInstall ? SCAN_NEW_INSTALL : 0);
10183        // Result object to be returned
10184        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10185
10186        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10187        // Retrieve PackageSettings and parse package
10188        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10189                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10190                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10191        PackageParser pp = new PackageParser();
10192        pp.setSeparateProcesses(mSeparateProcesses);
10193        pp.setDisplayMetrics(mMetrics);
10194
10195        final PackageParser.Package pkg;
10196        try {
10197            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10198        } catch (PackageParserException e) {
10199            res.returnCode = e.error;
10200            return;
10201        }
10202
10203        String pkgName = res.name = pkg.packageName;
10204        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10205            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10206                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10207                return;
10208            }
10209        }
10210
10211        try {
10212            pp.collectCertificates(pkg, parseFlags);
10213            pp.collectManifestDigest(pkg);
10214        } catch (PackageParserException e) {
10215            res.returnCode = e.error;
10216            return;
10217        }
10218
10219        /* If the installer passed in a manifest digest, compare it now. */
10220        if (args.manifestDigest != null) {
10221            if (DEBUG_INSTALL) {
10222                final String parsedManifest = pkg.manifestDigest == null ? "null"
10223                        : pkg.manifestDigest.toString();
10224                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10225                        + parsedManifest);
10226            }
10227
10228            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10229                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10230                return;
10231            }
10232        } else if (DEBUG_INSTALL) {
10233            final String parsedManifest = pkg.manifestDigest == null
10234                    ? "null" : pkg.manifestDigest.toString();
10235            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10236        }
10237
10238        // Get rid of all references to package scan path via parser.
10239        pp = null;
10240        String oldCodePath = null;
10241        boolean systemApp = false;
10242        synchronized (mPackages) {
10243            // Check whether the newly-scanned package wants to define an already-defined perm
10244            int N = pkg.permissions.size();
10245            for (int i = N-1; i >= 0; i--) {
10246                PackageParser.Permission perm = pkg.permissions.get(i);
10247                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10248                if (bp != null) {
10249                    // If the defining package is signed with our cert, it's okay.  This
10250                    // also includes the "updating the same package" case, of course.
10251                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10252                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10253                        // If the owning package is the system itself, we log but allow
10254                        // install to proceed; we fail the install on all other permission
10255                        // redefinitions.
10256                        if (!bp.sourcePackage.equals("android")) {
10257                            Slog.w(TAG, "Package " + pkg.packageName
10258                                    + " attempting to redeclare permission " + perm.info.name
10259                                    + " already owned by " + bp.sourcePackage);
10260                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10261                            res.origPermission = perm.info.name;
10262                            res.origPackage = bp.sourcePackage;
10263                            return;
10264                        } else {
10265                            Slog.w(TAG, "Package " + pkg.packageName
10266                                    + " attempting to redeclare system permission "
10267                                    + perm.info.name + "; ignoring new declaration");
10268                            pkg.permissions.remove(i);
10269                        }
10270                    }
10271                }
10272            }
10273
10274            // Check if installing already existing package
10275            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10276                String oldName = mSettings.mRenamedPackages.get(pkgName);
10277                if (pkg.mOriginalPackages != null
10278                        && pkg.mOriginalPackages.contains(oldName)
10279                        && mPackages.containsKey(oldName)) {
10280                    // This package is derived from an original package,
10281                    // and this device has been updating from that original
10282                    // name.  We must continue using the original name, so
10283                    // rename the new package here.
10284                    pkg.setPackageName(oldName);
10285                    pkgName = pkg.packageName;
10286                    replace = true;
10287                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10288                            + oldName + " pkgName=" + pkgName);
10289                } else if (mPackages.containsKey(pkgName)) {
10290                    // This package, under its official name, already exists
10291                    // on the device; we should replace it.
10292                    replace = true;
10293                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10294                }
10295            }
10296            PackageSetting ps = mSettings.mPackages.get(pkgName);
10297            if (ps != null) {
10298                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10299                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10300                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10301                    systemApp = (ps.pkg.applicationInfo.flags &
10302                            ApplicationInfo.FLAG_SYSTEM) != 0;
10303                }
10304                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10305            }
10306        }
10307
10308        if (systemApp && onSd) {
10309            // Disable updates to system apps on sdcard
10310            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10311            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10312            return;
10313        }
10314
10315        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10316            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10317            return;
10318        }
10319        // Set application objects path explicitly after the rename
10320        pkg.codePath = args.getCodePath();
10321        pkg.applicationInfo.sourceDir = args.getCodePath();
10322        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10323        pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths();
10324        pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths(
10325                pkg.applicationInfo.splitSourceDirs);
10326        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10327        if (replace) {
10328            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10329                    installerPackageName, res, args.abiOverride);
10330        } else {
10331            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10332                    installerPackageName, res, args.abiOverride);
10333        }
10334        synchronized (mPackages) {
10335            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10336            if (ps != null) {
10337                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10338            }
10339        }
10340    }
10341
10342    private static boolean isForwardLocked(PackageParser.Package pkg) {
10343        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10344    }
10345
10346
10347    private boolean isForwardLocked(PackageSetting ps) {
10348        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10349    }
10350
10351    private static boolean isExternal(PackageParser.Package pkg) {
10352        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10353    }
10354
10355    private static boolean isExternal(PackageSetting ps) {
10356        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10357    }
10358
10359    private static boolean isSystemApp(PackageParser.Package pkg) {
10360        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10361    }
10362
10363    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10364        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10365    }
10366
10367    private static boolean isSystemApp(ApplicationInfo info) {
10368        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10369    }
10370
10371    private static boolean isSystemApp(PackageSetting ps) {
10372        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10373    }
10374
10375    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10376        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10377    }
10378
10379    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10380        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10381    }
10382
10383    private int packageFlagsToInstallFlags(PackageSetting ps) {
10384        int installFlags = 0;
10385        if (isExternal(ps)) {
10386            installFlags |= PackageManager.INSTALL_EXTERNAL;
10387        }
10388        if (isForwardLocked(ps)) {
10389            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10390        }
10391        return installFlags;
10392    }
10393
10394    private void deleteTempPackageFiles() {
10395        final FilenameFilter filter = new FilenameFilter() {
10396            public boolean accept(File dir, String name) {
10397                return name.startsWith("vmdl") && name.endsWith(".tmp");
10398            }
10399        };
10400        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10401        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10402    }
10403
10404    private static final void deleteTempPackageFilesInDirectory(File directory,
10405            FilenameFilter filter) {
10406        final String[] tmpFilesList = directory.list(filter);
10407        if (tmpFilesList == null) {
10408            return;
10409        }
10410        for (int i = 0; i < tmpFilesList.length; i++) {
10411            final File tmpFile = new File(directory, tmpFilesList[i]);
10412            tmpFile.delete();
10413        }
10414    }
10415
10416    private File createTempPackageFile(File installDir) {
10417        File tmpPackageFile;
10418        try {
10419            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10420        } catch (IOException e) {
10421            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10422            return null;
10423        }
10424        try {
10425            FileUtils.setPermissions(
10426                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10427                    -1, -1);
10428            if (!SELinux.restorecon(tmpPackageFile)) {
10429                return null;
10430            }
10431        } catch (IOException e) {
10432            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10433            return null;
10434        }
10435        return tmpPackageFile;
10436    }
10437
10438    @Override
10439    public void deletePackageAsUser(final String packageName,
10440                                    final IPackageDeleteObserver observer,
10441                                    final int userId, final int flags) {
10442        mContext.enforceCallingOrSelfPermission(
10443                android.Manifest.permission.DELETE_PACKAGES, null);
10444        final int uid = Binder.getCallingUid();
10445        if (UserHandle.getUserId(uid) != userId) {
10446            mContext.enforceCallingPermission(
10447                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10448                    "deletePackage for user " + userId);
10449        }
10450        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10451            try {
10452                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10453            } catch (RemoteException re) {
10454            }
10455            return;
10456        }
10457
10458        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10459        // Queue up an async operation since the package deletion may take a little while.
10460        mHandler.post(new Runnable() {
10461            public void run() {
10462                mHandler.removeCallbacks(this);
10463                final int returnCode = deletePackageX(packageName, userId, flags);
10464                if (observer != null) {
10465                    try {
10466                        observer.packageDeleted(packageName, returnCode);
10467                    } catch (RemoteException e) {
10468                        Log.i(TAG, "Observer no longer exists.");
10469                    } //end catch
10470                } //end if
10471            } //end run
10472        });
10473    }
10474
10475    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10476        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10477                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10478        try {
10479            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10480                    || dpm.isDeviceOwner(packageName))) {
10481                return true;
10482            }
10483        } catch (RemoteException e) {
10484        }
10485        return false;
10486    }
10487
10488    /**
10489     *  This method is an internal method that could be get invoked either
10490     *  to delete an installed package or to clean up a failed installation.
10491     *  After deleting an installed package, a broadcast is sent to notify any
10492     *  listeners that the package has been installed. For cleaning up a failed
10493     *  installation, the broadcast is not necessary since the package's
10494     *  installation wouldn't have sent the initial broadcast either
10495     *  The key steps in deleting a package are
10496     *  deleting the package information in internal structures like mPackages,
10497     *  deleting the packages base directories through installd
10498     *  updating mSettings to reflect current status
10499     *  persisting settings for later use
10500     *  sending a broadcast if necessary
10501     */
10502    private int deletePackageX(String packageName, int userId, int flags) {
10503        final PackageRemovedInfo info = new PackageRemovedInfo();
10504        final boolean res;
10505
10506        if (isPackageDeviceAdmin(packageName, userId)) {
10507            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10508            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10509        }
10510
10511        boolean removedForAllUsers = false;
10512        boolean systemUpdate = false;
10513
10514        // for the uninstall-updates case and restricted profiles, remember the per-
10515        // userhandle installed state
10516        int[] allUsers;
10517        boolean[] perUserInstalled;
10518        synchronized (mPackages) {
10519            PackageSetting ps = mSettings.mPackages.get(packageName);
10520            allUsers = sUserManager.getUserIds();
10521            perUserInstalled = new boolean[allUsers.length];
10522            for (int i = 0; i < allUsers.length; i++) {
10523                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10524            }
10525        }
10526
10527        synchronized (mInstallLock) {
10528            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10529            res = deletePackageLI(packageName,
10530                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10531                            ? UserHandle.ALL : new UserHandle(userId),
10532                    true, allUsers, perUserInstalled,
10533                    flags | REMOVE_CHATTY, info, true);
10534            systemUpdate = info.isRemovedPackageSystemUpdate;
10535            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10536                removedForAllUsers = true;
10537            }
10538            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10539                    + " removedForAllUsers=" + removedForAllUsers);
10540        }
10541
10542        if (res) {
10543            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10544
10545            // If the removed package was a system update, the old system package
10546            // was re-enabled; we need to broadcast this information
10547            if (systemUpdate) {
10548                Bundle extras = new Bundle(1);
10549                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10550                        ? info.removedAppId : info.uid);
10551                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10552
10553                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10554                        extras, null, null, null);
10555                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10556                        extras, null, null, null);
10557                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10558                        null, packageName, null, null);
10559            }
10560        }
10561        // Force a gc here.
10562        Runtime.getRuntime().gc();
10563        // Delete the resources here after sending the broadcast to let
10564        // other processes clean up before deleting resources.
10565        if (info.args != null) {
10566            synchronized (mInstallLock) {
10567                info.args.doPostDeleteLI(true);
10568            }
10569        }
10570
10571        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10572    }
10573
10574    static class PackageRemovedInfo {
10575        String removedPackage;
10576        int uid = -1;
10577        int removedAppId = -1;
10578        int[] removedUsers = null;
10579        boolean isRemovedPackageSystemUpdate = false;
10580        // Clean up resources deleted packages.
10581        InstallArgs args = null;
10582
10583        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10584            Bundle extras = new Bundle(1);
10585            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10586            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10587            if (replacing) {
10588                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10589            }
10590            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10591            if (removedPackage != null) {
10592                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10593                        extras, null, null, removedUsers);
10594                if (fullRemove && !replacing) {
10595                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10596                            extras, null, null, removedUsers);
10597                }
10598            }
10599            if (removedAppId >= 0) {
10600                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10601                        removedUsers);
10602            }
10603        }
10604    }
10605
10606    /*
10607     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10608     * flag is not set, the data directory is removed as well.
10609     * make sure this flag is set for partially installed apps. If not its meaningless to
10610     * delete a partially installed application.
10611     */
10612    private void removePackageDataLI(PackageSetting ps,
10613            int[] allUserHandles, boolean[] perUserInstalled,
10614            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10615        String packageName = ps.name;
10616        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10617        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10618        // Retrieve object to delete permissions for shared user later on
10619        final PackageSetting deletedPs;
10620        // reader
10621        synchronized (mPackages) {
10622            deletedPs = mSettings.mPackages.get(packageName);
10623            if (outInfo != null) {
10624                outInfo.removedPackage = packageName;
10625                outInfo.removedUsers = deletedPs != null
10626                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10627                        : null;
10628            }
10629        }
10630        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10631            removeDataDirsLI(packageName);
10632            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10633        }
10634        // writer
10635        synchronized (mPackages) {
10636            if (deletedPs != null) {
10637                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10638                    if (outInfo != null) {
10639                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10640                    }
10641                    if (deletedPs != null) {
10642                        updatePermissionsLPw(deletedPs.name, null, 0);
10643                        if (deletedPs.sharedUser != null) {
10644                            // remove permissions associated with package
10645                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10646                        }
10647                    }
10648                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10649                }
10650                // make sure to preserve per-user disabled state if this removal was just
10651                // a downgrade of a system app to the factory package
10652                if (allUserHandles != null && perUserInstalled != null) {
10653                    if (DEBUG_REMOVE) {
10654                        Slog.d(TAG, "Propagating install state across downgrade");
10655                    }
10656                    for (int i = 0; i < allUserHandles.length; i++) {
10657                        if (DEBUG_REMOVE) {
10658                            Slog.d(TAG, "    user " + allUserHandles[i]
10659                                    + " => " + perUserInstalled[i]);
10660                        }
10661                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10662                    }
10663                }
10664            }
10665            // can downgrade to reader
10666            if (writeSettings) {
10667                // Save settings now
10668                mSettings.writeLPr();
10669            }
10670        }
10671        if (outInfo != null) {
10672            // A user ID was deleted here. Go through all users and remove it
10673            // from KeyStore.
10674            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10675        }
10676    }
10677
10678    static boolean locationIsPrivileged(File path) {
10679        try {
10680            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10681                    .getCanonicalPath();
10682            return path.getCanonicalPath().startsWith(privilegedAppDir);
10683        } catch (IOException e) {
10684            Slog.e(TAG, "Unable to access code path " + path);
10685        }
10686        return false;
10687    }
10688
10689    /*
10690     * Tries to delete system package.
10691     */
10692    private boolean deleteSystemPackageLI(PackageSetting newPs,
10693            int[] allUserHandles, boolean[] perUserInstalled,
10694            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10695        final boolean applyUserRestrictions
10696                = (allUserHandles != null) && (perUserInstalled != null);
10697        PackageSetting disabledPs = null;
10698        // Confirm if the system package has been updated
10699        // An updated system app can be deleted. This will also have to restore
10700        // the system pkg from system partition
10701        // reader
10702        synchronized (mPackages) {
10703            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10704        }
10705        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10706                + " disabledPs=" + disabledPs);
10707        if (disabledPs == null) {
10708            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10709            return false;
10710        } else if (DEBUG_REMOVE) {
10711            Slog.d(TAG, "Deleting system pkg from data partition");
10712        }
10713        if (DEBUG_REMOVE) {
10714            if (applyUserRestrictions) {
10715                Slog.d(TAG, "Remembering install states:");
10716                for (int i = 0; i < allUserHandles.length; i++) {
10717                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10718                }
10719            }
10720        }
10721        // Delete the updated package
10722        outInfo.isRemovedPackageSystemUpdate = true;
10723        if (disabledPs.versionCode < newPs.versionCode) {
10724            // Delete data for downgrades
10725            flags &= ~PackageManager.DELETE_KEEP_DATA;
10726        } else {
10727            // Preserve data by setting flag
10728            flags |= PackageManager.DELETE_KEEP_DATA;
10729        }
10730        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10731                allUserHandles, perUserInstalled, outInfo, writeSettings);
10732        if (!ret) {
10733            return false;
10734        }
10735        // writer
10736        synchronized (mPackages) {
10737            // Reinstate the old system package
10738            mSettings.enableSystemPackageLPw(newPs.name);
10739            // Remove any native libraries from the upgraded package.
10740            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10741        }
10742        // Install the system package
10743        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10744        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10745        if (locationIsPrivileged(disabledPs.codePath)) {
10746            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10747        }
10748        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10749                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10750
10751        if (newPkg == null) {
10752            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10753                    + " with error:" + mLastScanError);
10754            return false;
10755        }
10756        // writer
10757        synchronized (mPackages) {
10758            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10759            setInternalAppNativeLibraryPath(newPkg, ps);
10760            updatePermissionsLPw(newPkg.packageName, newPkg,
10761                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10762            if (applyUserRestrictions) {
10763                if (DEBUG_REMOVE) {
10764                    Slog.d(TAG, "Propagating install state across reinstall");
10765                }
10766                for (int i = 0; i < allUserHandles.length; i++) {
10767                    if (DEBUG_REMOVE) {
10768                        Slog.d(TAG, "    user " + allUserHandles[i]
10769                                + " => " + perUserInstalled[i]);
10770                    }
10771                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10772                }
10773                // Regardless of writeSettings we need to ensure that this restriction
10774                // state propagation is persisted
10775                mSettings.writeAllUsersPackageRestrictionsLPr();
10776            }
10777            // can downgrade to reader here
10778            if (writeSettings) {
10779                mSettings.writeLPr();
10780            }
10781        }
10782        return true;
10783    }
10784
10785    private boolean deleteInstalledPackageLI(PackageSetting ps,
10786            boolean deleteCodeAndResources, int flags,
10787            int[] allUserHandles, boolean[] perUserInstalled,
10788            PackageRemovedInfo outInfo, boolean writeSettings) {
10789        if (outInfo != null) {
10790            outInfo.uid = ps.appId;
10791        }
10792
10793        // Delete package data from internal structures and also remove data if flag is set
10794        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10795
10796        // Delete application code and resources
10797        if (deleteCodeAndResources && (outInfo != null)) {
10798            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10799                    ps.resourcePathString, ps.nativeLibraryPathString,
10800                    getAppInstructionSetFromSettings(ps));
10801        }
10802        return true;
10803    }
10804
10805    /*
10806     * This method handles package deletion in general
10807     */
10808    private boolean deletePackageLI(String packageName, UserHandle user,
10809            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10810            int flags, PackageRemovedInfo outInfo,
10811            boolean writeSettings) {
10812        if (packageName == null) {
10813            Slog.w(TAG, "Attempt to delete null packageName.");
10814            return false;
10815        }
10816        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10817        PackageSetting ps;
10818        boolean dataOnly = false;
10819        int removeUser = -1;
10820        int appId = -1;
10821        synchronized (mPackages) {
10822            ps = mSettings.mPackages.get(packageName);
10823            if (ps == null) {
10824                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10825                return false;
10826            }
10827            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10828                    && user.getIdentifier() != UserHandle.USER_ALL) {
10829                // The caller is asking that the package only be deleted for a single
10830                // user.  To do this, we just mark its uninstalled state and delete
10831                // its data.  If this is a system app, we only allow this to happen if
10832                // they have set the special DELETE_SYSTEM_APP which requests different
10833                // semantics than normal for uninstalling system apps.
10834                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10835                ps.setUserState(user.getIdentifier(),
10836                        COMPONENT_ENABLED_STATE_DEFAULT,
10837                        false, //installed
10838                        true,  //stopped
10839                        true,  //notLaunched
10840                        false, //blocked
10841                        null, null, null);
10842                if (!isSystemApp(ps)) {
10843                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10844                        // Other user still have this package installed, so all
10845                        // we need to do is clear this user's data and save that
10846                        // it is uninstalled.
10847                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10848                        removeUser = user.getIdentifier();
10849                        appId = ps.appId;
10850                        mSettings.writePackageRestrictionsLPr(removeUser);
10851                    } else {
10852                        // We need to set it back to 'installed' so the uninstall
10853                        // broadcasts will be sent correctly.
10854                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10855                        ps.setInstalled(true, user.getIdentifier());
10856                    }
10857                } else {
10858                    // This is a system app, so we assume that the
10859                    // other users still have this package installed, so all
10860                    // we need to do is clear this user's data and save that
10861                    // it is uninstalled.
10862                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10863                    removeUser = user.getIdentifier();
10864                    appId = ps.appId;
10865                    mSettings.writePackageRestrictionsLPr(removeUser);
10866                }
10867            }
10868        }
10869
10870        if (removeUser >= 0) {
10871            // From above, we determined that we are deleting this only
10872            // for a single user.  Continue the work here.
10873            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10874            if (outInfo != null) {
10875                outInfo.removedPackage = packageName;
10876                outInfo.removedAppId = appId;
10877                outInfo.removedUsers = new int[] {removeUser};
10878            }
10879            mInstaller.clearUserData(packageName, removeUser);
10880            removeKeystoreDataIfNeeded(removeUser, appId);
10881            schedulePackageCleaning(packageName, removeUser, false);
10882            return true;
10883        }
10884
10885        if (dataOnly) {
10886            // Delete application data first
10887            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10888            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10889            return true;
10890        }
10891
10892        boolean ret = false;
10893        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10894        if (isSystemApp(ps)) {
10895            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10896            // When an updated system application is deleted we delete the existing resources as well and
10897            // fall back to existing code in system partition
10898            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10899                    flags, outInfo, writeSettings);
10900        } else {
10901            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10902            // Kill application pre-emptively especially for apps on sd.
10903            killApplication(packageName, ps.appId, "uninstall pkg");
10904            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10905                    allUserHandles, perUserInstalled,
10906                    outInfo, writeSettings);
10907        }
10908
10909        return ret;
10910    }
10911
10912    private final class ClearStorageConnection implements ServiceConnection {
10913        IMediaContainerService mContainerService;
10914
10915        @Override
10916        public void onServiceConnected(ComponentName name, IBinder service) {
10917            synchronized (this) {
10918                mContainerService = IMediaContainerService.Stub.asInterface(service);
10919                notifyAll();
10920            }
10921        }
10922
10923        @Override
10924        public void onServiceDisconnected(ComponentName name) {
10925        }
10926    }
10927
10928    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10929        final boolean mounted;
10930        if (Environment.isExternalStorageEmulated()) {
10931            mounted = true;
10932        } else {
10933            final String status = Environment.getExternalStorageState();
10934
10935            mounted = status.equals(Environment.MEDIA_MOUNTED)
10936                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10937        }
10938
10939        if (!mounted) {
10940            return;
10941        }
10942
10943        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10944        int[] users;
10945        if (userId == UserHandle.USER_ALL) {
10946            users = sUserManager.getUserIds();
10947        } else {
10948            users = new int[] { userId };
10949        }
10950        final ClearStorageConnection conn = new ClearStorageConnection();
10951        if (mContext.bindServiceAsUser(
10952                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10953            try {
10954                for (int curUser : users) {
10955                    long timeout = SystemClock.uptimeMillis() + 5000;
10956                    synchronized (conn) {
10957                        long now = SystemClock.uptimeMillis();
10958                        while (conn.mContainerService == null && now < timeout) {
10959                            try {
10960                                conn.wait(timeout - now);
10961                            } catch (InterruptedException e) {
10962                            }
10963                        }
10964                    }
10965                    if (conn.mContainerService == null) {
10966                        return;
10967                    }
10968
10969                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10970                    clearDirectory(conn.mContainerService,
10971                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10972                    if (allData) {
10973                        clearDirectory(conn.mContainerService,
10974                                userEnv.buildExternalStorageAppDataDirs(packageName));
10975                        clearDirectory(conn.mContainerService,
10976                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10977                    }
10978                }
10979            } finally {
10980                mContext.unbindService(conn);
10981            }
10982        }
10983    }
10984
10985    @Override
10986    public void clearApplicationUserData(final String packageName,
10987            final IPackageDataObserver observer, final int userId) {
10988        mContext.enforceCallingOrSelfPermission(
10989                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10990        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10991        // Queue up an async operation since the package deletion may take a little while.
10992        mHandler.post(new Runnable() {
10993            public void run() {
10994                mHandler.removeCallbacks(this);
10995                final boolean succeeded;
10996                synchronized (mInstallLock) {
10997                    succeeded = clearApplicationUserDataLI(packageName, userId);
10998                }
10999                clearExternalStorageDataSync(packageName, userId, true);
11000                if (succeeded) {
11001                    // invoke DeviceStorageMonitor's update method to clear any notifications
11002                    DeviceStorageMonitorInternal
11003                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11004                    if (dsm != null) {
11005                        dsm.checkMemory();
11006                    }
11007                }
11008                if(observer != null) {
11009                    try {
11010                        observer.onRemoveCompleted(packageName, succeeded);
11011                    } catch (RemoteException e) {
11012                        Log.i(TAG, "Observer no longer exists.");
11013                    }
11014                } //end if observer
11015            } //end run
11016        });
11017    }
11018
11019    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11020        if (packageName == null) {
11021            Slog.w(TAG, "Attempt to delete null packageName.");
11022            return false;
11023        }
11024        PackageParser.Package p;
11025        boolean dataOnly = false;
11026        final int appId;
11027        synchronized (mPackages) {
11028            p = mPackages.get(packageName);
11029            if (p == null) {
11030                dataOnly = true;
11031                PackageSetting ps = mSettings.mPackages.get(packageName);
11032                if ((ps == null) || (ps.pkg == null)) {
11033                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11034                    return false;
11035                }
11036                p = ps.pkg;
11037            }
11038            if (!dataOnly) {
11039                // need to check this only for fully installed applications
11040                if (p == null) {
11041                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11042                    return false;
11043                }
11044                final ApplicationInfo applicationInfo = p.applicationInfo;
11045                if (applicationInfo == null) {
11046                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11047                    return false;
11048                }
11049            }
11050            if (p != null && p.applicationInfo != null) {
11051                appId = p.applicationInfo.uid;
11052            } else {
11053                appId = -1;
11054            }
11055        }
11056        int retCode = mInstaller.clearUserData(packageName, userId);
11057        if (retCode < 0) {
11058            Slog.w(TAG, "Couldn't remove cache files for package: "
11059                    + packageName);
11060            return false;
11061        }
11062        removeKeystoreDataIfNeeded(userId, appId);
11063        return true;
11064    }
11065
11066    /**
11067     * Remove entries from the keystore daemon. Will only remove it if the
11068     * {@code appId} is valid.
11069     */
11070    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11071        if (appId < 0) {
11072            return;
11073        }
11074
11075        final KeyStore keyStore = KeyStore.getInstance();
11076        if (keyStore != null) {
11077            if (userId == UserHandle.USER_ALL) {
11078                for (final int individual : sUserManager.getUserIds()) {
11079                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11080                }
11081            } else {
11082                keyStore.clearUid(UserHandle.getUid(userId, appId));
11083            }
11084        } else {
11085            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11086        }
11087    }
11088
11089    @Override
11090    public void deleteApplicationCacheFiles(final String packageName,
11091            final IPackageDataObserver observer) {
11092        mContext.enforceCallingOrSelfPermission(
11093                android.Manifest.permission.DELETE_CACHE_FILES, null);
11094        // Queue up an async operation since the package deletion may take a little while.
11095        final int userId = UserHandle.getCallingUserId();
11096        mHandler.post(new Runnable() {
11097            public void run() {
11098                mHandler.removeCallbacks(this);
11099                final boolean succeded;
11100                synchronized (mInstallLock) {
11101                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11102                }
11103                clearExternalStorageDataSync(packageName, userId, false);
11104                if(observer != null) {
11105                    try {
11106                        observer.onRemoveCompleted(packageName, succeded);
11107                    } catch (RemoteException e) {
11108                        Log.i(TAG, "Observer no longer exists.");
11109                    }
11110                } //end if observer
11111            } //end run
11112        });
11113    }
11114
11115    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11116        if (packageName == null) {
11117            Slog.w(TAG, "Attempt to delete null packageName.");
11118            return false;
11119        }
11120        PackageParser.Package p;
11121        synchronized (mPackages) {
11122            p = mPackages.get(packageName);
11123        }
11124        if (p == null) {
11125            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11126            return false;
11127        }
11128        final ApplicationInfo applicationInfo = p.applicationInfo;
11129        if (applicationInfo == null) {
11130            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11131            return false;
11132        }
11133        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11134        if (retCode < 0) {
11135            Slog.w(TAG, "Couldn't remove cache files for package: "
11136                       + packageName + " u" + userId);
11137            return false;
11138        }
11139        return true;
11140    }
11141
11142    @Override
11143    public void getPackageSizeInfo(final String packageName, int userHandle,
11144            final IPackageStatsObserver observer) {
11145        mContext.enforceCallingOrSelfPermission(
11146                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11147        if (packageName == null) {
11148            throw new IllegalArgumentException("Attempt to get size of null packageName");
11149        }
11150
11151        PackageStats stats = new PackageStats(packageName, userHandle);
11152
11153        /*
11154         * Queue up an async operation since the package measurement may take a
11155         * little while.
11156         */
11157        Message msg = mHandler.obtainMessage(INIT_COPY);
11158        msg.obj = new MeasureParams(stats, observer);
11159        mHandler.sendMessage(msg);
11160    }
11161
11162    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11163            PackageStats pStats) {
11164        if (packageName == null) {
11165            Slog.w(TAG, "Attempt to get size of null packageName.");
11166            return false;
11167        }
11168        PackageParser.Package p;
11169        boolean dataOnly = false;
11170        String libDirPath = null;
11171        String asecPath = null;
11172        PackageSetting ps = null;
11173        synchronized (mPackages) {
11174            p = mPackages.get(packageName);
11175            ps = mSettings.mPackages.get(packageName);
11176            if(p == null) {
11177                dataOnly = true;
11178                if((ps == null) || (ps.pkg == null)) {
11179                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11180                    return false;
11181                }
11182                p = ps.pkg;
11183            }
11184            if (ps != null) {
11185                libDirPath = ps.nativeLibraryPathString;
11186            }
11187            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11188                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11189                if (secureContainerId != null) {
11190                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11191                }
11192            }
11193        }
11194        String publicSrcDir = null;
11195        if(!dataOnly) {
11196            final ApplicationInfo applicationInfo = p.applicationInfo;
11197            if (applicationInfo == null) {
11198                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11199                return false;
11200            }
11201            if (isForwardLocked(p)) {
11202                publicSrcDir = applicationInfo.publicSourceDir;
11203            }
11204        }
11205        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11206                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11207                pStats);
11208        if (res < 0) {
11209            return false;
11210        }
11211
11212        // Fix-up for forward-locked applications in ASEC containers.
11213        if (!isExternal(p)) {
11214            pStats.codeSize += pStats.externalCodeSize;
11215            pStats.externalCodeSize = 0L;
11216        }
11217
11218        return true;
11219    }
11220
11221
11222    @Override
11223    public void addPackageToPreferred(String packageName) {
11224        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11225    }
11226
11227    @Override
11228    public void removePackageFromPreferred(String packageName) {
11229        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11230    }
11231
11232    @Override
11233    public List<PackageInfo> getPreferredPackages(int flags) {
11234        return new ArrayList<PackageInfo>();
11235    }
11236
11237    private int getUidTargetSdkVersionLockedLPr(int uid) {
11238        Object obj = mSettings.getUserIdLPr(uid);
11239        if (obj instanceof SharedUserSetting) {
11240            final SharedUserSetting sus = (SharedUserSetting) obj;
11241            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11242            final Iterator<PackageSetting> it = sus.packages.iterator();
11243            while (it.hasNext()) {
11244                final PackageSetting ps = it.next();
11245                if (ps.pkg != null) {
11246                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11247                    if (v < vers) vers = v;
11248                }
11249            }
11250            return vers;
11251        } else if (obj instanceof PackageSetting) {
11252            final PackageSetting ps = (PackageSetting) obj;
11253            if (ps.pkg != null) {
11254                return ps.pkg.applicationInfo.targetSdkVersion;
11255            }
11256        }
11257        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11258    }
11259
11260    @Override
11261    public void addPreferredActivity(IntentFilter filter, int match,
11262            ComponentName[] set, ComponentName activity, int userId) {
11263        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11264    }
11265
11266    private void addPreferredActivityInternal(IntentFilter filter, int match,
11267            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11268        // writer
11269        int callingUid = Binder.getCallingUid();
11270        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11271        if (filter.countActions() == 0) {
11272            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11273            return;
11274        }
11275        synchronized (mPackages) {
11276            if (mContext.checkCallingOrSelfPermission(
11277                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11278                    != PackageManager.PERMISSION_GRANTED) {
11279                if (getUidTargetSdkVersionLockedLPr(callingUid)
11280                        < Build.VERSION_CODES.FROYO) {
11281                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11282                            + callingUid);
11283                    return;
11284                }
11285                mContext.enforceCallingOrSelfPermission(
11286                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11287            }
11288
11289            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11290            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11291            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11292                    new PreferredActivity(filter, match, set, activity, always));
11293            mSettings.writePackageRestrictionsLPr(userId);
11294        }
11295    }
11296
11297    @Override
11298    public void replacePreferredActivity(IntentFilter filter, int match,
11299            ComponentName[] set, ComponentName activity) {
11300        if (filter.countActions() != 1) {
11301            throw new IllegalArgumentException(
11302                    "replacePreferredActivity expects filter to have only 1 action.");
11303        }
11304        if (filter.countDataAuthorities() != 0
11305                || filter.countDataPaths() != 0
11306                || filter.countDataSchemes() > 1
11307                || filter.countDataTypes() != 0) {
11308            throw new IllegalArgumentException(
11309                    "replacePreferredActivity expects filter to have no data authorities, " +
11310                    "paths, or types; and at most one scheme.");
11311        }
11312        synchronized (mPackages) {
11313            if (mContext.checkCallingOrSelfPermission(
11314                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11315                    != PackageManager.PERMISSION_GRANTED) {
11316                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11317                        < Build.VERSION_CODES.FROYO) {
11318                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11319                            + Binder.getCallingUid());
11320                    return;
11321                }
11322                mContext.enforceCallingOrSelfPermission(
11323                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11324            }
11325
11326            final int callingUserId = UserHandle.getCallingUserId();
11327            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11328            if (pir != null) {
11329                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11330                if (filter.countDataSchemes() == 1) {
11331                    Uri.Builder builder = new Uri.Builder();
11332                    builder.scheme(filter.getDataScheme(0));
11333                    intent.setData(builder.build());
11334                }
11335                List<PreferredActivity> matches = pir.queryIntent(
11336                        intent, null, true, callingUserId);
11337                if (DEBUG_PREFERRED) {
11338                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11339                }
11340                for (int i = 0; i < matches.size(); i++) {
11341                    PreferredActivity pa = matches.get(i);
11342                    if (DEBUG_PREFERRED) {
11343                        Slog.i(TAG, "Removing preferred activity "
11344                                + pa.mPref.mComponent + ":");
11345                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11346                    }
11347                    pir.removeFilter(pa);
11348                }
11349            }
11350            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11351        }
11352    }
11353
11354    @Override
11355    public void clearPackagePreferredActivities(String packageName) {
11356        final int uid = Binder.getCallingUid();
11357        // writer
11358        synchronized (mPackages) {
11359            PackageParser.Package pkg = mPackages.get(packageName);
11360            if (pkg == null || pkg.applicationInfo.uid != uid) {
11361                if (mContext.checkCallingOrSelfPermission(
11362                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11363                        != PackageManager.PERMISSION_GRANTED) {
11364                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11365                            < Build.VERSION_CODES.FROYO) {
11366                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11367                                + Binder.getCallingUid());
11368                        return;
11369                    }
11370                    mContext.enforceCallingOrSelfPermission(
11371                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11372                }
11373            }
11374
11375            int user = UserHandle.getCallingUserId();
11376            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11377                mSettings.writePackageRestrictionsLPr(user);
11378                scheduleWriteSettingsLocked();
11379            }
11380        }
11381    }
11382
11383    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11384    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11385        ArrayList<PreferredActivity> removed = null;
11386        boolean changed = false;
11387        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11388            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11389            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11390            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11391                continue;
11392            }
11393            Iterator<PreferredActivity> it = pir.filterIterator();
11394            while (it.hasNext()) {
11395                PreferredActivity pa = it.next();
11396                // Mark entry for removal only if it matches the package name
11397                // and the entry is of type "always".
11398                if (packageName == null ||
11399                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11400                                && pa.mPref.mAlways)) {
11401                    if (removed == null) {
11402                        removed = new ArrayList<PreferredActivity>();
11403                    }
11404                    removed.add(pa);
11405                }
11406            }
11407            if (removed != null) {
11408                for (int j=0; j<removed.size(); j++) {
11409                    PreferredActivity pa = removed.get(j);
11410                    pir.removeFilter(pa);
11411                }
11412                changed = true;
11413            }
11414        }
11415        return changed;
11416    }
11417
11418    @Override
11419    public void resetPreferredActivities(int userId) {
11420        mContext.enforceCallingOrSelfPermission(
11421                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11422        // writer
11423        synchronized (mPackages) {
11424            int user = UserHandle.getCallingUserId();
11425            clearPackagePreferredActivitiesLPw(null, user);
11426            mSettings.readDefaultPreferredAppsLPw(this, user);
11427            mSettings.writePackageRestrictionsLPr(user);
11428            scheduleWriteSettingsLocked();
11429        }
11430    }
11431
11432    @Override
11433    public int getPreferredActivities(List<IntentFilter> outFilters,
11434            List<ComponentName> outActivities, String packageName) {
11435
11436        int num = 0;
11437        final int userId = UserHandle.getCallingUserId();
11438        // reader
11439        synchronized (mPackages) {
11440            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11441            if (pir != null) {
11442                final Iterator<PreferredActivity> it = pir.filterIterator();
11443                while (it.hasNext()) {
11444                    final PreferredActivity pa = it.next();
11445                    if (packageName == null
11446                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11447                                    && pa.mPref.mAlways)) {
11448                        if (outFilters != null) {
11449                            outFilters.add(new IntentFilter(pa));
11450                        }
11451                        if (outActivities != null) {
11452                            outActivities.add(pa.mPref.mComponent);
11453                        }
11454                    }
11455                }
11456            }
11457        }
11458
11459        return num;
11460    }
11461
11462    @Override
11463    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11464            int userId) {
11465        int callingUid = Binder.getCallingUid();
11466        if (callingUid != Process.SYSTEM_UID) {
11467            throw new SecurityException(
11468                    "addPersistentPreferredActivity can only be run by the system");
11469        }
11470        if (filter.countActions() == 0) {
11471            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11472            return;
11473        }
11474        synchronized (mPackages) {
11475            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11476                    " :");
11477            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11478            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11479                    new PersistentPreferredActivity(filter, activity));
11480            mSettings.writePackageRestrictionsLPr(userId);
11481        }
11482    }
11483
11484    @Override
11485    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11486        int callingUid = Binder.getCallingUid();
11487        if (callingUid != Process.SYSTEM_UID) {
11488            throw new SecurityException(
11489                    "clearPackagePersistentPreferredActivities can only be run by the system");
11490        }
11491        ArrayList<PersistentPreferredActivity> removed = null;
11492        boolean changed = false;
11493        synchronized (mPackages) {
11494            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11495                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11496                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11497                        .valueAt(i);
11498                if (userId != thisUserId) {
11499                    continue;
11500                }
11501                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11502                while (it.hasNext()) {
11503                    PersistentPreferredActivity ppa = it.next();
11504                    // Mark entry for removal only if it matches the package name.
11505                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11506                        if (removed == null) {
11507                            removed = new ArrayList<PersistentPreferredActivity>();
11508                        }
11509                        removed.add(ppa);
11510                    }
11511                }
11512                if (removed != null) {
11513                    for (int j=0; j<removed.size(); j++) {
11514                        PersistentPreferredActivity ppa = removed.get(j);
11515                        ppir.removeFilter(ppa);
11516                    }
11517                    changed = true;
11518                }
11519            }
11520
11521            if (changed) {
11522                mSettings.writePackageRestrictionsLPr(userId);
11523            }
11524        }
11525    }
11526
11527    @Override
11528    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11529            int targetUserId, int flags) {
11530        mContext.enforceCallingOrSelfPermission(
11531                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11532        if (intentFilter.countActions() == 0) {
11533            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11534            return;
11535        }
11536        synchronized (mPackages) {
11537            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11538                    targetUserId, flags);
11539            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11540            mSettings.writePackageRestrictionsLPr(sourceUserId);
11541        }
11542    }
11543
11544    public void addCrossProfileIntentsForPackage(String packageName,
11545            int sourceUserId, int targetUserId) {
11546        mContext.enforceCallingOrSelfPermission(
11547                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11548        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11549        mSettings.writePackageRestrictionsLPr(sourceUserId);
11550    }
11551
11552    public void removeCrossProfileIntentsForPackage(String packageName,
11553            int sourceUserId, int targetUserId) {
11554        mContext.enforceCallingOrSelfPermission(
11555                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11556        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11557        mSettings.writePackageRestrictionsLPr(sourceUserId);
11558    }
11559
11560    @Override
11561    public void clearCrossProfileIntentFilters(int sourceUserId) {
11562        mContext.enforceCallingOrSelfPermission(
11563                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11564        synchronized (mPackages) {
11565            CrossProfileIntentResolver resolver =
11566                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11567            HashSet<CrossProfileIntentFilter> set =
11568                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11569            for (CrossProfileIntentFilter filter : set) {
11570                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11571                    resolver.removeFilter(filter);
11572                }
11573            }
11574            mSettings.writePackageRestrictionsLPr(sourceUserId);
11575        }
11576    }
11577
11578    @Override
11579    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11580        Intent intent = new Intent(Intent.ACTION_MAIN);
11581        intent.addCategory(Intent.CATEGORY_HOME);
11582
11583        final int callingUserId = UserHandle.getCallingUserId();
11584        List<ResolveInfo> list = queryIntentActivities(intent, null,
11585                PackageManager.GET_META_DATA, callingUserId);
11586        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11587                true, false, false, callingUserId);
11588
11589        allHomeCandidates.clear();
11590        if (list != null) {
11591            for (ResolveInfo ri : list) {
11592                allHomeCandidates.add(ri);
11593            }
11594        }
11595        return (preferred == null || preferred.activityInfo == null)
11596                ? null
11597                : new ComponentName(preferred.activityInfo.packageName,
11598                        preferred.activityInfo.name);
11599    }
11600
11601    @Override
11602    public void setApplicationEnabledSetting(String appPackageName,
11603            int newState, int flags, int userId, String callingPackage) {
11604        if (!sUserManager.exists(userId)) return;
11605        if (callingPackage == null) {
11606            callingPackage = Integer.toString(Binder.getCallingUid());
11607        }
11608        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11609    }
11610
11611    @Override
11612    public void setComponentEnabledSetting(ComponentName componentName,
11613            int newState, int flags, int userId) {
11614        if (!sUserManager.exists(userId)) return;
11615        setEnabledSetting(componentName.getPackageName(),
11616                componentName.getClassName(), newState, flags, userId, null);
11617    }
11618
11619    private void setEnabledSetting(final String packageName, String className, int newState,
11620            final int flags, int userId, String callingPackage) {
11621        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11622              || newState == COMPONENT_ENABLED_STATE_ENABLED
11623              || newState == COMPONENT_ENABLED_STATE_DISABLED
11624              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11625              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11626            throw new IllegalArgumentException("Invalid new component state: "
11627                    + newState);
11628        }
11629        PackageSetting pkgSetting;
11630        final int uid = Binder.getCallingUid();
11631        final int permission = mContext.checkCallingOrSelfPermission(
11632                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11633        enforceCrossUserPermission(uid, userId, false, "set enabled");
11634        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11635        boolean sendNow = false;
11636        boolean isApp = (className == null);
11637        String componentName = isApp ? packageName : className;
11638        int packageUid = -1;
11639        ArrayList<String> components;
11640
11641        // writer
11642        synchronized (mPackages) {
11643            pkgSetting = mSettings.mPackages.get(packageName);
11644            if (pkgSetting == null) {
11645                if (className == null) {
11646                    throw new IllegalArgumentException(
11647                            "Unknown package: " + packageName);
11648                }
11649                throw new IllegalArgumentException(
11650                        "Unknown component: " + packageName
11651                        + "/" + className);
11652            }
11653            // Allow root and verify that userId is not being specified by a different user
11654            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11655                throw new SecurityException(
11656                        "Permission Denial: attempt to change component state from pid="
11657                        + Binder.getCallingPid()
11658                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11659            }
11660            if (className == null) {
11661                // We're dealing with an application/package level state change
11662                if (pkgSetting.getEnabled(userId) == newState) {
11663                    // Nothing to do
11664                    return;
11665                }
11666                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11667                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11668                    // Don't care about who enables an app.
11669                    callingPackage = null;
11670                }
11671                pkgSetting.setEnabled(newState, userId, callingPackage);
11672                // pkgSetting.pkg.mSetEnabled = newState;
11673            } else {
11674                // We're dealing with a component level state change
11675                // First, verify that this is a valid class name.
11676                PackageParser.Package pkg = pkgSetting.pkg;
11677                if (pkg == null || !pkg.hasComponentClassName(className)) {
11678                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11679                        throw new IllegalArgumentException("Component class " + className
11680                                + " does not exist in " + packageName);
11681                    } else {
11682                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11683                                + className + " does not exist in " + packageName);
11684                    }
11685                }
11686                switch (newState) {
11687                case COMPONENT_ENABLED_STATE_ENABLED:
11688                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11689                        return;
11690                    }
11691                    break;
11692                case COMPONENT_ENABLED_STATE_DISABLED:
11693                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11694                        return;
11695                    }
11696                    break;
11697                case COMPONENT_ENABLED_STATE_DEFAULT:
11698                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11699                        return;
11700                    }
11701                    break;
11702                default:
11703                    Slog.e(TAG, "Invalid new component state: " + newState);
11704                    return;
11705                }
11706            }
11707            mSettings.writePackageRestrictionsLPr(userId);
11708            components = mPendingBroadcasts.get(userId, packageName);
11709            final boolean newPackage = components == null;
11710            if (newPackage) {
11711                components = new ArrayList<String>();
11712            }
11713            if (!components.contains(componentName)) {
11714                components.add(componentName);
11715            }
11716            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11717                sendNow = true;
11718                // Purge entry from pending broadcast list if another one exists already
11719                // since we are sending one right away.
11720                mPendingBroadcasts.remove(userId, packageName);
11721            } else {
11722                if (newPackage) {
11723                    mPendingBroadcasts.put(userId, packageName, components);
11724                }
11725                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11726                    // Schedule a message
11727                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11728                }
11729            }
11730        }
11731
11732        long callingId = Binder.clearCallingIdentity();
11733        try {
11734            if (sendNow) {
11735                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11736                sendPackageChangedBroadcast(packageName,
11737                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11738            }
11739        } finally {
11740            Binder.restoreCallingIdentity(callingId);
11741        }
11742    }
11743
11744    private void sendPackageChangedBroadcast(String packageName,
11745            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11746        if (DEBUG_INSTALL)
11747            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11748                    + componentNames);
11749        Bundle extras = new Bundle(4);
11750        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11751        String nameList[] = new String[componentNames.size()];
11752        componentNames.toArray(nameList);
11753        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11754        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11755        extras.putInt(Intent.EXTRA_UID, packageUid);
11756        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11757                new int[] {UserHandle.getUserId(packageUid)});
11758    }
11759
11760    @Override
11761    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11762        if (!sUserManager.exists(userId)) return;
11763        final int uid = Binder.getCallingUid();
11764        final int permission = mContext.checkCallingOrSelfPermission(
11765                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11766        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11767        enforceCrossUserPermission(uid, userId, true, "stop package");
11768        // writer
11769        synchronized (mPackages) {
11770            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11771                    uid, userId)) {
11772                scheduleWritePackageRestrictionsLocked(userId);
11773            }
11774        }
11775    }
11776
11777    @Override
11778    public String getInstallerPackageName(String packageName) {
11779        // reader
11780        synchronized (mPackages) {
11781            return mSettings.getInstallerPackageNameLPr(packageName);
11782        }
11783    }
11784
11785    @Override
11786    public int getApplicationEnabledSetting(String packageName, int userId) {
11787        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11788        int uid = Binder.getCallingUid();
11789        enforceCrossUserPermission(uid, userId, false, "get enabled");
11790        // reader
11791        synchronized (mPackages) {
11792            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11793        }
11794    }
11795
11796    @Override
11797    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11798        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11799        int uid = Binder.getCallingUid();
11800        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11801        // reader
11802        synchronized (mPackages) {
11803            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11804        }
11805    }
11806
11807    @Override
11808    public void enterSafeMode() {
11809        enforceSystemOrRoot("Only the system can request entering safe mode");
11810
11811        if (!mSystemReady) {
11812            mSafeMode = true;
11813        }
11814    }
11815
11816    @Override
11817    public void systemReady() {
11818        mSystemReady = true;
11819
11820        // Read the compatibilty setting when the system is ready.
11821        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11822                mContext.getContentResolver(),
11823                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11824        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11825        if (DEBUG_SETTINGS) {
11826            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11827        }
11828
11829        synchronized (mPackages) {
11830            // Verify that all of the preferred activity components actually
11831            // exist.  It is possible for applications to be updated and at
11832            // that point remove a previously declared activity component that
11833            // had been set as a preferred activity.  We try to clean this up
11834            // the next time we encounter that preferred activity, but it is
11835            // possible for the user flow to never be able to return to that
11836            // situation so here we do a sanity check to make sure we haven't
11837            // left any junk around.
11838            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11839            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11840                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11841                removed.clear();
11842                for (PreferredActivity pa : pir.filterSet()) {
11843                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11844                        removed.add(pa);
11845                    }
11846                }
11847                if (removed.size() > 0) {
11848                    for (int r=0; r<removed.size(); r++) {
11849                        PreferredActivity pa = removed.get(r);
11850                        Slog.w(TAG, "Removing dangling preferred activity: "
11851                                + pa.mPref.mComponent);
11852                        pir.removeFilter(pa);
11853                    }
11854                    mSettings.writePackageRestrictionsLPr(
11855                            mSettings.mPreferredActivities.keyAt(i));
11856                }
11857            }
11858        }
11859        sUserManager.systemReady();
11860    }
11861
11862    @Override
11863    public boolean isSafeMode() {
11864        return mSafeMode;
11865    }
11866
11867    @Override
11868    public boolean hasSystemUidErrors() {
11869        return mHasSystemUidErrors;
11870    }
11871
11872    static String arrayToString(int[] array) {
11873        StringBuffer buf = new StringBuffer(128);
11874        buf.append('[');
11875        if (array != null) {
11876            for (int i=0; i<array.length; i++) {
11877                if (i > 0) buf.append(", ");
11878                buf.append(array[i]);
11879            }
11880        }
11881        buf.append(']');
11882        return buf.toString();
11883    }
11884
11885    static class DumpState {
11886        public static final int DUMP_LIBS = 1 << 0;
11887
11888        public static final int DUMP_FEATURES = 1 << 1;
11889
11890        public static final int DUMP_RESOLVERS = 1 << 2;
11891
11892        public static final int DUMP_PERMISSIONS = 1 << 3;
11893
11894        public static final int DUMP_PACKAGES = 1 << 4;
11895
11896        public static final int DUMP_SHARED_USERS = 1 << 5;
11897
11898        public static final int DUMP_MESSAGES = 1 << 6;
11899
11900        public static final int DUMP_PROVIDERS = 1 << 7;
11901
11902        public static final int DUMP_VERIFIERS = 1 << 8;
11903
11904        public static final int DUMP_PREFERRED = 1 << 9;
11905
11906        public static final int DUMP_PREFERRED_XML = 1 << 10;
11907
11908        public static final int DUMP_KEYSETS = 1 << 11;
11909
11910        public static final int DUMP_VERSION = 1 << 12;
11911
11912        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11913
11914        private int mTypes;
11915
11916        private int mOptions;
11917
11918        private boolean mTitlePrinted;
11919
11920        private SharedUserSetting mSharedUser;
11921
11922        public boolean isDumping(int type) {
11923            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11924                return true;
11925            }
11926
11927            return (mTypes & type) != 0;
11928        }
11929
11930        public void setDump(int type) {
11931            mTypes |= type;
11932        }
11933
11934        public boolean isOptionEnabled(int option) {
11935            return (mOptions & option) != 0;
11936        }
11937
11938        public void setOptionEnabled(int option) {
11939            mOptions |= option;
11940        }
11941
11942        public boolean onTitlePrinted() {
11943            final boolean printed = mTitlePrinted;
11944            mTitlePrinted = true;
11945            return printed;
11946        }
11947
11948        public boolean getTitlePrinted() {
11949            return mTitlePrinted;
11950        }
11951
11952        public void setTitlePrinted(boolean enabled) {
11953            mTitlePrinted = enabled;
11954        }
11955
11956        public SharedUserSetting getSharedUser() {
11957            return mSharedUser;
11958        }
11959
11960        public void setSharedUser(SharedUserSetting user) {
11961            mSharedUser = user;
11962        }
11963    }
11964
11965    @Override
11966    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11967        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11968                != PackageManager.PERMISSION_GRANTED) {
11969            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11970                    + Binder.getCallingPid()
11971                    + ", uid=" + Binder.getCallingUid()
11972                    + " without permission "
11973                    + android.Manifest.permission.DUMP);
11974            return;
11975        }
11976
11977        DumpState dumpState = new DumpState();
11978        boolean fullPreferred = false;
11979        boolean checkin = false;
11980
11981        String packageName = null;
11982
11983        int opti = 0;
11984        while (opti < args.length) {
11985            String opt = args[opti];
11986            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11987                break;
11988            }
11989            opti++;
11990            if ("-a".equals(opt)) {
11991                // Right now we only know how to print all.
11992            } else if ("-h".equals(opt)) {
11993                pw.println("Package manager dump options:");
11994                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11995                pw.println("    --checkin: dump for a checkin");
11996                pw.println("    -f: print details of intent filters");
11997                pw.println("    -h: print this help");
11998                pw.println("  cmd may be one of:");
11999                pw.println("    l[ibraries]: list known shared libraries");
12000                pw.println("    f[ibraries]: list device features");
12001                pw.println("    k[eysets]: print known keysets");
12002                pw.println("    r[esolvers]: dump intent resolvers");
12003                pw.println("    perm[issions]: dump permissions");
12004                pw.println("    pref[erred]: print preferred package settings");
12005                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12006                pw.println("    prov[iders]: dump content providers");
12007                pw.println("    p[ackages]: dump installed packages");
12008                pw.println("    s[hared-users]: dump shared user IDs");
12009                pw.println("    m[essages]: print collected runtime messages");
12010                pw.println("    v[erifiers]: print package verifier info");
12011                pw.println("    version: print database version info");
12012                pw.println("    write: write current settings now");
12013                pw.println("    <package.name>: info about given package");
12014                return;
12015            } else if ("--checkin".equals(opt)) {
12016                checkin = true;
12017            } else if ("-f".equals(opt)) {
12018                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12019            } else {
12020                pw.println("Unknown argument: " + opt + "; use -h for help");
12021            }
12022        }
12023
12024        // Is the caller requesting to dump a particular piece of data?
12025        if (opti < args.length) {
12026            String cmd = args[opti];
12027            opti++;
12028            // Is this a package name?
12029            if ("android".equals(cmd) || cmd.contains(".")) {
12030                packageName = cmd;
12031                // When dumping a single package, we always dump all of its
12032                // filter information since the amount of data will be reasonable.
12033                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12034            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12035                dumpState.setDump(DumpState.DUMP_LIBS);
12036            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12037                dumpState.setDump(DumpState.DUMP_FEATURES);
12038            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12039                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12040            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12041                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12042            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12043                dumpState.setDump(DumpState.DUMP_PREFERRED);
12044            } else if ("preferred-xml".equals(cmd)) {
12045                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12046                if (opti < args.length && "--full".equals(args[opti])) {
12047                    fullPreferred = true;
12048                    opti++;
12049                }
12050            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12051                dumpState.setDump(DumpState.DUMP_PACKAGES);
12052            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12053                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12054            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12055                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12056            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12057                dumpState.setDump(DumpState.DUMP_MESSAGES);
12058            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12059                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12060            } else if ("version".equals(cmd)) {
12061                dumpState.setDump(DumpState.DUMP_VERSION);
12062            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12063                dumpState.setDump(DumpState.DUMP_KEYSETS);
12064            } else if ("write".equals(cmd)) {
12065                synchronized (mPackages) {
12066                    mSettings.writeLPr();
12067                    pw.println("Settings written.");
12068                    return;
12069                }
12070            }
12071        }
12072
12073        if (checkin) {
12074            pw.println("vers,1");
12075        }
12076
12077        // reader
12078        synchronized (mPackages) {
12079            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12080                if (!checkin) {
12081                    if (dumpState.onTitlePrinted())
12082                        pw.println();
12083                    pw.println("Database versions:");
12084                    pw.print("  SDK Version:");
12085                    pw.print(" internal=");
12086                    pw.print(mSettings.mInternalSdkPlatform);
12087                    pw.print(" external=");
12088                    pw.println(mSettings.mExternalSdkPlatform);
12089                    pw.print("  DB Version:");
12090                    pw.print(" internal=");
12091                    pw.print(mSettings.mInternalDatabaseVersion);
12092                    pw.print(" external=");
12093                    pw.println(mSettings.mExternalDatabaseVersion);
12094                }
12095            }
12096
12097            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12098                if (!checkin) {
12099                    if (dumpState.onTitlePrinted())
12100                        pw.println();
12101                    pw.println("Verifiers:");
12102                    pw.print("  Required: ");
12103                    pw.print(mRequiredVerifierPackage);
12104                    pw.print(" (uid=");
12105                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12106                    pw.println(")");
12107                } else if (mRequiredVerifierPackage != null) {
12108                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12109                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12110                }
12111            }
12112
12113            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12114                boolean printedHeader = false;
12115                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12116                while (it.hasNext()) {
12117                    String name = it.next();
12118                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12119                    if (!checkin) {
12120                        if (!printedHeader) {
12121                            if (dumpState.onTitlePrinted())
12122                                pw.println();
12123                            pw.println("Libraries:");
12124                            printedHeader = true;
12125                        }
12126                        pw.print("  ");
12127                    } else {
12128                        pw.print("lib,");
12129                    }
12130                    pw.print(name);
12131                    if (!checkin) {
12132                        pw.print(" -> ");
12133                    }
12134                    if (ent.path != null) {
12135                        if (!checkin) {
12136                            pw.print("(jar) ");
12137                            pw.print(ent.path);
12138                        } else {
12139                            pw.print(",jar,");
12140                            pw.print(ent.path);
12141                        }
12142                    } else {
12143                        if (!checkin) {
12144                            pw.print("(apk) ");
12145                            pw.print(ent.apk);
12146                        } else {
12147                            pw.print(",apk,");
12148                            pw.print(ent.apk);
12149                        }
12150                    }
12151                    pw.println();
12152                }
12153            }
12154
12155            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12156                if (dumpState.onTitlePrinted())
12157                    pw.println();
12158                if (!checkin) {
12159                    pw.println("Features:");
12160                }
12161                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12162                while (it.hasNext()) {
12163                    String name = it.next();
12164                    if (!checkin) {
12165                        pw.print("  ");
12166                    } else {
12167                        pw.print("feat,");
12168                    }
12169                    pw.println(name);
12170                }
12171            }
12172
12173            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12174                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12175                        : "Activity Resolver Table:", "  ", packageName,
12176                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12177                    dumpState.setTitlePrinted(true);
12178                }
12179                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12180                        : "Receiver Resolver Table:", "  ", packageName,
12181                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12182                    dumpState.setTitlePrinted(true);
12183                }
12184                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12185                        : "Service Resolver Table:", "  ", packageName,
12186                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12187                    dumpState.setTitlePrinted(true);
12188                }
12189                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12190                        : "Provider Resolver Table:", "  ", packageName,
12191                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12192                    dumpState.setTitlePrinted(true);
12193                }
12194            }
12195
12196            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12197                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12198                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12199                    int user = mSettings.mPreferredActivities.keyAt(i);
12200                    if (pir.dump(pw,
12201                            dumpState.getTitlePrinted()
12202                                ? "\nPreferred Activities User " + user + ":"
12203                                : "Preferred Activities User " + user + ":", "  ",
12204                            packageName, true)) {
12205                        dumpState.setTitlePrinted(true);
12206                    }
12207                }
12208            }
12209
12210            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12211                pw.flush();
12212                FileOutputStream fout = new FileOutputStream(fd);
12213                BufferedOutputStream str = new BufferedOutputStream(fout);
12214                XmlSerializer serializer = new FastXmlSerializer();
12215                try {
12216                    serializer.setOutput(str, "utf-8");
12217                    serializer.startDocument(null, true);
12218                    serializer.setFeature(
12219                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12220                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12221                    serializer.endDocument();
12222                    serializer.flush();
12223                } catch (IllegalArgumentException e) {
12224                    pw.println("Failed writing: " + e);
12225                } catch (IllegalStateException e) {
12226                    pw.println("Failed writing: " + e);
12227                } catch (IOException e) {
12228                    pw.println("Failed writing: " + e);
12229                }
12230            }
12231
12232            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12233                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12234            }
12235
12236            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12237                boolean printedSomething = false;
12238                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12239                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12240                        continue;
12241                    }
12242                    if (!printedSomething) {
12243                        if (dumpState.onTitlePrinted())
12244                            pw.println();
12245                        pw.println("Registered ContentProviders:");
12246                        printedSomething = true;
12247                    }
12248                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12249                    pw.print("    "); pw.println(p.toString());
12250                }
12251                printedSomething = false;
12252                for (Map.Entry<String, PackageParser.Provider> entry :
12253                        mProvidersByAuthority.entrySet()) {
12254                    PackageParser.Provider p = entry.getValue();
12255                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12256                        continue;
12257                    }
12258                    if (!printedSomething) {
12259                        if (dumpState.onTitlePrinted())
12260                            pw.println();
12261                        pw.println("ContentProvider Authorities:");
12262                        printedSomething = true;
12263                    }
12264                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12265                    pw.print("    "); pw.println(p.toString());
12266                    if (p.info != null && p.info.applicationInfo != null) {
12267                        final String appInfo = p.info.applicationInfo.toString();
12268                        pw.print("      applicationInfo="); pw.println(appInfo);
12269                    }
12270                }
12271            }
12272
12273            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12274                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12275            }
12276
12277            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12278                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12279            }
12280
12281            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12282                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12283            }
12284
12285            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12286                if (dumpState.onTitlePrinted())
12287                    pw.println();
12288                mSettings.dumpReadMessagesLPr(pw, dumpState);
12289
12290                pw.println();
12291                pw.println("Package warning messages:");
12292                final File fname = getSettingsProblemFile();
12293                FileInputStream in = null;
12294                try {
12295                    in = new FileInputStream(fname);
12296                    final int avail = in.available();
12297                    final byte[] data = new byte[avail];
12298                    in.read(data);
12299                    pw.print(new String(data));
12300                } catch (FileNotFoundException e) {
12301                } catch (IOException e) {
12302                } finally {
12303                    if (in != null) {
12304                        try {
12305                            in.close();
12306                        } catch (IOException e) {
12307                        }
12308                    }
12309                }
12310            }
12311        }
12312    }
12313
12314    // ------- apps on sdcard specific code -------
12315    static final boolean DEBUG_SD_INSTALL = false;
12316
12317    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12318
12319    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12320
12321    private boolean mMediaMounted = false;
12322
12323    private String getEncryptKey() {
12324        try {
12325            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12326                    SD_ENCRYPTION_KEYSTORE_NAME);
12327            if (sdEncKey == null) {
12328                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12329                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12330                if (sdEncKey == null) {
12331                    Slog.e(TAG, "Failed to create encryption keys");
12332                    return null;
12333                }
12334            }
12335            return sdEncKey;
12336        } catch (NoSuchAlgorithmException nsae) {
12337            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12338            return null;
12339        } catch (IOException ioe) {
12340            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12341            return null;
12342        }
12343
12344    }
12345
12346    /* package */static String getTempContainerId() {
12347        int tmpIdx = 1;
12348        String list[] = PackageHelper.getSecureContainerList();
12349        if (list != null) {
12350            for (final String name : list) {
12351                // Ignore null and non-temporary container entries
12352                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12353                    continue;
12354                }
12355
12356                String subStr = name.substring(mTempContainerPrefix.length());
12357                try {
12358                    int cid = Integer.parseInt(subStr);
12359                    if (cid >= tmpIdx) {
12360                        tmpIdx = cid + 1;
12361                    }
12362                } catch (NumberFormatException e) {
12363                }
12364            }
12365        }
12366        return mTempContainerPrefix + tmpIdx;
12367    }
12368
12369    /*
12370     * Update media status on PackageManager.
12371     */
12372    @Override
12373    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12374        int callingUid = Binder.getCallingUid();
12375        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12376            throw new SecurityException("Media status can only be updated by the system");
12377        }
12378        // reader; this apparently protects mMediaMounted, but should probably
12379        // be a different lock in that case.
12380        synchronized (mPackages) {
12381            Log.i(TAG, "Updating external media status from "
12382                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12383                    + (mediaStatus ? "mounted" : "unmounted"));
12384            if (DEBUG_SD_INSTALL)
12385                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12386                        + ", mMediaMounted=" + mMediaMounted);
12387            if (mediaStatus == mMediaMounted) {
12388                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12389                        : 0, -1);
12390                mHandler.sendMessage(msg);
12391                return;
12392            }
12393            mMediaMounted = mediaStatus;
12394        }
12395        // Queue up an async operation since the package installation may take a
12396        // little while.
12397        mHandler.post(new Runnable() {
12398            public void run() {
12399                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12400            }
12401        });
12402    }
12403
12404    /**
12405     * Called by MountService when the initial ASECs to scan are available.
12406     * Should block until all the ASEC containers are finished being scanned.
12407     */
12408    public void scanAvailableAsecs() {
12409        updateExternalMediaStatusInner(true, false, false);
12410        if (mShouldRestoreconData) {
12411            SELinuxMMAC.setRestoreconDone();
12412            mShouldRestoreconData = false;
12413        }
12414    }
12415
12416    /*
12417     * Collect information of applications on external media, map them against
12418     * existing containers and update information based on current mount status.
12419     * Please note that we always have to report status if reportStatus has been
12420     * set to true especially when unloading packages.
12421     */
12422    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12423            boolean externalStorage) {
12424        // Collection of uids
12425        int uidArr[] = null;
12426        // Collection of stale containers
12427        HashSet<String> removeCids = new HashSet<String>();
12428        // Collection of packages on external media with valid containers.
12429        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12430        // Get list of secure containers.
12431        final String list[] = PackageHelper.getSecureContainerList();
12432        if (list == null || list.length == 0) {
12433            Log.i(TAG, "No secure containers on sdcard");
12434        } else {
12435            // Process list of secure containers and categorize them
12436            // as active or stale based on their package internal state.
12437            int uidList[] = new int[list.length];
12438            int num = 0;
12439            // reader
12440            synchronized (mPackages) {
12441                for (String cid : list) {
12442                    if (DEBUG_SD_INSTALL)
12443                        Log.i(TAG, "Processing container " + cid);
12444                    String pkgName = getAsecPackageName(cid);
12445                    if (pkgName == null) {
12446                        if (DEBUG_SD_INSTALL)
12447                            Log.i(TAG, "Container : " + cid + " stale");
12448                        removeCids.add(cid);
12449                        continue;
12450                    }
12451                    if (DEBUG_SD_INSTALL)
12452                        Log.i(TAG, "Looking for pkg : " + pkgName);
12453
12454                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12455                    if (ps == null) {
12456                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12457                        removeCids.add(cid);
12458                        continue;
12459                    }
12460
12461                    /*
12462                     * Skip packages that are not external if we're unmounting
12463                     * external storage.
12464                     */
12465                    if (externalStorage && !isMounted && !isExternal(ps)) {
12466                        continue;
12467                    }
12468
12469                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12470                            getAppInstructionSetFromSettings(ps),
12471                            isForwardLocked(ps));
12472                    // The package status is changed only if the code path
12473                    // matches between settings and the container id.
12474                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12475                        if (DEBUG_SD_INSTALL) {
12476                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12477                                    + " at code path: " + ps.codePathString);
12478                        }
12479
12480                        // We do have a valid package installed on sdcard
12481                        processCids.put(args, ps.codePathString);
12482                        final int uid = ps.appId;
12483                        if (uid != -1) {
12484                            uidList[num++] = uid;
12485                        }
12486                    } else {
12487                        Log.i(TAG, "Deleting stale container for " + cid);
12488                        removeCids.add(cid);
12489                    }
12490                }
12491            }
12492
12493            if (num > 0) {
12494                // Sort uid list
12495                Arrays.sort(uidList, 0, num);
12496                // Throw away duplicates
12497                uidArr = new int[num];
12498                uidArr[0] = uidList[0];
12499                int di = 0;
12500                for (int i = 1; i < num; i++) {
12501                    if (uidList[i - 1] != uidList[i]) {
12502                        uidArr[di++] = uidList[i];
12503                    }
12504                }
12505            }
12506        }
12507        // Process packages with valid entries.
12508        if (isMounted) {
12509            if (DEBUG_SD_INSTALL)
12510                Log.i(TAG, "Loading packages");
12511            loadMediaPackages(processCids, uidArr, removeCids);
12512            startCleaningPackages();
12513        } else {
12514            if (DEBUG_SD_INSTALL)
12515                Log.i(TAG, "Unloading packages");
12516            unloadMediaPackages(processCids, uidArr, reportStatus);
12517        }
12518    }
12519
12520   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12521           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12522        int size = pkgList.size();
12523        if (size > 0) {
12524            // Send broadcasts here
12525            Bundle extras = new Bundle();
12526            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12527                    .toArray(new String[size]));
12528            if (uidArr != null) {
12529                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12530            }
12531            if (replacing) {
12532                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12533            }
12534            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12535                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12536            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12537        }
12538    }
12539
12540   /*
12541     * Look at potentially valid container ids from processCids If package
12542     * information doesn't match the one on record or package scanning fails,
12543     * the cid is added to list of removeCids. We currently don't delete stale
12544     * containers.
12545     */
12546   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12547            HashSet<String> removeCids) {
12548        ArrayList<String> pkgList = new ArrayList<String>();
12549        Set<AsecInstallArgs> keys = processCids.keySet();
12550        boolean doGc = false;
12551        for (AsecInstallArgs args : keys) {
12552            String codePath = processCids.get(args);
12553            if (DEBUG_SD_INSTALL)
12554                Log.i(TAG, "Loading container : " + args.cid);
12555            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12556            try {
12557                // Make sure there are no container errors first.
12558                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12559                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12560                            + " when installing from sdcard");
12561                    continue;
12562                }
12563                // Check code path here.
12564                if (codePath == null || !codePath.equals(args.getCodePath())) {
12565                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12566                            + " does not match one in settings " + codePath);
12567                    continue;
12568                }
12569                // Parse package
12570                int parseFlags = mDefParseFlags;
12571                if (args.isExternal()) {
12572                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12573                }
12574                if (args.isFwdLocked()) {
12575                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12576                }
12577
12578                doGc = true;
12579                synchronized (mInstallLock) {
12580                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12581                            0, 0, null, null);
12582                    // Scan the package
12583                    if (pkg != null) {
12584                        /*
12585                         * TODO why is the lock being held? doPostInstall is
12586                         * called in other places without the lock. This needs
12587                         * to be straightened out.
12588                         */
12589                        // writer
12590                        synchronized (mPackages) {
12591                            retCode = PackageManager.INSTALL_SUCCEEDED;
12592                            pkgList.add(pkg.packageName);
12593                            // Post process args
12594                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12595                                    pkg.applicationInfo.uid);
12596                        }
12597                    } else {
12598                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12599                    }
12600                }
12601
12602            } finally {
12603                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12604                    // Don't destroy container here. Wait till gc clears things
12605                    // up.
12606                    removeCids.add(args.cid);
12607                }
12608            }
12609        }
12610        // writer
12611        synchronized (mPackages) {
12612            // If the platform SDK has changed since the last time we booted,
12613            // we need to re-grant app permission to catch any new ones that
12614            // appear. This is really a hack, and means that apps can in some
12615            // cases get permissions that the user didn't initially explicitly
12616            // allow... it would be nice to have some better way to handle
12617            // this situation.
12618            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12619            if (regrantPermissions)
12620                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12621                        + mSdkVersion + "; regranting permissions for external storage");
12622            mSettings.mExternalSdkPlatform = mSdkVersion;
12623
12624            // Make sure group IDs have been assigned, and any permission
12625            // changes in other apps are accounted for
12626            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12627                    | (regrantPermissions
12628                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12629                            : 0));
12630
12631            mSettings.updateExternalDatabaseVersion();
12632
12633            // can downgrade to reader
12634            // Persist settings
12635            mSettings.writeLPr();
12636        }
12637        // Send a broadcast to let everyone know we are done processing
12638        if (pkgList.size() > 0) {
12639            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12640        }
12641        // Force gc to avoid any stale parser references that we might have.
12642        if (doGc) {
12643            Runtime.getRuntime().gc();
12644        }
12645        // List stale containers and destroy stale temporary containers.
12646        if (removeCids != null) {
12647            for (String cid : removeCids) {
12648                if (cid.startsWith(mTempContainerPrefix)) {
12649                    Log.i(TAG, "Destroying stale temporary container " + cid);
12650                    PackageHelper.destroySdDir(cid);
12651                } else {
12652                    Log.w(TAG, "Container " + cid + " is stale");
12653               }
12654           }
12655        }
12656    }
12657
12658   /*
12659     * Utility method to unload a list of specified containers
12660     */
12661    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12662        // Just unmount all valid containers.
12663        for (AsecInstallArgs arg : cidArgs) {
12664            synchronized (mInstallLock) {
12665                arg.doPostDeleteLI(false);
12666           }
12667       }
12668   }
12669
12670    /*
12671     * Unload packages mounted on external media. This involves deleting package
12672     * data from internal structures, sending broadcasts about diabled packages,
12673     * gc'ing to free up references, unmounting all secure containers
12674     * corresponding to packages on external media, and posting a
12675     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12676     * that we always have to post this message if status has been requested no
12677     * matter what.
12678     */
12679    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12680            final boolean reportStatus) {
12681        if (DEBUG_SD_INSTALL)
12682            Log.i(TAG, "unloading media packages");
12683        ArrayList<String> pkgList = new ArrayList<String>();
12684        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12685        final Set<AsecInstallArgs> keys = processCids.keySet();
12686        for (AsecInstallArgs args : keys) {
12687            String pkgName = args.getPackageName();
12688            if (DEBUG_SD_INSTALL)
12689                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12690            // Delete package internally
12691            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12692            synchronized (mInstallLock) {
12693                boolean res = deletePackageLI(pkgName, null, false, null, null,
12694                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12695                if (res) {
12696                    pkgList.add(pkgName);
12697                } else {
12698                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12699                    failedList.add(args);
12700                }
12701            }
12702        }
12703
12704        // reader
12705        synchronized (mPackages) {
12706            // We didn't update the settings after removing each package;
12707            // write them now for all packages.
12708            mSettings.writeLPr();
12709        }
12710
12711        // We have to absolutely send UPDATED_MEDIA_STATUS only
12712        // after confirming that all the receivers processed the ordered
12713        // broadcast when packages get disabled, force a gc to clean things up.
12714        // and unload all the containers.
12715        if (pkgList.size() > 0) {
12716            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12717                    new IIntentReceiver.Stub() {
12718                public void performReceive(Intent intent, int resultCode, String data,
12719                        Bundle extras, boolean ordered, boolean sticky,
12720                        int sendingUser) throws RemoteException {
12721                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12722                            reportStatus ? 1 : 0, 1, keys);
12723                    mHandler.sendMessage(msg);
12724                }
12725            });
12726        } else {
12727            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12728                    keys);
12729            mHandler.sendMessage(msg);
12730        }
12731    }
12732
12733    /** Binder call */
12734    @Override
12735    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12736            final int flags) {
12737        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12738        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12739        int returnCode = PackageManager.MOVE_SUCCEEDED;
12740        int currFlags = 0;
12741        int newFlags = 0;
12742        // reader
12743        synchronized (mPackages) {
12744            PackageParser.Package pkg = mPackages.get(packageName);
12745            if (pkg == null) {
12746                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12747            } else {
12748                // Disable moving fwd locked apps and system packages
12749                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12750                    Slog.w(TAG, "Cannot move system application");
12751                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12752                } else if (pkg.mOperationPending) {
12753                    Slog.w(TAG, "Attempt to move package which has pending operations");
12754                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12755                } else {
12756                    // Find install location first
12757                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12758                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12759                        Slog.w(TAG, "Ambigous flags specified for move location.");
12760                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12761                    } else {
12762                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12763                                : PackageManager.INSTALL_INTERNAL;
12764                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12765                                : PackageManager.INSTALL_INTERNAL;
12766
12767                        if (newFlags == currFlags) {
12768                            Slog.w(TAG, "No move required. Trying to move to same location");
12769                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12770                        } else {
12771                            if (isForwardLocked(pkg)) {
12772                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12773                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12774                            }
12775                        }
12776                    }
12777                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12778                        pkg.mOperationPending = true;
12779                    }
12780                }
12781            }
12782
12783            /*
12784             * TODO this next block probably shouldn't be inside the lock. We
12785             * can't guarantee these won't change after this is fired off
12786             * anyway.
12787             */
12788            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12789                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12790                        null, -1, user),
12791                        returnCode);
12792            } else {
12793                Message msg = mHandler.obtainMessage(INIT_COPY);
12794                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12795                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12796                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12797                        instructionSet);
12798                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12799                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12800                msg.obj = mp;
12801                mHandler.sendMessage(msg);
12802            }
12803        }
12804    }
12805
12806    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12807        // Queue up an async operation since the package deletion may take a
12808        // little while.
12809        mHandler.post(new Runnable() {
12810            public void run() {
12811                // TODO fix this; this does nothing.
12812                mHandler.removeCallbacks(this);
12813                int returnCode = currentStatus;
12814                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12815                    int uidArr[] = null;
12816                    ArrayList<String> pkgList = null;
12817                    synchronized (mPackages) {
12818                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12819                        if (pkg == null) {
12820                            Slog.w(TAG, " Package " + mp.packageName
12821                                    + " doesn't exist. Aborting move");
12822                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12823                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12824                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12825                                    + mp.srcArgs.getCodePath() + " to "
12826                                    + pkg.applicationInfo.sourceDir
12827                                    + " Aborting move and returning error");
12828                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12829                        } else {
12830                            uidArr = new int[] {
12831                                pkg.applicationInfo.uid
12832                            };
12833                            pkgList = new ArrayList<String>();
12834                            pkgList.add(mp.packageName);
12835                        }
12836                    }
12837                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12838                        // Send resources unavailable broadcast
12839                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12840                        // Update package code and resource paths
12841                        synchronized (mInstallLock) {
12842                            synchronized (mPackages) {
12843                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12844                                // Recheck for package again.
12845                                if (pkg == null) {
12846                                    Slog.w(TAG, " Package " + mp.packageName
12847                                            + " doesn't exist. Aborting move");
12848                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12849                                } else if (!mp.srcArgs.getCodePath().equals(
12850                                        pkg.applicationInfo.sourceDir)) {
12851                                    Slog.w(TAG, "Package " + mp.packageName
12852                                            + " code path changed from " + mp.srcArgs.getCodePath()
12853                                            + " to " + pkg.applicationInfo.sourceDir
12854                                            + " Aborting move and returning error");
12855                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12856                                } else {
12857                                    final String oldCodePath = pkg.codePath;
12858                                    final String newCodePath = mp.targetArgs.getCodePath();
12859                                    final String newResPath = mp.targetArgs.getResourcePath();
12860                                    final String newNativePath = mp.targetArgs
12861                                            .getNativeLibraryPath();
12862
12863                                    final File newNativeDir = new File(newNativePath);
12864
12865                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12866                                        ApkHandle handle = null;
12867                                        try {
12868                                            handle = ApkHandle.create(newCodePath);
12869                                            final int abi = NativeLibraryHelper.findSupportedAbi(
12870                                                    handle, Build.SUPPORTED_ABIS);
12871                                            if (abi >= 0) {
12872                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12873                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12874                                            }
12875                                        } catch (IOException ioe) {
12876                                            Slog.w(TAG, "Unable to extract native libs for package :"
12877                                                    + mp.packageName, ioe);
12878                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12879                                        } finally {
12880                                            IoUtils.closeQuietly(handle);
12881                                        }
12882                                    }
12883                                    final int[] users = sUserManager.getUserIds();
12884                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12885                                        for (int user : users) {
12886                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12887                                                    newNativePath, user) < 0) {
12888                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12889                                            }
12890                                        }
12891                                    }
12892
12893                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12894                                        pkg.codePath = newCodePath;
12895                                        // Move dex files around
12896                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12897                                            // Moving of dex files failed. Set
12898                                            // error code and abort move.
12899                                            pkg.codePath = oldCodePath;
12900                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12901                                        }
12902                                    }
12903
12904                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12905                                        pkg.applicationInfo.sourceDir = newCodePath;
12906                                        pkg.applicationInfo.publicSourceDir = newResPath;
12907                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12908                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12909                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12910                                        ps.codePathString = ps.codePath.getPath();
12911                                        ps.resourcePath = new File(
12912                                                pkg.applicationInfo.publicSourceDir);
12913                                        ps.resourcePathString = ps.resourcePath.getPath();
12914                                        ps.nativeLibraryPathString = newNativePath;
12915                                        // Set the application info flag
12916                                        // correctly.
12917                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12918                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12919                                        } else {
12920                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12921                                        }
12922                                        ps.setFlags(pkg.applicationInfo.flags);
12923                                        mAppDirs.remove(oldCodePath);
12924                                        mAppDirs.put(newCodePath, pkg);
12925                                        // Persist settings
12926                                        mSettings.writeLPr();
12927                                    }
12928                                }
12929                            }
12930                        }
12931                        // Send resources available broadcast
12932                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12933                    }
12934                }
12935                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12936                    // Clean up failed installation
12937                    if (mp.targetArgs != null) {
12938                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12939                                -1);
12940                    }
12941                } else {
12942                    // Force a gc to clear things up.
12943                    Runtime.getRuntime().gc();
12944                    // Delete older code
12945                    synchronized (mInstallLock) {
12946                        mp.srcArgs.doPostDeleteLI(true);
12947                    }
12948                }
12949
12950                // Allow more operations on this file if we didn't fail because
12951                // an operation was already pending for this package.
12952                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12953                    synchronized (mPackages) {
12954                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12955                        if (pkg != null) {
12956                            pkg.mOperationPending = false;
12957                       }
12958                   }
12959                }
12960
12961                IPackageMoveObserver observer = mp.observer;
12962                if (observer != null) {
12963                    try {
12964                        observer.packageMoved(mp.packageName, returnCode);
12965                    } catch (RemoteException e) {
12966                        Log.i(TAG, "Observer no longer exists.");
12967                    }
12968                }
12969            }
12970        });
12971    }
12972
12973    @Override
12974    public boolean setInstallLocation(int loc) {
12975        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12976                null);
12977        if (getInstallLocation() == loc) {
12978            return true;
12979        }
12980        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12981                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12982            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12983                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12984            return true;
12985        }
12986        return false;
12987   }
12988
12989    @Override
12990    public int getInstallLocation() {
12991        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12992                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12993                PackageHelper.APP_INSTALL_AUTO);
12994    }
12995
12996    /** Called by UserManagerService */
12997    void cleanUpUserLILPw(int userHandle) {
12998        mDirtyUsers.remove(userHandle);
12999        mSettings.removeUserLPr(userHandle);
13000        mPendingBroadcasts.remove(userHandle);
13001        if (mInstaller != null) {
13002            // Technically, we shouldn't be doing this with the package lock
13003            // held.  However, this is very rare, and there is already so much
13004            // other disk I/O going on, that we'll let it slide for now.
13005            mInstaller.removeUserDataDirs(userHandle);
13006        }
13007        mUserNeedsBadging.delete(userHandle);
13008    }
13009
13010    /** Called by UserManagerService */
13011    void createNewUserLILPw(int userHandle, File path) {
13012        if (mInstaller != null) {
13013            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13014        }
13015    }
13016
13017    @Override
13018    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13019        mContext.enforceCallingOrSelfPermission(
13020                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13021                "Only package verification agents can read the verifier device identity");
13022
13023        synchronized (mPackages) {
13024            return mSettings.getVerifierDeviceIdentityLPw();
13025        }
13026    }
13027
13028    @Override
13029    public void setPermissionEnforced(String permission, boolean enforced) {
13030        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13031        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13032            synchronized (mPackages) {
13033                if (mSettings.mReadExternalStorageEnforced == null
13034                        || mSettings.mReadExternalStorageEnforced != enforced) {
13035                    mSettings.mReadExternalStorageEnforced = enforced;
13036                    mSettings.writeLPr();
13037                }
13038            }
13039            // kill any non-foreground processes so we restart them and
13040            // grant/revoke the GID.
13041            final IActivityManager am = ActivityManagerNative.getDefault();
13042            if (am != null) {
13043                final long token = Binder.clearCallingIdentity();
13044                try {
13045                    am.killProcessesBelowForeground("setPermissionEnforcement");
13046                } catch (RemoteException e) {
13047                } finally {
13048                    Binder.restoreCallingIdentity(token);
13049                }
13050            }
13051        } else {
13052            throw new IllegalArgumentException("No selective enforcement for " + permission);
13053        }
13054    }
13055
13056    @Override
13057    @Deprecated
13058    public boolean isPermissionEnforced(String permission) {
13059        return true;
13060    }
13061
13062    @Override
13063    public boolean isStorageLow() {
13064        final long token = Binder.clearCallingIdentity();
13065        try {
13066            final DeviceStorageMonitorInternal
13067                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13068            if (dsm != null) {
13069                return dsm.isMemoryLow();
13070            } else {
13071                return false;
13072            }
13073        } finally {
13074            Binder.restoreCallingIdentity(token);
13075        }
13076    }
13077
13078    @Override
13079    public IPackageInstaller getPackageInstaller() {
13080        return mInstallerService;
13081    }
13082
13083    private boolean userNeedsBadging(int userId) {
13084        int index = mUserNeedsBadging.indexOfKey(userId);
13085        if (index < 0) {
13086            final UserInfo userInfo;
13087            final long token = Binder.clearCallingIdentity();
13088            try {
13089                userInfo = sUserManager.getUserInfo(userId);
13090            } finally {
13091                Binder.restoreCallingIdentity(token);
13092            }
13093            final boolean b;
13094            if (userInfo != null && userInfo.isManagedProfile()) {
13095                b = true;
13096            } else {
13097                b = false;
13098            }
13099            mUserNeedsBadging.put(userId, b);
13100            return b;
13101        }
13102        return mUserNeedsBadging.valueAt(index);
13103    }
13104}
13105