PackageManagerService.java revision 625239a05401bbf18b04d9874cea3f82da7c29a1
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
25import static com.android.internal.util.ArrayUtils.appendInt;
26import static com.android.internal.util.ArrayUtils.removeInt;
27import static libcore.io.OsConstants.S_ISLNK;
28import static libcore.io.OsConstants.S_IRWXU;
29import static libcore.io.OsConstants.S_IRGRP;
30import static libcore.io.OsConstants.S_IXGRP;
31import static libcore.io.OsConstants.S_IROTH;
32import static libcore.io.OsConstants.S_IXOTH;
33
34import com.android.internal.app.IMediaContainerService;
35import com.android.internal.app.ResolverActivity;
36import com.android.internal.content.NativeLibraryHelper;
37import com.android.internal.content.PackageHelper;
38import com.android.internal.util.FastXmlSerializer;
39import com.android.internal.util.XmlUtils;
40import com.android.server.DeviceStorageMonitorService;
41import com.android.server.EventLogTags;
42import com.android.server.IntentResolver;
43
44import org.xmlpull.v1.XmlPullParser;
45import org.xmlpull.v1.XmlPullParserException;
46import org.xmlpull.v1.XmlSerializer;
47
48import android.app.ActivityManagerNative;
49import android.app.IActivityManager;
50import android.app.admin.IDevicePolicyManager;
51import android.app.backup.IBackupManager;
52import android.content.BroadcastReceiver;
53import android.content.ComponentName;
54import android.content.Context;
55import android.content.IIntentReceiver;
56import android.content.Intent;
57import android.content.IntentFilter;
58import android.content.IntentSender;
59import android.content.ServiceConnection;
60import android.content.IntentSender.SendIntentException;
61import android.content.pm.ActivityInfo;
62import android.content.pm.ApplicationInfo;
63import android.content.pm.ContainerEncryptionParams;
64import android.content.pm.FeatureInfo;
65import android.content.pm.IPackageDataObserver;
66import android.content.pm.IPackageDeleteObserver;
67import android.content.pm.IPackageInstallObserver;
68import android.content.pm.IPackageManager;
69import android.content.pm.IPackageMoveObserver;
70import android.content.pm.IPackageStatsObserver;
71import android.content.pm.InstrumentationInfo;
72import android.content.pm.PackageCleanItem;
73import android.content.pm.PackageInfo;
74import android.content.pm.PackageInfoLite;
75import android.content.pm.PackageManager;
76import android.content.pm.PackageParser;
77import android.content.pm.PackageUserState;
78import android.content.pm.PackageParser.ActivityIntentInfo;
79import android.content.pm.PackageStats;
80import android.content.pm.ParceledListSlice;
81import android.content.pm.PermissionGroupInfo;
82import android.content.pm.PermissionInfo;
83import android.content.pm.ProviderInfo;
84import android.content.pm.ResolveInfo;
85import android.content.pm.ServiceInfo;
86import android.content.pm.Signature;
87import android.content.pm.ManifestDigest;
88import android.content.pm.VerificationParams;
89import android.content.pm.VerifierDeviceIdentity;
90import android.content.pm.VerifierInfo;
91import android.net.Uri;
92import android.os.Binder;
93import android.os.Build;
94import android.os.Bundle;
95import android.os.Environment;
96import android.os.FileObserver;
97import android.os.FileUtils;
98import android.os.Handler;
99import android.os.HandlerThread;
100import android.os.IBinder;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
105import android.os.Process;
106import android.os.RemoteException;
107import android.os.SELinux;
108import android.os.ServiceManager;
109import android.os.SystemClock;
110import android.os.SystemProperties;
111import android.os.UserHandle;
112import android.os.Environment.UserEnvironment;
113import android.provider.Settings.Secure;
114import android.security.SystemKeyStore;
115import android.util.DisplayMetrics;
116import android.util.EventLog;
117import android.util.Log;
118import android.util.LogPrinter;
119import android.util.Slog;
120import android.util.SparseArray;
121import android.util.Xml;
122import android.view.Display;
123import android.view.WindowManager;
124
125import java.io.BufferedOutputStream;
126import java.io.File;
127import java.io.FileDescriptor;
128import java.io.FileInputStream;
129import java.io.FileNotFoundException;
130import java.io.FileOutputStream;
131import java.io.FileReader;
132import java.io.FilenameFilter;
133import java.io.IOException;
134import java.io.PrintWriter;
135import java.security.NoSuchAlgorithmException;
136import java.security.PublicKey;
137import java.security.cert.CertificateException;
138import java.text.SimpleDateFormat;
139import java.util.ArrayList;
140import java.util.Arrays;
141import java.util.Collection;
142import java.util.Collections;
143import java.util.Comparator;
144import java.util.Date;
145import java.util.HashMap;
146import java.util.HashSet;
147import java.util.Iterator;
148import java.util.List;
149import java.util.Map;
150import java.util.Map.Entry;
151import java.util.Set;
152
153import libcore.io.ErrnoException;
154import libcore.io.IoUtils;
155import libcore.io.Libcore;
156import libcore.io.OsConstants;
157import libcore.io.StructStat;
158
159/**
160 * Keep track of all those .apks everywhere.
161 *
162 * This is very central to the platform's security; please run the unit
163 * tests whenever making modifications here:
164 *
165mmm frameworks/base/tests/AndroidTests
166adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
167adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
168 *
169 * {@hide}
170 */
171public class PackageManagerService extends IPackageManager.Stub {
172    static final String TAG = "PackageManager";
173    static final boolean DEBUG_SETTINGS = false;
174    private static final boolean DEBUG_PREFERRED = false;
175    static final boolean DEBUG_UPGRADE = false;
176    private static final boolean DEBUG_INSTALL = false;
177    private static final boolean DEBUG_REMOVE = false;
178    private static final boolean DEBUG_BROADCASTS = false;
179    private static final boolean DEBUG_SHOW_INFO = false;
180    private static final boolean DEBUG_PACKAGE_INFO = false;
181    private static final boolean DEBUG_INTENT_MATCHING = false;
182    private static final boolean DEBUG_PACKAGE_SCANNING = false;
183    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
184    private static final boolean DEBUG_VERIFY = false;
185
186    private static final int RADIO_UID = Process.PHONE_UID;
187    private static final int LOG_UID = Process.LOG_UID;
188    private static final int NFC_UID = Process.NFC_UID;
189    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
190
191    private static final boolean GET_CERTIFICATES = true;
192
193    private static final int REMOVE_EVENTS =
194        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
195    private static final int ADD_EVENTS =
196        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
197
198    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
199    // Suffix used during package installation when copying/moving
200    // package apks to install directory.
201    private static final String INSTALL_PACKAGE_SUFFIX = "-";
202
203    static final int SCAN_MONITOR = 1<<0;
204    static final int SCAN_NO_DEX = 1<<1;
205    static final int SCAN_FORCE_DEX = 1<<2;
206    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
207    static final int SCAN_NEW_INSTALL = 1<<4;
208    static final int SCAN_NO_PATHS = 1<<5;
209    static final int SCAN_UPDATE_TIME = 1<<6;
210    static final int SCAN_DEFER_DEX = 1<<7;
211    static final int SCAN_BOOTING = 1<<8;
212
213    static final int REMOVE_CHATTY = 1<<16;
214
215    /**
216     * Whether verification is enabled by default.
217     */
218    private static final boolean DEFAULT_VERIFY_ENABLE = true;
219
220    /**
221     * The default maximum time to wait for the verification agent to return in
222     * milliseconds.
223     */
224    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
225
226    /**
227     * The default response for package verification timeout.
228     *
229     * This can be either PackageManager.VERIFICATION_ALLOW or
230     * PackageManager.VERIFICATION_REJECT.
231     */
232    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
233
234    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
235
236    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
237            DEFAULT_CONTAINER_PACKAGE,
238            "com.android.defcontainer.DefaultContainerService");
239
240    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
241
242    private static final String LIB_DIR_NAME = "lib";
243
244    static final String mTempContainerPrefix = "smdl2tmp";
245
246    final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
247            Process.THREAD_PRIORITY_BACKGROUND);
248    final PackageHandler mHandler;
249
250    final int mSdkVersion = Build.VERSION.SDK_INT;
251    final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
252            ? null : Build.VERSION.CODENAME;
253
254    final Context mContext;
255    final boolean mFactoryTest;
256    final boolean mOnlyCore;
257    final boolean mNoDexOpt;
258    final DisplayMetrics mMetrics;
259    final int mDefParseFlags;
260    final String[] mSeparateProcesses;
261
262    // This is where all application persistent data goes.
263    final File mAppDataDir;
264
265    // This is where all application persistent data goes for secondary users.
266    final File mUserAppDataDir;
267
268    /** The location for ASEC container files on internal storage. */
269    final String mAsecInternalPath;
270
271    // This is the object monitoring the framework dir.
272    final FileObserver mFrameworkInstallObserver;
273
274    // This is the object monitoring the system app dir.
275    final FileObserver mSystemInstallObserver;
276
277    // This is the object monitoring the system app dir.
278    final FileObserver mVendorInstallObserver;
279
280    // This is the object monitoring mAppInstallDir.
281    final FileObserver mAppInstallObserver;
282
283    // This is the object monitoring mDrmAppPrivateInstallDir.
284    final FileObserver mDrmAppInstallObserver;
285
286    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
287    // LOCK HELD.  Can be called with mInstallLock held.
288    final Installer mInstaller;
289
290    final File mFrameworkDir;
291    final File mSystemAppDir;
292    final File mVendorAppDir;
293    final File mAppInstallDir;
294    final File mDalvikCacheDir;
295
296    /**
297     * Directory to which applications installed internally have native
298     * libraries copied.
299     */
300    private File mAppLibInstallDir;
301
302    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
303    // apps.
304    final File mDrmAppPrivateInstallDir;
305
306    // ----------------------------------------------------------------
307
308    // Lock for state used when installing and doing other long running
309    // operations.  Methods that must be called with this lock held have
310    // the prefix "LI".
311    final Object mInstallLock = new Object();
312
313    // These are the directories in the 3rd party applications installed dir
314    // that we have currently loaded packages from.  Keys are the application's
315    // installed zip file (absolute codePath), and values are Package.
316    final HashMap<String, PackageParser.Package> mAppDirs =
317            new HashMap<String, PackageParser.Package>();
318
319    // Information for the parser to write more useful error messages.
320    File mScanningPath;
321    int mLastScanError;
322
323    // ----------------------------------------------------------------
324
325    // Keys are String (package name), values are Package.  This also serves
326    // as the lock for the global state.  Methods that must be called with
327    // this lock held have the prefix "LP".
328    final HashMap<String, PackageParser.Package> mPackages =
329            new HashMap<String, PackageParser.Package>();
330
331    final Settings mSettings;
332    boolean mRestoredSettings;
333
334    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
335    int[] mGlobalGids;
336
337    // These are the built-in uid -> permission mappings that were read from the
338    // etc/permissions.xml file.
339    final SparseArray<HashSet<String>> mSystemPermissions =
340            new SparseArray<HashSet<String>>();
341
342    // These are the built-in shared libraries that were read from the
343    // etc/permissions.xml file.
344    final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
345
346    // Temporary for building the final shared libraries for an .apk.
347    String[] mTmpSharedLibraries = null;
348
349    // These are the features this devices supports that were read from the
350    // etc/permissions.xml file.
351    final HashMap<String, FeatureInfo> mAvailableFeatures =
352            new HashMap<String, FeatureInfo>();
353
354    // All available activities, for your resolving pleasure.
355    final ActivityIntentResolver mActivities =
356            new ActivityIntentResolver();
357
358    // All available receivers, for your resolving pleasure.
359    final ActivityIntentResolver mReceivers =
360            new ActivityIntentResolver();
361
362    // All available services, for your resolving pleasure.
363    final ServiceIntentResolver mServices = new ServiceIntentResolver();
364
365    // Keys are String (provider class name), values are Provider.
366    final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
367            new HashMap<ComponentName, PackageParser.Provider>();
368
369    // Mapping from provider base names (first directory in content URI codePath)
370    // to the provider information.
371    final HashMap<String, PackageParser.Provider> mProviders =
372            new HashMap<String, PackageParser.Provider>();
373
374    // Mapping from instrumentation class names to info about them.
375    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
376            new HashMap<ComponentName, PackageParser.Instrumentation>();
377
378    // Mapping from permission names to info about them.
379    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
380            new HashMap<String, PackageParser.PermissionGroup>();
381
382    // Packages whose data we have transfered into another package, thus
383    // should no longer exist.
384    final HashSet<String> mTransferedPackages = new HashSet<String>();
385
386    // Broadcast actions that are only available to the system.
387    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
388
389    /** List of packages waiting for verification. */
390    final SparseArray<PackageVerificationState> mPendingVerification
391            = new SparseArray<PackageVerificationState>();
392
393    final ArrayList<PackageParser.Package> mDeferredDexOpt =
394            new ArrayList<PackageParser.Package>();
395
396    /** Token for keys in mPendingVerification. */
397    private int mPendingVerificationToken = 0;
398
399    boolean mSystemReady;
400    boolean mSafeMode;
401    boolean mHasSystemUidErrors;
402
403    ApplicationInfo mAndroidApplication;
404    final ActivityInfo mResolveActivity = new ActivityInfo();
405    final ResolveInfo mResolveInfo = new ResolveInfo();
406    ComponentName mResolveComponentName;
407    PackageParser.Package mPlatformPackage;
408
409    // Set of pending broadcasts for aggregating enable/disable of components.
410    final HashMap<String, ArrayList<String>> mPendingBroadcasts
411            = new HashMap<String, ArrayList<String>>();
412    // Service Connection to remote media container service to copy
413    // package uri's from external media onto secure containers
414    // or internal storage.
415    private IMediaContainerService mContainerService = null;
416
417    static final int SEND_PENDING_BROADCAST = 1;
418    static final int MCS_BOUND = 3;
419    static final int END_COPY = 4;
420    static final int INIT_COPY = 5;
421    static final int MCS_UNBIND = 6;
422    static final int START_CLEANING_PACKAGE = 7;
423    static final int FIND_INSTALL_LOC = 8;
424    static final int POST_INSTALL = 9;
425    static final int MCS_RECONNECT = 10;
426    static final int MCS_GIVE_UP = 11;
427    static final int UPDATED_MEDIA_STATUS = 12;
428    static final int WRITE_SETTINGS = 13;
429    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
430    static final int PACKAGE_VERIFIED = 15;
431    static final int CHECK_PENDING_VERIFICATION = 16;
432
433    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
434
435    // Delay time in millisecs
436    static final int BROADCAST_DELAY = 10 * 1000;
437
438    static UserManagerService sUserManager;
439
440    // Stores a list of users whose package restrictions file needs to be updated
441    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
442
443    final private DefaultContainerConnection mDefContainerConn =
444            new DefaultContainerConnection();
445    class DefaultContainerConnection implements ServiceConnection {
446        public void onServiceConnected(ComponentName name, IBinder service) {
447            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
448            IMediaContainerService imcs =
449                IMediaContainerService.Stub.asInterface(service);
450            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
451        }
452
453        public void onServiceDisconnected(ComponentName name) {
454            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
455        }
456    };
457
458    // Recordkeeping of restore-after-install operations that are currently in flight
459    // between the Package Manager and the Backup Manager
460    class PostInstallData {
461        public InstallArgs args;
462        public PackageInstalledInfo res;
463
464        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
465            args = _a;
466            res = _r;
467        }
468    };
469    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
470    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
471
472    private final String mRequiredVerifierPackage;
473
474    class PackageHandler extends Handler {
475        private boolean mBound = false;
476        final ArrayList<HandlerParams> mPendingInstalls =
477            new ArrayList<HandlerParams>();
478
479        private boolean connectToService() {
480            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
481                    " DefaultContainerService");
482            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
483            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
484            if (mContext.bindService(service, mDefContainerConn,
485                    Context.BIND_AUTO_CREATE, UserHandle.USER_OWNER)) {
486                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
487                mBound = true;
488                return true;
489            }
490            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
491            return false;
492        }
493
494        private void disconnectService() {
495            mContainerService = null;
496            mBound = false;
497            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
498            mContext.unbindService(mDefContainerConn);
499            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
500        }
501
502        PackageHandler(Looper looper) {
503            super(looper);
504        }
505
506        public void handleMessage(Message msg) {
507            try {
508                doHandleMessage(msg);
509            } finally {
510                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
511            }
512        }
513
514        void doHandleMessage(Message msg) {
515            switch (msg.what) {
516                case INIT_COPY: {
517                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy");
518                    HandlerParams params = (HandlerParams) msg.obj;
519                    int idx = mPendingInstalls.size();
520                    if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx);
521                    // If a bind was already initiated we dont really
522                    // need to do anything. The pending install
523                    // will be processed later on.
524                    if (!mBound) {
525                        // If this is the only one pending we might
526                        // have to bind to the service again.
527                        if (!connectToService()) {
528                            Slog.e(TAG, "Failed to bind to media container service");
529                            params.serviceError();
530                            return;
531                        } else {
532                            // Once we bind to the service, the first
533                            // pending request will be processed.
534                            mPendingInstalls.add(idx, params);
535                        }
536                    } else {
537                        mPendingInstalls.add(idx, params);
538                        // Already bound to the service. Just make
539                        // sure we trigger off processing the first request.
540                        if (idx == 0) {
541                            mHandler.sendEmptyMessage(MCS_BOUND);
542                        }
543                    }
544                    break;
545                }
546                case MCS_BOUND: {
547                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
548                    if (msg.obj != null) {
549                        mContainerService = (IMediaContainerService) msg.obj;
550                    }
551                    if (mContainerService == null) {
552                        // Something seriously wrong. Bail out
553                        Slog.e(TAG, "Cannot bind to media container service");
554                        for (HandlerParams params : mPendingInstalls) {
555                            // Indicate service bind error
556                            params.serviceError();
557                        }
558                        mPendingInstalls.clear();
559                    } else if (mPendingInstalls.size() > 0) {
560                        HandlerParams params = mPendingInstalls.get(0);
561                        if (params != null) {
562                            if (params.startCopy()) {
563                                // We are done...  look for more work or to
564                                // go idle.
565                                if (DEBUG_SD_INSTALL) Log.i(TAG,
566                                        "Checking for more work or unbind...");
567                                // Delete pending install
568                                if (mPendingInstalls.size() > 0) {
569                                    mPendingInstalls.remove(0);
570                                }
571                                if (mPendingInstalls.size() == 0) {
572                                    if (mBound) {
573                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
574                                                "Posting delayed MCS_UNBIND");
575                                        removeMessages(MCS_UNBIND);
576                                        Message ubmsg = obtainMessage(MCS_UNBIND);
577                                        // Unbind after a little delay, to avoid
578                                        // continual thrashing.
579                                        sendMessageDelayed(ubmsg, 10000);
580                                    }
581                                } else {
582                                    // There are more pending requests in queue.
583                                    // Just post MCS_BOUND message to trigger processing
584                                    // of next pending install.
585                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
586                                            "Posting MCS_BOUND for next woek");
587                                    mHandler.sendEmptyMessage(MCS_BOUND);
588                                }
589                            }
590                        }
591                    } else {
592                        // Should never happen ideally.
593                        Slog.w(TAG, "Empty queue");
594                    }
595                    break;
596                }
597                case MCS_RECONNECT: {
598                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
599                    if (mPendingInstalls.size() > 0) {
600                        if (mBound) {
601                            disconnectService();
602                        }
603                        if (!connectToService()) {
604                            Slog.e(TAG, "Failed to bind to media container service");
605                            for (HandlerParams params : mPendingInstalls) {
606                                // Indicate service bind error
607                                params.serviceError();
608                            }
609                            mPendingInstalls.clear();
610                        }
611                    }
612                    break;
613                }
614                case MCS_UNBIND: {
615                    // If there is no actual work left, then time to unbind.
616                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
617
618                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
619                        if (mBound) {
620                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
621
622                            disconnectService();
623                        }
624                    } else if (mPendingInstalls.size() > 0) {
625                        // There are more pending requests in queue.
626                        // Just post MCS_BOUND message to trigger processing
627                        // of next pending install.
628                        mHandler.sendEmptyMessage(MCS_BOUND);
629                    }
630
631                    break;
632                }
633                case MCS_GIVE_UP: {
634                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
635                    mPendingInstalls.remove(0);
636                    break;
637                }
638                case SEND_PENDING_BROADCAST: {
639                    String packages[];
640                    ArrayList<String> components[];
641                    int size = 0;
642                    int uids[];
643                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
644                    synchronized (mPackages) {
645                        if (mPendingBroadcasts == null) {
646                            return;
647                        }
648                        size = mPendingBroadcasts.size();
649                        if (size <= 0) {
650                            // Nothing to be done. Just return
651                            return;
652                        }
653                        packages = new String[size];
654                        components = new ArrayList[size];
655                        uids = new int[size];
656                        Iterator<Map.Entry<String, ArrayList<String>>>
657                                it = mPendingBroadcasts.entrySet().iterator();
658                        int i = 0;
659                        while (it.hasNext() && i < size) {
660                            Map.Entry<String, ArrayList<String>> ent = it.next();
661                            packages[i] = ent.getKey();
662                            components[i] = ent.getValue();
663                            PackageSetting ps = mSettings.mPackages.get(ent.getKey());
664                            uids[i] = (ps != null) ? ps.appId : -1;
665                            i++;
666                        }
667                        size = i;
668                        mPendingBroadcasts.clear();
669                    }
670                    // Send broadcasts
671                    for (int i = 0; i < size; i++) {
672                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
673                    }
674                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
675                    break;
676                }
677                case START_CLEANING_PACKAGE: {
678                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
679                    final String packageName = (String)msg.obj;
680                    final int userId = msg.arg1;
681                    final boolean andCode = msg.arg2 != 0;
682                    synchronized (mPackages) {
683                        if (userId == UserHandle.USER_ALL) {
684                            int[] users = sUserManager.getUserIds();
685                            for (int user : users) {
686                                mSettings.addPackageToCleanLPw(
687                                        new PackageCleanItem(user, packageName, andCode));
688                            }
689                        } else {
690                            mSettings.addPackageToCleanLPw(
691                                    new PackageCleanItem(userId, packageName, andCode));
692                        }
693                    }
694                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
695                    startCleaningPackages();
696                } break;
697                case POST_INSTALL: {
698                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
699                    PostInstallData data = mRunningInstalls.get(msg.arg1);
700                    mRunningInstalls.delete(msg.arg1);
701                    boolean deleteOld = false;
702
703                    if (data != null) {
704                        InstallArgs args = data.args;
705                        PackageInstalledInfo res = data.res;
706
707                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
708                            res.removedInfo.sendBroadcast(false, true, false);
709                            Bundle extras = new Bundle(1);
710                            extras.putInt(Intent.EXTRA_UID, res.uid);
711                            // Determine the set of users who are adding this
712                            // package for the first time vs. those who are seeing
713                            // an update.
714                            int[] firstUsers;
715                            int[] updateUsers = new int[0];
716                            if (res.origUsers == null || res.origUsers.length == 0) {
717                                firstUsers = res.newUsers;
718                            } else {
719                                firstUsers = new int[0];
720                                for (int i=0; i<res.newUsers.length; i++) {
721                                    int user = res.newUsers[i];
722                                    boolean isNew = true;
723                                    for (int j=0; j<res.origUsers.length; j++) {
724                                        if (res.origUsers[j] == user) {
725                                            isNew = false;
726                                            break;
727                                        }
728                                    }
729                                    if (isNew) {
730                                        int[] newFirst = new int[firstUsers.length+1];
731                                        System.arraycopy(firstUsers, 0, newFirst, 0,
732                                                firstUsers.length);
733                                        newFirst[firstUsers.length] = user;
734                                        firstUsers = newFirst;
735                                    } else {
736                                        int[] newUpdate = new int[updateUsers.length+1];
737                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
738                                                updateUsers.length);
739                                        newUpdate[updateUsers.length] = user;
740                                        updateUsers = newUpdate;
741                                    }
742                                }
743                            }
744                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
745                                    res.pkg.applicationInfo.packageName,
746                                    extras, null, null, firstUsers);
747                            final boolean update = res.removedInfo.removedPackage != null;
748                            if (update) {
749                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
750                            }
751                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
752                                    res.pkg.applicationInfo.packageName,
753                                    extras, null, null, updateUsers);
754                            if (update) {
755                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
756                                        res.pkg.applicationInfo.packageName,
757                                        extras, null, null, updateUsers);
758                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
759                                        null, null,
760                                        res.pkg.applicationInfo.packageName, null, updateUsers);
761                            }
762                            if (res.removedInfo.args != null) {
763                                // Remove the replaced package's older resources safely now
764                                deleteOld = true;
765                            }
766
767                            // Log current value of "unknown sources" setting
768                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
769                                getUnknownSourcesSettings());
770                        }
771                        // Force a gc to clear up things
772                        Runtime.getRuntime().gc();
773                        // We delete after a gc for applications  on sdcard.
774                        if (deleteOld) {
775                            synchronized (mInstallLock) {
776                                res.removedInfo.args.doPostDeleteLI(true);
777                            }
778                        }
779                        if (args.observer != null) {
780                            try {
781                                args.observer.packageInstalled(res.name, res.returnCode);
782                            } catch (RemoteException e) {
783                                Slog.i(TAG, "Observer no longer exists.");
784                            }
785                        }
786                    } else {
787                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
788                    }
789                } break;
790                case UPDATED_MEDIA_STATUS: {
791                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
792                    boolean reportStatus = msg.arg1 == 1;
793                    boolean doGc = msg.arg2 == 1;
794                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
795                    if (doGc) {
796                        // Force a gc to clear up stale containers.
797                        Runtime.getRuntime().gc();
798                    }
799                    if (msg.obj != null) {
800                        @SuppressWarnings("unchecked")
801                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
802                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
803                        // Unload containers
804                        unloadAllContainers(args);
805                    }
806                    if (reportStatus) {
807                        try {
808                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
809                            PackageHelper.getMountService().finishMediaUpdate();
810                        } catch (RemoteException e) {
811                            Log.e(TAG, "MountService not running?");
812                        }
813                    }
814                } break;
815                case WRITE_SETTINGS: {
816                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
817                    synchronized (mPackages) {
818                        removeMessages(WRITE_SETTINGS);
819                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
820                        mSettings.writeLPr();
821                        mDirtyUsers.clear();
822                    }
823                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
824                } break;
825                case WRITE_PACKAGE_RESTRICTIONS: {
826                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
827                    synchronized (mPackages) {
828                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
829                        for (int userId : mDirtyUsers) {
830                            mSettings.writePackageRestrictionsLPr(userId);
831                        }
832                        mDirtyUsers.clear();
833                    }
834                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
835                } break;
836                case CHECK_PENDING_VERIFICATION: {
837                    final int verificationId = msg.arg1;
838                    final PackageVerificationState state = mPendingVerification.get(verificationId);
839
840                    if ((state != null) && !state.timeoutExtended()) {
841                        final InstallArgs args = state.getInstallArgs();
842                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
843                        mPendingVerification.remove(verificationId);
844
845                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
846
847                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
848                            Slog.i(TAG, "Continuing with installation of "
849                                    + args.packageURI.toString());
850                            state.setVerifierResponse(Binder.getCallingUid(),
851                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
852                            broadcastPackageVerified(verificationId, args.packageURI,
853                                    PackageManager.VERIFICATION_ALLOW);
854                            try {
855                                ret = args.copyApk(mContainerService, true);
856                            } catch (RemoteException e) {
857                                Slog.e(TAG, "Could not contact the ContainerService");
858                            }
859                        } else {
860                            broadcastPackageVerified(verificationId, args.packageURI,
861                                    PackageManager.VERIFICATION_REJECT);
862                        }
863
864                        processPendingInstall(args, ret);
865                        mHandler.sendEmptyMessage(MCS_UNBIND);
866                    }
867                    break;
868                }
869                case PACKAGE_VERIFIED: {
870                    final int verificationId = msg.arg1;
871
872                    final PackageVerificationState state = mPendingVerification.get(verificationId);
873                    if (state == null) {
874                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
875                        break;
876                    }
877
878                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
879
880                    state.setVerifierResponse(response.callerUid, response.code);
881
882                    if (state.isVerificationComplete()) {
883                        mPendingVerification.remove(verificationId);
884
885                        final InstallArgs args = state.getInstallArgs();
886
887                        int ret;
888                        if (state.isInstallAllowed()) {
889                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
890                            broadcastPackageVerified(verificationId, args.packageURI,
891                                    response.code);
892                            try {
893                                ret = args.copyApk(mContainerService, true);
894                            } catch (RemoteException e) {
895                                Slog.e(TAG, "Could not contact the ContainerService");
896                            }
897                        } else {
898                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
899                        }
900
901                        processPendingInstall(args, ret);
902
903                        mHandler.sendEmptyMessage(MCS_UNBIND);
904                    }
905
906                    break;
907                }
908            }
909        }
910    }
911
912    void scheduleWriteSettingsLocked() {
913        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
914            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
915        }
916    }
917
918    void scheduleWritePackageRestrictionsLocked(int userId) {
919        if (!sUserManager.exists(userId)) return;
920        mDirtyUsers.add(userId);
921        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
922            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
923        }
924    }
925
926    public static final IPackageManager main(Context context, Installer installer,
927            boolean factoryTest, boolean onlyCore) {
928        PackageManagerService m = new PackageManagerService(context, installer,
929                factoryTest, onlyCore);
930        ServiceManager.addService("package", m);
931        return m;
932    }
933
934    static String[] splitString(String str, char sep) {
935        int count = 1;
936        int i = 0;
937        while ((i=str.indexOf(sep, i)) >= 0) {
938            count++;
939            i++;
940        }
941
942        String[] res = new String[count];
943        i=0;
944        count = 0;
945        int lastI=0;
946        while ((i=str.indexOf(sep, i)) >= 0) {
947            res[count] = str.substring(lastI, i);
948            count++;
949            i++;
950            lastI = i;
951        }
952        res[count] = str.substring(lastI, str.length());
953        return res;
954    }
955
956    public PackageManagerService(Context context, Installer installer,
957            boolean factoryTest, boolean onlyCore) {
958        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
959                SystemClock.uptimeMillis());
960
961        if (mSdkVersion <= 0) {
962            Slog.w(TAG, "**** ro.build.version.sdk not set!");
963        }
964
965        mContext = context;
966        mFactoryTest = factoryTest;
967        mOnlyCore = onlyCore;
968        mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
969        mMetrics = new DisplayMetrics();
970        mSettings = new Settings(context);
971        mSettings.addSharedUserLPw("android.uid.system",
972                Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
973        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
974        mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
975        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
976        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
977
978        String separateProcesses = SystemProperties.get("debug.separate_processes");
979        if (separateProcesses != null && separateProcesses.length() > 0) {
980            if ("*".equals(separateProcesses)) {
981                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
982                mSeparateProcesses = null;
983                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
984            } else {
985                mDefParseFlags = 0;
986                mSeparateProcesses = separateProcesses.split(",");
987                Slog.w(TAG, "Running with debug.separate_processes: "
988                        + separateProcesses);
989            }
990        } else {
991            mDefParseFlags = 0;
992            mSeparateProcesses = null;
993        }
994
995        mInstaller = installer;
996
997        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
998        Display d = wm.getDefaultDisplay();
999        d.getMetrics(mMetrics);
1000
1001        synchronized (mInstallLock) {
1002        // writer
1003        synchronized (mPackages) {
1004            mHandlerThread.start();
1005            mHandler = new PackageHandler(mHandlerThread.getLooper());
1006
1007            File dataDir = Environment.getDataDirectory();
1008            mAppDataDir = new File(dataDir, "data");
1009            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1010            mUserAppDataDir = new File(dataDir, "user");
1011            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1012
1013            sUserManager = new UserManagerService(context, this,
1014                    mInstallLock, mPackages);
1015
1016            readPermissions();
1017
1018            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1019            long startTime = SystemClock.uptimeMillis();
1020
1021            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1022                    startTime);
1023
1024            // Set flag to monitor and not change apk file paths when
1025            // scanning install directories.
1026            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1027            if (mNoDexOpt) {
1028                Slog.w(TAG, "Running ENG build: no pre-dexopt!");
1029                scanMode |= SCAN_NO_DEX;
1030            }
1031
1032            final HashSet<String> libFiles = new HashSet<String>();
1033
1034            mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
1035            mDalvikCacheDir = new File(dataDir, "dalvik-cache");
1036
1037            boolean didDexOpt = false;
1038
1039            /**
1040             * Out of paranoia, ensure that everything in the boot class
1041             * path has been dexed.
1042             */
1043            String bootClassPath = System.getProperty("java.boot.class.path");
1044            if (bootClassPath != null) {
1045                String[] paths = splitString(bootClassPath, ':');
1046                for (int i=0; i<paths.length; i++) {
1047                    try {
1048                        if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
1049                            libFiles.add(paths[i]);
1050                            mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
1051                            didDexOpt = true;
1052                        }
1053                    } catch (FileNotFoundException e) {
1054                        Slog.w(TAG, "Boot class path not found: " + paths[i]);
1055                    } catch (IOException e) {
1056                        Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
1057                                + e.getMessage());
1058                    }
1059                }
1060            } else {
1061                Slog.w(TAG, "No BOOTCLASSPATH found!");
1062            }
1063
1064            /**
1065             * Also ensure all external libraries have had dexopt run on them.
1066             */
1067            if (mSharedLibraries.size() > 0) {
1068                Iterator<String> libs = mSharedLibraries.values().iterator();
1069                while (libs.hasNext()) {
1070                    String lib = libs.next();
1071                    try {
1072                        if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
1073                            libFiles.add(lib);
1074                            mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
1075                            didDexOpt = true;
1076                        }
1077                    } catch (FileNotFoundException e) {
1078                        Slog.w(TAG, "Library not found: " + lib);
1079                    } catch (IOException e) {
1080                        Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1081                                + e.getMessage());
1082                    }
1083                }
1084            }
1085
1086            // Gross hack for now: we know this file doesn't contain any
1087            // code, so don't dexopt it to avoid the resulting log spew.
1088            libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
1089
1090            /**
1091             * And there are a number of commands implemented in Java, which
1092             * we currently need to do the dexopt on so that they can be
1093             * run from a non-root shell.
1094             */
1095            String[] frameworkFiles = mFrameworkDir.list();
1096            if (frameworkFiles != null) {
1097                for (int i=0; i<frameworkFiles.length; i++) {
1098                    File libPath = new File(mFrameworkDir, frameworkFiles[i]);
1099                    String path = libPath.getPath();
1100                    // Skip the file if we alrady did it.
1101                    if (libFiles.contains(path)) {
1102                        continue;
1103                    }
1104                    // Skip the file if it is not a type we want to dexopt.
1105                    if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1106                        continue;
1107                    }
1108                    try {
1109                        if (dalvik.system.DexFile.isDexOptNeeded(path)) {
1110                            mInstaller.dexopt(path, Process.SYSTEM_UID, true);
1111                            didDexOpt = true;
1112                        }
1113                    } catch (FileNotFoundException e) {
1114                        Slog.w(TAG, "Jar not found: " + path);
1115                    } catch (IOException e) {
1116                        Slog.w(TAG, "Exception reading jar: " + path, e);
1117                    }
1118                }
1119            }
1120
1121            if (didDexOpt) {
1122                // If we had to do a dexopt of one of the previous
1123                // things, then something on the system has changed.
1124                // Consider this significant, and wipe away all other
1125                // existing dexopt files to ensure we don't leave any
1126                // dangling around.
1127                String[] files = mDalvikCacheDir.list();
1128                if (files != null) {
1129                    for (int i=0; i<files.length; i++) {
1130                        String fn = files[i];
1131                        if (fn.startsWith("data@app@")
1132                                || fn.startsWith("data@app-private@")) {
1133                            Slog.i(TAG, "Pruning dalvik file: " + fn);
1134                            (new File(mDalvikCacheDir, fn)).delete();
1135                        }
1136                    }
1137                }
1138            }
1139
1140            // Find base frameworks (resource packages without code).
1141            mFrameworkInstallObserver = new AppDirObserver(
1142                mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
1143            mFrameworkInstallObserver.startWatching();
1144            scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
1145                    | PackageParser.PARSE_IS_SYSTEM_DIR,
1146                    scanMode | SCAN_NO_DEX, 0);
1147
1148            // Collect all system packages.
1149            mSystemAppDir = new File(Environment.getRootDirectory(), "app");
1150            mSystemInstallObserver = new AppDirObserver(
1151                mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
1152            mSystemInstallObserver.startWatching();
1153            scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
1154                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1155
1156            // Collect all vendor packages.
1157            mVendorAppDir = new File("/vendor/app");
1158            mVendorInstallObserver = new AppDirObserver(
1159                mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
1160            mVendorInstallObserver.startWatching();
1161            scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
1162                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1163
1164            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1165            mInstaller.moveFiles();
1166
1167            // Prune any system packages that no longer exist.
1168            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1169            if (!mOnlyCore) {
1170                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1171                while (psit.hasNext()) {
1172                    PackageSetting ps = psit.next();
1173
1174                    /*
1175                     * If this is not a system app, it can't be a
1176                     * disable system app.
1177                     */
1178                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1179                        continue;
1180                    }
1181
1182                    /*
1183                     * If the package is scanned, it's not erased.
1184                     */
1185                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1186                    if (scannedPkg != null) {
1187                        /*
1188                         * If the system app is both scanned and in the
1189                         * disabled packages list, then it must have been
1190                         * added via OTA. Remove it from the currently
1191                         * scanned package so the previously user-installed
1192                         * application can be scanned.
1193                         */
1194                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1195                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1196                                    + "; removing system app");
1197                            removePackageLI(ps, true);
1198                        }
1199
1200                        continue;
1201                    }
1202
1203                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1204                        psit.remove();
1205                        String msg = "System package " + ps.name
1206                                + " no longer exists; wiping its data";
1207                        reportSettingsProblem(Log.WARN, msg);
1208                        removeDataDirsLI(ps.name);
1209                    } else {
1210                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1211                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1212                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1213                        }
1214                    }
1215                }
1216            }
1217
1218            mAppInstallDir = new File(dataDir, "app");
1219            mAppLibInstallDir = new File(dataDir, "app-lib");
1220            //look for any incomplete package installations
1221            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1222            //clean up list
1223            for(int i = 0; i < deletePkgsList.size(); i++) {
1224                //clean up here
1225                cleanupInstallFailedPackage(deletePkgsList.get(i));
1226            }
1227            //delete tmp files
1228            deleteTempPackageFiles();
1229
1230            if (!mOnlyCore) {
1231                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1232                        SystemClock.uptimeMillis());
1233                mAppInstallObserver = new AppDirObserver(
1234                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
1235                mAppInstallObserver.startWatching();
1236                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1237
1238                mDrmAppInstallObserver = new AppDirObserver(
1239                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
1240                mDrmAppInstallObserver.startWatching();
1241                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1242                        scanMode, 0);
1243
1244                /**
1245                 * Remove disable package settings for any updated system
1246                 * apps that were removed via an OTA. If they're not a
1247                 * previously-updated app, remove them completely.
1248                 * Otherwise, just revoke their system-level permissions.
1249                 */
1250                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1251                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1252                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1253
1254                    String msg;
1255                    if (deletedPkg == null) {
1256                        msg = "Updated system package " + deletedAppName
1257                                + " no longer exists; wiping its data";
1258                        removeDataDirsLI(deletedAppName);
1259                    } else {
1260                        msg = "Updated system app + " + deletedAppName
1261                                + " no longer present; removing system privileges for "
1262                                + deletedAppName;
1263
1264                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1265
1266                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1267                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1268                    }
1269                    reportSettingsProblem(Log.WARN, msg);
1270                }
1271            } else {
1272                mAppInstallObserver = null;
1273                mDrmAppInstallObserver = null;
1274            }
1275
1276            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1277                    SystemClock.uptimeMillis());
1278            Slog.i(TAG, "Time to scan packages: "
1279                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1280                    + " seconds");
1281
1282            // If the platform SDK has changed since the last time we booted,
1283            // we need to re-grant app permission to catch any new ones that
1284            // appear.  This is really a hack, and means that apps can in some
1285            // cases get permissions that the user didn't initially explicitly
1286            // allow...  it would be nice to have some better way to handle
1287            // this situation.
1288            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1289                    != mSdkVersion;
1290            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1291                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1292                    + "; regranting permissions for internal storage");
1293            mSettings.mInternalSdkPlatform = mSdkVersion;
1294
1295            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1296                    | (regrantPermissions
1297                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1298                            : 0));
1299
1300            // Verify that all of the preferred activity components actually
1301            // exist.  It is possible for applications to be updated and at
1302            // that point remove a previously declared activity component that
1303            // had been set as a preferred activity.  We try to clean this up
1304            // the next time we encounter that preferred activity, but it is
1305            // possible for the user flow to never be able to return to that
1306            // situation so here we do a sanity check to make sure we haven't
1307            // left any junk around.
1308            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
1309            for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
1310                if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
1311                    removed.add(pa);
1312                }
1313            }
1314            for (int i=0; i<removed.size(); i++) {
1315                PreferredActivity pa = removed.get(i);
1316                Slog.w(TAG, "Removing dangling preferred activity: "
1317                        + pa.mPref.mComponent);
1318                mSettings.mPreferredActivities.removeFilter(pa);
1319            }
1320
1321            // can downgrade to reader
1322            mSettings.writeLPr();
1323
1324            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1325                    SystemClock.uptimeMillis());
1326
1327            // Now after opening every single application zip, make sure they
1328            // are all flushed.  Not really needed, but keeps things nice and
1329            // tidy.
1330            Runtime.getRuntime().gc();
1331
1332            mRequiredVerifierPackage = getRequiredVerifierLPr();
1333        } // synchronized (mPackages)
1334        } // synchronized (mInstallLock)
1335    }
1336
1337    public boolean isFirstBoot() {
1338        return !mRestoredSettings;
1339    }
1340
1341    private String getRequiredVerifierLPr() {
1342        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1343        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1344                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1345
1346        String requiredVerifier = null;
1347
1348        final int N = receivers.size();
1349        for (int i = 0; i < N; i++) {
1350            final ResolveInfo info = receivers.get(i);
1351
1352            if (info.activityInfo == null) {
1353                continue;
1354            }
1355
1356            final String packageName = info.activityInfo.packageName;
1357
1358            final PackageSetting ps = mSettings.mPackages.get(packageName);
1359            if (ps == null) {
1360                continue;
1361            }
1362
1363            if (!ps.grantedPermissions
1364                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1365                continue;
1366            }
1367
1368            if (requiredVerifier != null) {
1369                throw new RuntimeException("There can be only one required verifier");
1370            }
1371
1372            requiredVerifier = packageName;
1373        }
1374
1375        return requiredVerifier;
1376    }
1377
1378    @Override
1379    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1380            throws RemoteException {
1381        try {
1382            return super.onTransact(code, data, reply, flags);
1383        } catch (RuntimeException e) {
1384            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1385                Slog.e(TAG, "Package Manager Crash", e);
1386            }
1387            throw e;
1388        }
1389    }
1390
1391    void cleanupInstallFailedPackage(PackageSetting ps) {
1392        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1393        removeDataDirsLI(ps.name);
1394        if (ps.codePath != null) {
1395            if (!ps.codePath.delete()) {
1396                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1397            }
1398        }
1399        if (ps.resourcePath != null) {
1400            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1401                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1402            }
1403        }
1404        mSettings.removePackageLPw(ps.name);
1405    }
1406
1407    void readPermissions() {
1408        // Read permissions from .../etc/permission directory.
1409        File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1410        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1411            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1412            return;
1413        }
1414        if (!libraryDir.canRead()) {
1415            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1416            return;
1417        }
1418
1419        // Iterate over the files in the directory and scan .xml files
1420        for (File f : libraryDir.listFiles()) {
1421            // We'll read platform.xml last
1422            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1423                continue;
1424            }
1425
1426            if (!f.getPath().endsWith(".xml")) {
1427                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1428                continue;
1429            }
1430            if (!f.canRead()) {
1431                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1432                continue;
1433            }
1434
1435            readPermissionsFromXml(f);
1436        }
1437
1438        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1439        final File permFile = new File(Environment.getRootDirectory(),
1440                "etc/permissions/platform.xml");
1441        readPermissionsFromXml(permFile);
1442    }
1443
1444    private void readPermissionsFromXml(File permFile) {
1445        FileReader permReader = null;
1446        try {
1447            permReader = new FileReader(permFile);
1448        } catch (FileNotFoundException e) {
1449            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1450            return;
1451        }
1452
1453        try {
1454            XmlPullParser parser = Xml.newPullParser();
1455            parser.setInput(permReader);
1456
1457            XmlUtils.beginDocument(parser, "permissions");
1458
1459            while (true) {
1460                XmlUtils.nextElement(parser);
1461                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1462                    break;
1463                }
1464
1465                String name = parser.getName();
1466                if ("group".equals(name)) {
1467                    String gidStr = parser.getAttributeValue(null, "gid");
1468                    if (gidStr != null) {
1469                        int gid = Integer.parseInt(gidStr);
1470                        mGlobalGids = appendInt(mGlobalGids, gid);
1471                    } else {
1472                        Slog.w(TAG, "<group> without gid at "
1473                                + parser.getPositionDescription());
1474                    }
1475
1476                    XmlUtils.skipCurrentTag(parser);
1477                    continue;
1478                } else if ("permission".equals(name)) {
1479                    String perm = parser.getAttributeValue(null, "name");
1480                    if (perm == null) {
1481                        Slog.w(TAG, "<permission> without name at "
1482                                + parser.getPositionDescription());
1483                        XmlUtils.skipCurrentTag(parser);
1484                        continue;
1485                    }
1486                    perm = perm.intern();
1487                    readPermission(parser, perm);
1488
1489                } else if ("assign-permission".equals(name)) {
1490                    String perm = parser.getAttributeValue(null, "name");
1491                    if (perm == null) {
1492                        Slog.w(TAG, "<assign-permission> without name at "
1493                                + parser.getPositionDescription());
1494                        XmlUtils.skipCurrentTag(parser);
1495                        continue;
1496                    }
1497                    String uidStr = parser.getAttributeValue(null, "uid");
1498                    if (uidStr == null) {
1499                        Slog.w(TAG, "<assign-permission> without uid at "
1500                                + parser.getPositionDescription());
1501                        XmlUtils.skipCurrentTag(parser);
1502                        continue;
1503                    }
1504                    int uid = Process.getUidForName(uidStr);
1505                    if (uid < 0) {
1506                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1507                                + uidStr + "\" at "
1508                                + parser.getPositionDescription());
1509                        XmlUtils.skipCurrentTag(parser);
1510                        continue;
1511                    }
1512                    perm = perm.intern();
1513                    HashSet<String> perms = mSystemPermissions.get(uid);
1514                    if (perms == null) {
1515                        perms = new HashSet<String>();
1516                        mSystemPermissions.put(uid, perms);
1517                    }
1518                    perms.add(perm);
1519                    XmlUtils.skipCurrentTag(parser);
1520
1521                } else if ("library".equals(name)) {
1522                    String lname = parser.getAttributeValue(null, "name");
1523                    String lfile = parser.getAttributeValue(null, "file");
1524                    if (lname == null) {
1525                        Slog.w(TAG, "<library> without name at "
1526                                + parser.getPositionDescription());
1527                    } else if (lfile == null) {
1528                        Slog.w(TAG, "<library> without file at "
1529                                + parser.getPositionDescription());
1530                    } else {
1531                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1532                        mSharedLibraries.put(lname, lfile);
1533                    }
1534                    XmlUtils.skipCurrentTag(parser);
1535                    continue;
1536
1537                } else if ("feature".equals(name)) {
1538                    String fname = parser.getAttributeValue(null, "name");
1539                    if (fname == null) {
1540                        Slog.w(TAG, "<feature> without name at "
1541                                + parser.getPositionDescription());
1542                    } else {
1543                        //Log.i(TAG, "Got feature " + fname);
1544                        FeatureInfo fi = new FeatureInfo();
1545                        fi.name = fname;
1546                        mAvailableFeatures.put(fname, fi);
1547                    }
1548                    XmlUtils.skipCurrentTag(parser);
1549                    continue;
1550
1551                } else {
1552                    XmlUtils.skipCurrentTag(parser);
1553                    continue;
1554                }
1555
1556            }
1557            permReader.close();
1558        } catch (XmlPullParserException e) {
1559            Slog.w(TAG, "Got execption parsing permissions.", e);
1560        } catch (IOException e) {
1561            Slog.w(TAG, "Got execption parsing permissions.", e);
1562        }
1563    }
1564
1565    void readPermission(XmlPullParser parser, String name)
1566            throws IOException, XmlPullParserException {
1567
1568        name = name.intern();
1569
1570        BasePermission bp = mSettings.mPermissions.get(name);
1571        if (bp == null) {
1572            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1573            mSettings.mPermissions.put(name, bp);
1574        }
1575        int outerDepth = parser.getDepth();
1576        int type;
1577        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1578               && (type != XmlPullParser.END_TAG
1579                       || parser.getDepth() > outerDepth)) {
1580            if (type == XmlPullParser.END_TAG
1581                    || type == XmlPullParser.TEXT) {
1582                continue;
1583            }
1584
1585            String tagName = parser.getName();
1586            if ("group".equals(tagName)) {
1587                String gidStr = parser.getAttributeValue(null, "gid");
1588                if (gidStr != null) {
1589                    int gid = Process.getGidForName(gidStr);
1590                    bp.gids = appendInt(bp.gids, gid);
1591                } else {
1592                    Slog.w(TAG, "<group> without gid at "
1593                            + parser.getPositionDescription());
1594                }
1595            }
1596            XmlUtils.skipCurrentTag(parser);
1597        }
1598    }
1599
1600    static int[] appendInts(int[] cur, int[] add) {
1601        if (add == null) return cur;
1602        if (cur == null) return add;
1603        final int N = add.length;
1604        for (int i=0; i<N; i++) {
1605            cur = appendInt(cur, add[i]);
1606        }
1607        return cur;
1608    }
1609
1610    static int[] removeInts(int[] cur, int[] rem) {
1611        if (rem == null) return cur;
1612        if (cur == null) return cur;
1613        final int N = rem.length;
1614        for (int i=0; i<N; i++) {
1615            cur = removeInt(cur, rem[i]);
1616        }
1617        return cur;
1618    }
1619
1620    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1621        if (!sUserManager.exists(userId)) return null;
1622        PackageInfo pi;
1623        final PackageSetting ps = (PackageSetting) p.mExtras;
1624        if (ps == null) {
1625            return null;
1626        }
1627        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1628        final PackageUserState state = ps.readUserState(userId);
1629        pi = PackageParser.generatePackageInfo(p, gp.gids, flags,
1630                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1631                state, userId);
1632        if (pi != null) {
1633            pi.applicationInfo.enabledSetting = state.enabled;
1634            pi.applicationInfo.enabled =
1635                    pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT
1636                    || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED;
1637        }
1638        return pi;
1639    }
1640
1641    @Override
1642    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1643        if (!sUserManager.exists(userId)) return null;
1644        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1645        // reader
1646        synchronized (mPackages) {
1647            PackageParser.Package p = mPackages.get(packageName);
1648            if (DEBUG_PACKAGE_INFO)
1649                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1650            if (p != null) {
1651                return generatePackageInfo(p, flags, userId);
1652            }
1653            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1654                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1655            }
1656        }
1657        return null;
1658    }
1659
1660    public String[] currentToCanonicalPackageNames(String[] names) {
1661        String[] out = new String[names.length];
1662        // reader
1663        synchronized (mPackages) {
1664            for (int i=names.length-1; i>=0; i--) {
1665                PackageSetting ps = mSettings.mPackages.get(names[i]);
1666                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1667            }
1668        }
1669        return out;
1670    }
1671
1672    public String[] canonicalToCurrentPackageNames(String[] names) {
1673        String[] out = new String[names.length];
1674        // reader
1675        synchronized (mPackages) {
1676            for (int i=names.length-1; i>=0; i--) {
1677                String cur = mSettings.mRenamedPackages.get(names[i]);
1678                out[i] = cur != null ? cur : names[i];
1679            }
1680        }
1681        return out;
1682    }
1683
1684    @Override
1685    public int getPackageUid(String packageName, int userId) {
1686        if (!sUserManager.exists(userId)) return -1;
1687        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1688        // reader
1689        synchronized (mPackages) {
1690            PackageParser.Package p = mPackages.get(packageName);
1691            if(p != null) {
1692                return UserHandle.getUid(userId, p.applicationInfo.uid);
1693            }
1694            PackageSetting ps = mSettings.mPackages.get(packageName);
1695            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1696                return -1;
1697            }
1698            p = ps.pkg;
1699            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1700        }
1701    }
1702
1703    public int[] getPackageGids(String packageName) {
1704        final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
1705        // reader
1706        synchronized (mPackages) {
1707            PackageParser.Package p = mPackages.get(packageName);
1708            if (DEBUG_PACKAGE_INFO)
1709                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1710            if (p != null) {
1711                final PackageSetting ps = (PackageSetting)p.mExtras;
1712                final SharedUserSetting suid = ps.sharedUser;
1713                int[] gids = suid != null ? suid.gids : ps.gids;
1714
1715                // include GIDs for any unenforced permissions
1716                if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
1717                    final BasePermission basePerm = mSettings.mPermissions.get(
1718                            READ_EXTERNAL_STORAGE);
1719                    gids = appendInts(gids, basePerm.gids);
1720                }
1721
1722                return gids;
1723            }
1724        }
1725        // stupid thing to indicate an error.
1726        return new int[0];
1727    }
1728
1729    static final PermissionInfo generatePermissionInfo(
1730            BasePermission bp, int flags) {
1731        if (bp.perm != null) {
1732            return PackageParser.generatePermissionInfo(bp.perm, flags);
1733        }
1734        PermissionInfo pi = new PermissionInfo();
1735        pi.name = bp.name;
1736        pi.packageName = bp.sourcePackage;
1737        pi.nonLocalizedLabel = bp.name;
1738        pi.protectionLevel = bp.protectionLevel;
1739        return pi;
1740    }
1741
1742    public PermissionInfo getPermissionInfo(String name, int flags) {
1743        // reader
1744        synchronized (mPackages) {
1745            final BasePermission p = mSettings.mPermissions.get(name);
1746            if (p != null) {
1747                return generatePermissionInfo(p, flags);
1748            }
1749            return null;
1750        }
1751    }
1752
1753    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1754        // reader
1755        synchronized (mPackages) {
1756            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1757            for (BasePermission p : mSettings.mPermissions.values()) {
1758                if (group == null) {
1759                    if (p.perm == null || p.perm.info.group == null) {
1760                        out.add(generatePermissionInfo(p, flags));
1761                    }
1762                } else {
1763                    if (p.perm != null && group.equals(p.perm.info.group)) {
1764                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1765                    }
1766                }
1767            }
1768
1769            if (out.size() > 0) {
1770                return out;
1771            }
1772            return mPermissionGroups.containsKey(group) ? out : null;
1773        }
1774    }
1775
1776    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1777        // reader
1778        synchronized (mPackages) {
1779            return PackageParser.generatePermissionGroupInfo(
1780                    mPermissionGroups.get(name), flags);
1781        }
1782    }
1783
1784    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1785        // reader
1786        synchronized (mPackages) {
1787            final int N = mPermissionGroups.size();
1788            ArrayList<PermissionGroupInfo> out
1789                    = new ArrayList<PermissionGroupInfo>(N);
1790            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1791                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1792            }
1793            return out;
1794        }
1795    }
1796
1797    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
1798            int userId) {
1799        if (!sUserManager.exists(userId)) return null;
1800        PackageSetting ps = mSettings.mPackages.get(packageName);
1801        if (ps != null) {
1802            if (ps.pkg == null) {
1803                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
1804                        flags, userId);
1805                if (pInfo != null) {
1806                    return pInfo.applicationInfo;
1807                }
1808                return null;
1809            }
1810            return PackageParser.generateApplicationInfo(ps.pkg, flags,
1811                    ps.readUserState(userId), userId);
1812        }
1813        return null;
1814    }
1815
1816    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
1817            int userId) {
1818        if (!sUserManager.exists(userId)) return null;
1819        PackageSetting ps = mSettings.mPackages.get(packageName);
1820        if (ps != null) {
1821            PackageParser.Package pkg = ps.pkg;
1822            if (pkg == null) {
1823                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
1824                    return null;
1825                }
1826                pkg = new PackageParser.Package(packageName);
1827                pkg.applicationInfo.packageName = packageName;
1828                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
1829                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1830                pkg.applicationInfo.sourceDir = ps.codePathString;
1831                pkg.applicationInfo.dataDir =
1832                        getDataPathForPackage(packageName, 0).getPath();
1833                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
1834            }
1835            // pkg.mSetEnabled = ps.getEnabled(userId);
1836            // pkg.mSetStopped = ps.getStopped(userId);
1837            return generatePackageInfo(pkg, flags, userId);
1838        }
1839        return null;
1840    }
1841
1842    @Override
1843    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
1844        if (!sUserManager.exists(userId)) return null;
1845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
1846        // writer
1847        synchronized (mPackages) {
1848            PackageParser.Package p = mPackages.get(packageName);
1849            if (DEBUG_PACKAGE_INFO) Log.v(
1850                    TAG, "getApplicationInfo " + packageName
1851                    + ": " + p);
1852            if (p != null) {
1853                PackageSetting ps = mSettings.mPackages.get(packageName);
1854                if (ps == null) return null;
1855                // Note: isEnabledLP() does not apply here - always return info
1856                return PackageParser.generateApplicationInfo(p, flags, ps.readUserState(userId));
1857            }
1858            if ("android".equals(packageName)||"system".equals(packageName)) {
1859                return mAndroidApplication;
1860            }
1861            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1862                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
1863            }
1864        }
1865        return null;
1866    }
1867
1868
1869    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1870        mContext.enforceCallingOrSelfPermission(
1871                android.Manifest.permission.CLEAR_APP_CACHE, null);
1872        // Queue up an async operation since clearing cache may take a little while.
1873        mHandler.post(new Runnable() {
1874            public void run() {
1875                mHandler.removeCallbacks(this);
1876                int retCode = -1;
1877                synchronized (mInstallLock) {
1878                    retCode = mInstaller.freeCache(freeStorageSize);
1879                    if (retCode < 0) {
1880                        Slog.w(TAG, "Couldn't clear application caches");
1881                    }
1882                }
1883                if (observer != null) {
1884                    try {
1885                        observer.onRemoveCompleted(null, (retCode >= 0));
1886                    } catch (RemoteException e) {
1887                        Slog.w(TAG, "RemoveException when invoking call back");
1888                    }
1889                }
1890            }
1891        });
1892    }
1893
1894    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
1895        mContext.enforceCallingOrSelfPermission(
1896                android.Manifest.permission.CLEAR_APP_CACHE, null);
1897        // Queue up an async operation since clearing cache may take a little while.
1898        mHandler.post(new Runnable() {
1899            public void run() {
1900                mHandler.removeCallbacks(this);
1901                int retCode = -1;
1902                synchronized (mInstallLock) {
1903                    retCode = mInstaller.freeCache(freeStorageSize);
1904                    if (retCode < 0) {
1905                        Slog.w(TAG, "Couldn't clear application caches");
1906                    }
1907                }
1908                if(pi != null) {
1909                    try {
1910                        // Callback via pending intent
1911                        int code = (retCode >= 0) ? 1 : 0;
1912                        pi.sendIntent(null, code, null,
1913                                null, null);
1914                    } catch (SendIntentException e1) {
1915                        Slog.i(TAG, "Failed to send pending intent");
1916                    }
1917                }
1918            }
1919        });
1920    }
1921
1922    @Override
1923    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
1924        if (!sUserManager.exists(userId)) return null;
1925        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
1926        synchronized (mPackages) {
1927            PackageParser.Activity a = mActivities.mActivities.get(component);
1928
1929            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
1930            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
1931                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1932                if (ps == null) return null;
1933                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1934                        userId);
1935            }
1936            if (mResolveComponentName.equals(component)) {
1937                return mResolveActivity;
1938            }
1939        }
1940        return null;
1941    }
1942
1943    @Override
1944    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
1945        if (!sUserManager.exists(userId)) return null;
1946        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
1947        synchronized (mPackages) {
1948            PackageParser.Activity a = mReceivers.mActivities.get(component);
1949            if (DEBUG_PACKAGE_INFO) Log.v(
1950                TAG, "getReceiverInfo " + component + ": " + a);
1951            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
1952                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1953                if (ps == null) return null;
1954                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
1955                        userId);
1956            }
1957        }
1958        return null;
1959    }
1960
1961    @Override
1962    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
1963        if (!sUserManager.exists(userId)) return null;
1964        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
1965        synchronized (mPackages) {
1966            PackageParser.Service s = mServices.mServices.get(component);
1967            if (DEBUG_PACKAGE_INFO) Log.v(
1968                TAG, "getServiceInfo " + component + ": " + s);
1969            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
1970                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1971                if (ps == null) return null;
1972                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
1973                        userId);
1974            }
1975        }
1976        return null;
1977    }
1978
1979    @Override
1980    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
1981        if (!sUserManager.exists(userId)) return null;
1982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
1983        synchronized (mPackages) {
1984            PackageParser.Provider p = mProvidersByComponent.get(component);
1985            if (DEBUG_PACKAGE_INFO) Log.v(
1986                TAG, "getProviderInfo " + component + ": " + p);
1987            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
1988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
1989                if (ps == null) return null;
1990                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
1991                        userId);
1992            }
1993        }
1994        return null;
1995    }
1996
1997    public String[] getSystemSharedLibraryNames() {
1998        Set<String> libSet;
1999        synchronized (mPackages) {
2000            libSet = mSharedLibraries.keySet();
2001            int size = libSet.size();
2002            if (size > 0) {
2003                String[] libs = new String[size];
2004                libSet.toArray(libs);
2005                return libs;
2006            }
2007        }
2008        return null;
2009    }
2010
2011    public FeatureInfo[] getSystemAvailableFeatures() {
2012        Collection<FeatureInfo> featSet;
2013        synchronized (mPackages) {
2014            featSet = mAvailableFeatures.values();
2015            int size = featSet.size();
2016            if (size > 0) {
2017                FeatureInfo[] features = new FeatureInfo[size+1];
2018                featSet.toArray(features);
2019                FeatureInfo fi = new FeatureInfo();
2020                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2021                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2022                features[size] = fi;
2023                return features;
2024            }
2025        }
2026        return null;
2027    }
2028
2029    public boolean hasSystemFeature(String name) {
2030        synchronized (mPackages) {
2031            return mAvailableFeatures.containsKey(name);
2032        }
2033    }
2034
2035    private void checkValidCaller(int uid, int userId) {
2036        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2037            return;
2038
2039        throw new SecurityException("Caller uid=" + uid
2040                + " is not privileged to communicate with user=" + userId);
2041    }
2042
2043    public int checkPermission(String permName, String pkgName) {
2044        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
2045        synchronized (mPackages) {
2046            PackageParser.Package p = mPackages.get(pkgName);
2047            if (p != null && p.mExtras != null) {
2048                PackageSetting ps = (PackageSetting)p.mExtras;
2049                if (ps.sharedUser != null) {
2050                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2051                        return PackageManager.PERMISSION_GRANTED;
2052                    }
2053                } else if (ps.grantedPermissions.contains(permName)) {
2054                    return PackageManager.PERMISSION_GRANTED;
2055                }
2056            }
2057            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
2058                return PackageManager.PERMISSION_GRANTED;
2059            }
2060        }
2061        return PackageManager.PERMISSION_DENIED;
2062    }
2063
2064    public int checkUidPermission(String permName, int uid) {
2065        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
2066        synchronized (mPackages) {
2067            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2068            if (obj != null) {
2069                GrantedPermissions gp = (GrantedPermissions)obj;
2070                if (gp.grantedPermissions.contains(permName)) {
2071                    return PackageManager.PERMISSION_GRANTED;
2072                }
2073            } else {
2074                HashSet<String> perms = mSystemPermissions.get(uid);
2075                if (perms != null && perms.contains(permName)) {
2076                    return PackageManager.PERMISSION_GRANTED;
2077                }
2078            }
2079            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
2080                return PackageManager.PERMISSION_GRANTED;
2081            }
2082        }
2083        return PackageManager.PERMISSION_DENIED;
2084    }
2085
2086    /**
2087     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2088     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2089     * @param message the message to log on security exception
2090     * @return
2091     */
2092    private void enforceCrossUserPermission(int callingUid, int userId,
2093            boolean requireFullPermission, String message) {
2094        if (userId < 0) {
2095            throw new IllegalArgumentException("Invalid userId " + userId);
2096        }
2097        if (userId == UserHandle.getUserId(callingUid)) return;
2098        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2099            if (requireFullPermission) {
2100                mContext.enforceCallingOrSelfPermission(
2101                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2102            } else {
2103                try {
2104                    mContext.enforceCallingOrSelfPermission(
2105                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2106                } catch (SecurityException se) {
2107                    mContext.enforceCallingOrSelfPermission(
2108                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2109                }
2110            }
2111        }
2112    }
2113
2114    private BasePermission findPermissionTreeLP(String permName) {
2115        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2116            if (permName.startsWith(bp.name) &&
2117                    permName.length() > bp.name.length() &&
2118                    permName.charAt(bp.name.length()) == '.') {
2119                return bp;
2120            }
2121        }
2122        return null;
2123    }
2124
2125    private BasePermission checkPermissionTreeLP(String permName) {
2126        if (permName != null) {
2127            BasePermission bp = findPermissionTreeLP(permName);
2128            if (bp != null) {
2129                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2130                    return bp;
2131                }
2132                throw new SecurityException("Calling uid "
2133                        + Binder.getCallingUid()
2134                        + " is not allowed to add to permission tree "
2135                        + bp.name + " owned by uid " + bp.uid);
2136            }
2137        }
2138        throw new SecurityException("No permission tree found for " + permName);
2139    }
2140
2141    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2142        if (s1 == null) {
2143            return s2 == null;
2144        }
2145        if (s2 == null) {
2146            return false;
2147        }
2148        if (s1.getClass() != s2.getClass()) {
2149            return false;
2150        }
2151        return s1.equals(s2);
2152    }
2153
2154    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2155        if (pi1.icon != pi2.icon) return false;
2156        if (pi1.logo != pi2.logo) return false;
2157        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2158        if (!compareStrings(pi1.name, pi2.name)) return false;
2159        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2160        // We'll take care of setting this one.
2161        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2162        // These are not currently stored in settings.
2163        //if (!compareStrings(pi1.group, pi2.group)) return false;
2164        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2165        //if (pi1.labelRes != pi2.labelRes) return false;
2166        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2167        return true;
2168    }
2169
2170    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2171        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2172            throw new SecurityException("Label must be specified in permission");
2173        }
2174        BasePermission tree = checkPermissionTreeLP(info.name);
2175        BasePermission bp = mSettings.mPermissions.get(info.name);
2176        boolean added = bp == null;
2177        boolean changed = true;
2178        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2179        if (added) {
2180            bp = new BasePermission(info.name, tree.sourcePackage,
2181                    BasePermission.TYPE_DYNAMIC);
2182        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2183            throw new SecurityException(
2184                    "Not allowed to modify non-dynamic permission "
2185                    + info.name);
2186        } else {
2187            if (bp.protectionLevel == fixedLevel
2188                    && bp.perm.owner.equals(tree.perm.owner)
2189                    && bp.uid == tree.uid
2190                    && comparePermissionInfos(bp.perm.info, info)) {
2191                changed = false;
2192            }
2193        }
2194        bp.protectionLevel = fixedLevel;
2195        info = new PermissionInfo(info);
2196        info.protectionLevel = fixedLevel;
2197        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2198        bp.perm.info.packageName = tree.perm.info.packageName;
2199        bp.uid = tree.uid;
2200        if (added) {
2201            mSettings.mPermissions.put(info.name, bp);
2202        }
2203        if (changed) {
2204            if (!async) {
2205                mSettings.writeLPr();
2206            } else {
2207                scheduleWriteSettingsLocked();
2208            }
2209        }
2210        return added;
2211    }
2212
2213    public boolean addPermission(PermissionInfo info) {
2214        synchronized (mPackages) {
2215            return addPermissionLocked(info, false);
2216        }
2217    }
2218
2219    public boolean addPermissionAsync(PermissionInfo info) {
2220        synchronized (mPackages) {
2221            return addPermissionLocked(info, true);
2222        }
2223    }
2224
2225    public void removePermission(String name) {
2226        synchronized (mPackages) {
2227            checkPermissionTreeLP(name);
2228            BasePermission bp = mSettings.mPermissions.get(name);
2229            if (bp != null) {
2230                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2231                    throw new SecurityException(
2232                            "Not allowed to modify non-dynamic permission "
2233                            + name);
2234                }
2235                mSettings.mPermissions.remove(name);
2236                mSettings.writeLPr();
2237            }
2238        }
2239    }
2240
2241    public void grantPermission(String packageName, String permissionName) {
2242        mContext.enforceCallingOrSelfPermission(
2243                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2244        synchronized (mPackages) {
2245            final PackageParser.Package pkg = mPackages.get(packageName);
2246            if (pkg == null) {
2247                throw new IllegalArgumentException("Unknown package: " + packageName);
2248            }
2249            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2250            if (bp == null) {
2251                throw new IllegalArgumentException("Unknown permission: " + packageName);
2252            }
2253            if (!pkg.requestedPermissions.contains(permissionName)) {
2254                throw new SecurityException("Package " + packageName
2255                        + " has not requested permission " + permissionName);
2256            }
2257            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2258                throw new SecurityException("Permission " + permissionName
2259                        + " is not a development permission");
2260            }
2261            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2262            if (ps == null) {
2263                return;
2264            }
2265            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2266            if (gp.grantedPermissions.add(permissionName)) {
2267                if (ps.haveGids) {
2268                    gp.gids = appendInts(gp.gids, bp.gids);
2269                }
2270                mSettings.writeLPr();
2271            }
2272        }
2273    }
2274
2275    public void revokePermission(String packageName, String permissionName) {
2276        synchronized (mPackages) {
2277            final PackageParser.Package pkg = mPackages.get(packageName);
2278            if (pkg == null) {
2279                throw new IllegalArgumentException("Unknown package: " + packageName);
2280            }
2281            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2282                mContext.enforceCallingOrSelfPermission(
2283                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2284            }
2285            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2286            if (bp == null) {
2287                throw new IllegalArgumentException("Unknown permission: " + packageName);
2288            }
2289            if (!pkg.requestedPermissions.contains(permissionName)) {
2290                throw new SecurityException("Package " + packageName
2291                        + " has not requested permission " + permissionName);
2292            }
2293            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) {
2294                throw new SecurityException("Permission " + permissionName
2295                        + " is not a development permission");
2296            }
2297            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2298            if (ps == null) {
2299                return;
2300            }
2301            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2302            if (gp.grantedPermissions.remove(permissionName)) {
2303                gp.grantedPermissions.remove(permissionName);
2304                if (ps.haveGids) {
2305                    gp.gids = removeInts(gp.gids, bp.gids);
2306                }
2307                mSettings.writeLPr();
2308            }
2309        }
2310    }
2311
2312    public boolean isProtectedBroadcast(String actionName) {
2313        synchronized (mPackages) {
2314            return mProtectedBroadcasts.contains(actionName);
2315        }
2316    }
2317
2318    public int checkSignatures(String pkg1, String pkg2) {
2319        synchronized (mPackages) {
2320            final PackageParser.Package p1 = mPackages.get(pkg1);
2321            final PackageParser.Package p2 = mPackages.get(pkg2);
2322            if (p1 == null || p1.mExtras == null
2323                    || p2 == null || p2.mExtras == null) {
2324                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2325            }
2326            return compareSignatures(p1.mSignatures, p2.mSignatures);
2327        }
2328    }
2329
2330    public int checkUidSignatures(int uid1, int uid2) {
2331        // Map to base uids.
2332        uid1 = UserHandle.getAppId(uid1);
2333        uid2 = UserHandle.getAppId(uid2);
2334        // reader
2335        synchronized (mPackages) {
2336            Signature[] s1;
2337            Signature[] s2;
2338            Object obj = mSettings.getUserIdLPr(uid1);
2339            if (obj != null) {
2340                if (obj instanceof SharedUserSetting) {
2341                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2342                } else if (obj instanceof PackageSetting) {
2343                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2344                } else {
2345                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2346                }
2347            } else {
2348                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2349            }
2350            obj = mSettings.getUserIdLPr(uid2);
2351            if (obj != null) {
2352                if (obj instanceof SharedUserSetting) {
2353                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2354                } else if (obj instanceof PackageSetting) {
2355                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2356                } else {
2357                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2358                }
2359            } else {
2360                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2361            }
2362            return compareSignatures(s1, s2);
2363        }
2364    }
2365
2366    static int compareSignatures(Signature[] s1, Signature[] s2) {
2367        if (s1 == null) {
2368            return s2 == null
2369                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2370                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2371        }
2372        if (s2 == null) {
2373            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2374        }
2375        HashSet<Signature> set1 = new HashSet<Signature>();
2376        for (Signature sig : s1) {
2377            set1.add(sig);
2378        }
2379        HashSet<Signature> set2 = new HashSet<Signature>();
2380        for (Signature sig : s2) {
2381            set2.add(sig);
2382        }
2383        // Make sure s2 contains all signatures in s1.
2384        if (set1.equals(set2)) {
2385            return PackageManager.SIGNATURE_MATCH;
2386        }
2387        return PackageManager.SIGNATURE_NO_MATCH;
2388    }
2389
2390    public String[] getPackagesForUid(int uid) {
2391        uid = UserHandle.getAppId(uid);
2392        // reader
2393        synchronized (mPackages) {
2394            Object obj = mSettings.getUserIdLPr(uid);
2395            if (obj instanceof SharedUserSetting) {
2396                final SharedUserSetting sus = (SharedUserSetting) obj;
2397                final int N = sus.packages.size();
2398                final String[] res = new String[N];
2399                final Iterator<PackageSetting> it = sus.packages.iterator();
2400                int i = 0;
2401                while (it.hasNext()) {
2402                    res[i++] = it.next().name;
2403                }
2404                return res;
2405            } else if (obj instanceof PackageSetting) {
2406                final PackageSetting ps = (PackageSetting) obj;
2407                return new String[] { ps.name };
2408            }
2409        }
2410        return null;
2411    }
2412
2413    public String getNameForUid(int uid) {
2414        // reader
2415        synchronized (mPackages) {
2416            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2417            if (obj instanceof SharedUserSetting) {
2418                final SharedUserSetting sus = (SharedUserSetting) obj;
2419                return sus.name + ":" + sus.userId;
2420            } else if (obj instanceof PackageSetting) {
2421                final PackageSetting ps = (PackageSetting) obj;
2422                return ps.name;
2423            }
2424        }
2425        return null;
2426    }
2427
2428    public int getUidForSharedUser(String sharedUserName) {
2429        if(sharedUserName == null) {
2430            return -1;
2431        }
2432        // reader
2433        synchronized (mPackages) {
2434            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2435            if (suid == null) {
2436                return -1;
2437            }
2438            return suid.userId;
2439        }
2440    }
2441
2442    @Override
2443    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2444            int flags, int userId) {
2445        if (!sUserManager.exists(userId)) return null;
2446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2447        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2448        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2449    }
2450
2451    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2452            int flags, List<ResolveInfo> query, int userId) {
2453        if (query != null) {
2454            final int N = query.size();
2455            if (N == 1) {
2456                return query.get(0);
2457            } else if (N > 1) {
2458                // If there is more than one activity with the same priority,
2459                // then let the user decide between them.
2460                ResolveInfo r0 = query.get(0);
2461                ResolveInfo r1 = query.get(1);
2462                if (DEBUG_INTENT_MATCHING) {
2463                    Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2464                            + r1.activityInfo.name + "=" + r1.priority);
2465                }
2466                // If the first activity has a higher priority, or a different
2467                // default, then it is always desireable to pick it.
2468                if (r0.priority != r1.priority
2469                        || r0.preferredOrder != r1.preferredOrder
2470                        || r0.isDefault != r1.isDefault) {
2471                    return query.get(0);
2472                }
2473                // If we have saved a preference for a preferred activity for
2474                // this Intent, use that.
2475                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2476                        flags, query, r0.priority, userId);
2477                if (ri != null) {
2478                    return ri;
2479                }
2480                if (userId != 0) {
2481                    ri = new ResolveInfo(mResolveInfo);
2482                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2483                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2484                            ri.activityInfo.applicationInfo);
2485                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2486                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2487                    return ri;
2488                }
2489                return mResolveInfo;
2490            }
2491        }
2492        return null;
2493    }
2494
2495    ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
2496            int flags, List<ResolveInfo> query, int priority, int userId) {
2497        if (!sUserManager.exists(userId)) return null;
2498        // writer
2499        synchronized (mPackages) {
2500            if (intent.getSelector() != null) {
2501                intent = intent.getSelector();
2502            }
2503            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2504            List<PreferredActivity> prefs =
2505                    mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
2506                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
2507            if (prefs != null && prefs.size() > 0) {
2508                // First figure out how good the original match set is.
2509                // We will only allow preferred activities that came
2510                // from the same match quality.
2511                int match = 0;
2512
2513                if (DEBUG_PREFERRED) {
2514                    Log.v(TAG, "Figuring out best match...");
2515                }
2516
2517                final int N = query.size();
2518                for (int j=0; j<N; j++) {
2519                    final ResolveInfo ri = query.get(j);
2520                    if (DEBUG_PREFERRED) {
2521                        Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
2522                                + Integer.toHexString(match));
2523                    }
2524                    if (ri.match > match) {
2525                        match = ri.match;
2526                    }
2527                }
2528
2529                if (DEBUG_PREFERRED) {
2530                    Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
2531                }
2532
2533                match &= IntentFilter.MATCH_CATEGORY_MASK;
2534                final int M = prefs.size();
2535                for (int i=0; i<M; i++) {
2536                    final PreferredActivity pa = prefs.get(i);
2537                    if (pa.mUserId != userId) {
2538                        continue;
2539                    }
2540                    if (pa.mPref.mMatch != match) {
2541                        continue;
2542                    }
2543                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId);
2544                    if (DEBUG_PREFERRED) {
2545                        Log.v(TAG, "Got preferred activity:");
2546                        if (ai != null) {
2547                            ai.dump(new LogPrinter(Log.VERBOSE, TAG), "  ");
2548                        } else {
2549                            Log.v(TAG, "  null");
2550                        }
2551                    }
2552                    if (ai == null) {
2553                        // This previously registered preferred activity
2554                        // component is no longer known.  Most likely an update
2555                        // to the app was installed and in the new version this
2556                        // component no longer exists.  Clean it up by removing
2557                        // it from the preferred activities list, and skip it.
2558                        Slog.w(TAG, "Removing dangling preferred activity: "
2559                                + pa.mPref.mComponent);
2560                        mSettings.mPreferredActivities.removeFilter(pa);
2561                        continue;
2562                    }
2563                    for (int j=0; j<N; j++) {
2564                        final ResolveInfo ri = query.get(j);
2565                        if (!ri.activityInfo.applicationInfo.packageName
2566                                .equals(ai.applicationInfo.packageName)) {
2567                            continue;
2568                        }
2569                        if (!ri.activityInfo.name.equals(ai.name)) {
2570                            continue;
2571                        }
2572
2573                        // Okay we found a previously set preferred app.
2574                        // If the result set is different from when this
2575                        // was created, we need to clear it and re-ask the
2576                        // user their preference.
2577                        if (!pa.mPref.sameSet(query, priority)) {
2578                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
2579                                    + intent + " type " + resolvedType);
2580                            mSettings.mPreferredActivities.removeFilter(pa);
2581                            return null;
2582                        }
2583
2584                        // Yay!
2585                        return ri;
2586                    }
2587                }
2588            }
2589        }
2590        return null;
2591    }
2592
2593    @Override
2594    public List<ResolveInfo> queryIntentActivities(Intent intent,
2595            String resolvedType, int flags, int userId) {
2596        if (!sUserManager.exists(userId)) return null;
2597        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
2598        ComponentName comp = intent.getComponent();
2599        if (comp == null) {
2600            if (intent.getSelector() != null) {
2601                intent = intent.getSelector();
2602                comp = intent.getComponent();
2603            }
2604        }
2605
2606        if (comp != null) {
2607            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2608            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
2609            if (ai != null) {
2610                final ResolveInfo ri = new ResolveInfo();
2611                ri.activityInfo = ai;
2612                list.add(ri);
2613            }
2614            return list;
2615        }
2616
2617        // reader
2618        synchronized (mPackages) {
2619            final String pkgName = intent.getPackage();
2620            if (pkgName == null) {
2621                return mActivities.queryIntent(intent, resolvedType, flags, userId);
2622            }
2623            final PackageParser.Package pkg = mPackages.get(pkgName);
2624            if (pkg != null) {
2625                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
2626                        pkg.activities, userId);
2627            }
2628            return new ArrayList<ResolveInfo>();
2629        }
2630    }
2631
2632    @Override
2633    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2634            Intent[] specifics, String[] specificTypes, Intent intent,
2635            String resolvedType, int flags, int userId) {
2636        if (!sUserManager.exists(userId)) return null;
2637        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
2638                "query intent activity options");
2639        final String resultsAction = intent.getAction();
2640
2641        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
2642                | PackageManager.GET_RESOLVED_FILTER, userId);
2643
2644        if (DEBUG_INTENT_MATCHING) {
2645            Log.v(TAG, "Query " + intent + ": " + results);
2646        }
2647
2648        int specificsPos = 0;
2649        int N;
2650
2651        // todo: note that the algorithm used here is O(N^2).  This
2652        // isn't a problem in our current environment, but if we start running
2653        // into situations where we have more than 5 or 10 matches then this
2654        // should probably be changed to something smarter...
2655
2656        // First we go through and resolve each of the specific items
2657        // that were supplied, taking care of removing any corresponding
2658        // duplicate items in the generic resolve list.
2659        if (specifics != null) {
2660            for (int i=0; i<specifics.length; i++) {
2661                final Intent sintent = specifics[i];
2662                if (sintent == null) {
2663                    continue;
2664                }
2665
2666                if (DEBUG_INTENT_MATCHING) {
2667                    Log.v(TAG, "Specific #" + i + ": " + sintent);
2668                }
2669
2670                String action = sintent.getAction();
2671                if (resultsAction != null && resultsAction.equals(action)) {
2672                    // If this action was explicitly requested, then don't
2673                    // remove things that have it.
2674                    action = null;
2675                }
2676
2677                ResolveInfo ri = null;
2678                ActivityInfo ai = null;
2679
2680                ComponentName comp = sintent.getComponent();
2681                if (comp == null) {
2682                    ri = resolveIntent(
2683                        sintent,
2684                        specificTypes != null ? specificTypes[i] : null,
2685                            flags, userId);
2686                    if (ri == null) {
2687                        continue;
2688                    }
2689                    if (ri == mResolveInfo) {
2690                        // ACK!  Must do something better with this.
2691                    }
2692                    ai = ri.activityInfo;
2693                    comp = new ComponentName(ai.applicationInfo.packageName,
2694                            ai.name);
2695                } else {
2696                    ai = getActivityInfo(comp, flags, userId);
2697                    if (ai == null) {
2698                        continue;
2699                    }
2700                }
2701
2702                // Look for any generic query activities that are duplicates
2703                // of this specific one, and remove them from the results.
2704                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
2705                N = results.size();
2706                int j;
2707                for (j=specificsPos; j<N; j++) {
2708                    ResolveInfo sri = results.get(j);
2709                    if ((sri.activityInfo.name.equals(comp.getClassName())
2710                            && sri.activityInfo.applicationInfo.packageName.equals(
2711                                    comp.getPackageName()))
2712                        || (action != null && sri.filter.matchAction(action))) {
2713                        results.remove(j);
2714                        if (DEBUG_INTENT_MATCHING) Log.v(
2715                            TAG, "Removing duplicate item from " + j
2716                            + " due to specific " + specificsPos);
2717                        if (ri == null) {
2718                            ri = sri;
2719                        }
2720                        j--;
2721                        N--;
2722                    }
2723                }
2724
2725                // Add this specific item to its proper place.
2726                if (ri == null) {
2727                    ri = new ResolveInfo();
2728                    ri.activityInfo = ai;
2729                }
2730                results.add(specificsPos, ri);
2731                ri.specificIndex = i;
2732                specificsPos++;
2733            }
2734        }
2735
2736        // Now we go through the remaining generic results and remove any
2737        // duplicate actions that are found here.
2738        N = results.size();
2739        for (int i=specificsPos; i<N-1; i++) {
2740            final ResolveInfo rii = results.get(i);
2741            if (rii.filter == null) {
2742                continue;
2743            }
2744
2745            // Iterate over all of the actions of this result's intent
2746            // filter...  typically this should be just one.
2747            final Iterator<String> it = rii.filter.actionsIterator();
2748            if (it == null) {
2749                continue;
2750            }
2751            while (it.hasNext()) {
2752                final String action = it.next();
2753                if (resultsAction != null && resultsAction.equals(action)) {
2754                    // If this action was explicitly requested, then don't
2755                    // remove things that have it.
2756                    continue;
2757                }
2758                for (int j=i+1; j<N; j++) {
2759                    final ResolveInfo rij = results.get(j);
2760                    if (rij.filter != null && rij.filter.hasAction(action)) {
2761                        results.remove(j);
2762                        if (DEBUG_INTENT_MATCHING) Log.v(
2763                            TAG, "Removing duplicate item from " + j
2764                            + " due to action " + action + " at " + i);
2765                        j--;
2766                        N--;
2767                    }
2768                }
2769            }
2770
2771            // If the caller didn't request filter information, drop it now
2772            // so we don't have to marshall/unmarshall it.
2773            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2774                rii.filter = null;
2775            }
2776        }
2777
2778        // Filter out the caller activity if so requested.
2779        if (caller != null) {
2780            N = results.size();
2781            for (int i=0; i<N; i++) {
2782                ActivityInfo ainfo = results.get(i).activityInfo;
2783                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2784                        && caller.getClassName().equals(ainfo.name)) {
2785                    results.remove(i);
2786                    break;
2787                }
2788            }
2789        }
2790
2791        // If the caller didn't request filter information,
2792        // drop them now so we don't have to
2793        // marshall/unmarshall it.
2794        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2795            N = results.size();
2796            for (int i=0; i<N; i++) {
2797                results.get(i).filter = null;
2798            }
2799        }
2800
2801        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
2802        return results;
2803    }
2804
2805    @Override
2806    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
2807            int userId) {
2808        if (!sUserManager.exists(userId)) return null;
2809        ComponentName comp = intent.getComponent();
2810        if (comp == null) {
2811            if (intent.getSelector() != null) {
2812                intent = intent.getSelector();
2813                comp = intent.getComponent();
2814            }
2815        }
2816        if (comp != null) {
2817            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2818            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
2819            if (ai != null) {
2820                ResolveInfo ri = new ResolveInfo();
2821                ri.activityInfo = ai;
2822                list.add(ri);
2823            }
2824            return list;
2825        }
2826
2827        // reader
2828        synchronized (mPackages) {
2829            String pkgName = intent.getPackage();
2830            if (pkgName == null) {
2831                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
2832            }
2833            final PackageParser.Package pkg = mPackages.get(pkgName);
2834            if (pkg != null) {
2835                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
2836                        userId);
2837            }
2838            return null;
2839        }
2840    }
2841
2842    @Override
2843    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
2844        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
2845        if (!sUserManager.exists(userId)) return null;
2846        if (query != null) {
2847            if (query.size() >= 1) {
2848                // If there is more than one service with the same priority,
2849                // just arbitrarily pick the first one.
2850                return query.get(0);
2851            }
2852        }
2853        return null;
2854    }
2855
2856    @Override
2857    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
2858            int userId) {
2859        if (!sUserManager.exists(userId)) return null;
2860        ComponentName comp = intent.getComponent();
2861        if (comp == null) {
2862            if (intent.getSelector() != null) {
2863                intent = intent.getSelector();
2864                comp = intent.getComponent();
2865            }
2866        }
2867        if (comp != null) {
2868            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2869            final ServiceInfo si = getServiceInfo(comp, flags, userId);
2870            if (si != null) {
2871                final ResolveInfo ri = new ResolveInfo();
2872                ri.serviceInfo = si;
2873                list.add(ri);
2874            }
2875            return list;
2876        }
2877
2878        // reader
2879        synchronized (mPackages) {
2880            String pkgName = intent.getPackage();
2881            if (pkgName == null) {
2882                return mServices.queryIntent(intent, resolvedType, flags, userId);
2883            }
2884            final PackageParser.Package pkg = mPackages.get(pkgName);
2885            if (pkg != null) {
2886                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
2887                        userId);
2888            }
2889            return null;
2890        }
2891    }
2892
2893    private static final int getContinuationPoint(final String[] keys, final String key) {
2894        final int index;
2895        if (key == null) {
2896            index = 0;
2897        } else {
2898            final int insertPoint = Arrays.binarySearch(keys, key);
2899            if (insertPoint < 0) {
2900                index = -insertPoint;
2901            } else {
2902                index = insertPoint + 1;
2903            }
2904        }
2905        return index;
2906    }
2907
2908    @Override
2909    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead,
2910            int userId) {
2911        final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
2912        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2913        final String[] keys;
2914
2915        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
2916
2917        // writer
2918        synchronized (mPackages) {
2919            if (listUninstalled) {
2920                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2921            } else {
2922                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2923            }
2924
2925            Arrays.sort(keys);
2926            int i = getContinuationPoint(keys, lastRead);
2927            final int N = keys.length;
2928
2929            while (i < N) {
2930                final String packageName = keys[i++];
2931
2932                PackageInfo pi = null;
2933                if (listUninstalled) {
2934                    final PackageSetting ps = mSettings.mPackages.get(packageName);
2935                    if (ps != null) {
2936                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
2937                    }
2938                } else {
2939                    final PackageParser.Package p = mPackages.get(packageName);
2940                    if (p != null) {
2941                        pi = generatePackageInfo(p, flags, userId);
2942                    }
2943                }
2944
2945                if (pi != null && list.append(pi)) {
2946                    break;
2947                }
2948            }
2949
2950            if (i == N) {
2951                list.setLastSlice(true);
2952            }
2953        }
2954
2955        return list;
2956    }
2957
2958    @Override
2959    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
2960            String lastRead, int userId) {
2961        if (!sUserManager.exists(userId)) return null;
2962        final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
2963        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
2964        final String[] keys;
2965
2966        // writer
2967        synchronized (mPackages) {
2968            if (listUninstalled) {
2969                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
2970            } else {
2971                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
2972            }
2973
2974            Arrays.sort(keys);
2975            int i = getContinuationPoint(keys, lastRead);
2976            final int N = keys.length;
2977
2978            while (i < N) {
2979                final String packageName = keys[i++];
2980
2981                ApplicationInfo ai = null;
2982                final PackageSetting ps = mSettings.mPackages.get(packageName);
2983                if (listUninstalled) {
2984                    if (ps != null) {
2985                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
2986                    }
2987                } else {
2988                    final PackageParser.Package p = mPackages.get(packageName);
2989                    if (p != null && ps != null) {
2990                        ai = PackageParser.generateApplicationInfo(p, flags,
2991                                ps.readUserState(userId), userId);
2992                    }
2993                }
2994
2995                if (ai != null && list.append(ai)) {
2996                    break;
2997                }
2998            }
2999
3000            if (i == N) {
3001                list.setLastSlice(true);
3002            }
3003        }
3004
3005        return list;
3006    }
3007
3008    public List<ApplicationInfo> getPersistentApplications(int flags) {
3009        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3010
3011        // reader
3012        synchronized (mPackages) {
3013            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3014            final int userId = UserHandle.getCallingUserId();
3015            while (i.hasNext()) {
3016                final PackageParser.Package p = i.next();
3017                if (p.applicationInfo != null
3018                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3019                        && (!mSafeMode || isSystemApp(p))) {
3020                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3021                    if (ps != null) {
3022                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3023                                ps.readUserState(userId), userId);
3024                        if (ai != null) {
3025                            finalList.add(ai);
3026                        }
3027                    }
3028                }
3029            }
3030        }
3031
3032        return finalList;
3033    }
3034
3035    @Override
3036    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3037        if (!sUserManager.exists(userId)) return null;
3038        // reader
3039        synchronized (mPackages) {
3040            final PackageParser.Provider provider = mProviders.get(name);
3041            PackageSetting ps = provider != null
3042                    ? mSettings.mPackages.get(provider.owner.packageName)
3043                    : null;
3044            return ps != null
3045                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3046                    && (!mSafeMode || (provider.info.applicationInfo.flags
3047                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3048                    ? PackageParser.generateProviderInfo(provider, flags,
3049                            ps.readUserState(userId), userId)
3050                    : null;
3051        }
3052    }
3053
3054    /**
3055     * @deprecated
3056     */
3057    @Deprecated
3058    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3059        // reader
3060        synchronized (mPackages) {
3061            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
3062                    .iterator();
3063            final int userId = UserHandle.getCallingUserId();
3064            while (i.hasNext()) {
3065                Map.Entry<String, PackageParser.Provider> entry = i.next();
3066                PackageParser.Provider p = entry.getValue();
3067                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3068
3069                if (ps != null && p.syncable
3070                        && (!mSafeMode || (p.info.applicationInfo.flags
3071                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3072                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3073                            ps.readUserState(userId), userId);
3074                    if (info != null) {
3075                        outNames.add(entry.getKey());
3076                        outInfo.add(info);
3077                    }
3078                }
3079            }
3080        }
3081    }
3082
3083    public List<ProviderInfo> queryContentProviders(String processName,
3084            int uid, int flags) {
3085        ArrayList<ProviderInfo> finalList = null;
3086
3087        // reader
3088        synchronized (mPackages) {
3089            final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
3090            final int userId = processName != null ?
3091                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3092            while (i.hasNext()) {
3093                final PackageParser.Provider p = i.next();
3094                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3095                if (ps != null && p.info.authority != null
3096                        && (processName == null
3097                                || (p.info.processName.equals(processName)
3098                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3099                        && mSettings.isEnabledLPr(p.info, flags, userId)
3100                        && (!mSafeMode
3101                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3102                    if (finalList == null) {
3103                        finalList = new ArrayList<ProviderInfo>(3);
3104                    }
3105                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3106                            ps.readUserState(userId), userId);
3107                    if (info != null) {
3108                        finalList.add(info);
3109                    }
3110                }
3111            }
3112        }
3113
3114        if (finalList != null) {
3115            Collections.sort(finalList, mProviderInitOrderSorter);
3116        }
3117
3118        return finalList;
3119    }
3120
3121    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3122            int flags) {
3123        // reader
3124        synchronized (mPackages) {
3125            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3126            return PackageParser.generateInstrumentationInfo(i, flags);
3127        }
3128    }
3129
3130    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3131            int flags) {
3132        ArrayList<InstrumentationInfo> finalList =
3133            new ArrayList<InstrumentationInfo>();
3134
3135        // reader
3136        synchronized (mPackages) {
3137            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3138            while (i.hasNext()) {
3139                final PackageParser.Instrumentation p = i.next();
3140                if (targetPackage == null
3141                        || targetPackage.equals(p.info.targetPackage)) {
3142                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3143                            flags);
3144                    if (ii != null) {
3145                        finalList.add(ii);
3146                    }
3147                }
3148            }
3149        }
3150
3151        return finalList;
3152    }
3153
3154    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
3155        String[] files = dir.list();
3156        if (files == null) {
3157            Log.d(TAG, "No files in app dir " + dir);
3158            return;
3159        }
3160
3161        if (DEBUG_PACKAGE_SCANNING) {
3162            Log.d(TAG, "Scanning app dir " + dir);
3163        }
3164
3165        int i;
3166        for (i=0; i<files.length; i++) {
3167            File file = new File(dir, files[i]);
3168            if (!isPackageFilename(files[i])) {
3169                // Ignore entries which are not apk's
3170                continue;
3171            }
3172            PackageParser.Package pkg = scanPackageLI(file,
3173                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
3174            // Don't mess around with apps in system partition.
3175            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
3176                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
3177                // Delete the apk
3178                Slog.w(TAG, "Cleaning up failed install of " + file);
3179                file.delete();
3180            }
3181        }
3182    }
3183
3184    private static File getSettingsProblemFile() {
3185        File dataDir = Environment.getDataDirectory();
3186        File systemDir = new File(dataDir, "system");
3187        File fname = new File(systemDir, "uiderrors.txt");
3188        return fname;
3189    }
3190
3191    static void reportSettingsProblem(int priority, String msg) {
3192        try {
3193            File fname = getSettingsProblemFile();
3194            FileOutputStream out = new FileOutputStream(fname, true);
3195            PrintWriter pw = new PrintWriter(out);
3196            SimpleDateFormat formatter = new SimpleDateFormat();
3197            String dateString = formatter.format(new Date(System.currentTimeMillis()));
3198            pw.println(dateString + ": " + msg);
3199            pw.close();
3200            FileUtils.setPermissions(
3201                    fname.toString(),
3202                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
3203                    -1, -1);
3204        } catch (java.io.IOException e) {
3205        }
3206        Slog.println(priority, TAG, msg);
3207    }
3208
3209    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
3210            PackageParser.Package pkg, File srcFile, int parseFlags) {
3211        if (GET_CERTIFICATES) {
3212            if (ps != null
3213                    && ps.codePath.equals(srcFile)
3214                    && ps.timeStamp == srcFile.lastModified()) {
3215                if (ps.signatures.mSignatures != null
3216                        && ps.signatures.mSignatures.length != 0) {
3217                    // Optimization: reuse the existing cached certificates
3218                    // if the package appears to be unchanged.
3219                    pkg.mSignatures = ps.signatures.mSignatures;
3220                    return true;
3221                }
3222
3223                Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
3224            } else {
3225                Log.i(TAG, srcFile.toString() + " changed; collecting certs");
3226            }
3227
3228            if (!pp.collectCertificates(pkg, parseFlags)) {
3229                mLastScanError = pp.getParseError();
3230                return false;
3231            }
3232        }
3233        return true;
3234    }
3235
3236    /*
3237     *  Scan a package and return the newly parsed package.
3238     *  Returns null in case of errors and the error code is stored in mLastScanError
3239     */
3240    private PackageParser.Package scanPackageLI(File scanFile,
3241            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3242        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3243        String scanPath = scanFile.getPath();
3244        parseFlags |= mDefParseFlags;
3245        PackageParser pp = new PackageParser(scanPath);
3246        pp.setSeparateProcesses(mSeparateProcesses);
3247        pp.setOnlyCoreApps(mOnlyCore);
3248        final PackageParser.Package pkg = pp.parsePackage(scanFile,
3249                scanPath, mMetrics, parseFlags);
3250        if (pkg == null) {
3251            mLastScanError = pp.getParseError();
3252            return null;
3253        }
3254        PackageSetting ps = null;
3255        PackageSetting updatedPkg;
3256        // reader
3257        synchronized (mPackages) {
3258            // Look to see if we already know about this package.
3259            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
3260            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
3261                // This package has been renamed to its original name.  Let's
3262                // use that.
3263                ps = mSettings.peekPackageLPr(oldName);
3264            }
3265            // If there was no original package, see one for the real package name.
3266            if (ps == null) {
3267                ps = mSettings.peekPackageLPr(pkg.packageName);
3268            }
3269            // Check to see if this package could be hiding/updating a system
3270            // package.  Must look for it either under the original or real
3271            // package name depending on our state.
3272            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
3273        }
3274        // First check if this is a system package that may involve an update
3275        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3276            if (ps != null && !ps.codePath.equals(scanFile)) {
3277                // The path has changed from what was last scanned...  check the
3278                // version of the new path against what we have stored to determine
3279                // what to do.
3280                if (pkg.mVersionCode < ps.versionCode) {
3281                    // The system package has been updated and the code path does not match
3282                    // Ignore entry. Skip it.
3283                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
3284                            + " ignored: updated version " + ps.versionCode
3285                            + " better than this " + pkg.mVersionCode);
3286                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3287                    return null;
3288                } else {
3289                    // The current app on the system partion is better than
3290                    // what we have updated to on the data partition; switch
3291                    // back to the system partition version.
3292                    // At this point, its safely assumed that package installation for
3293                    // apps in system partition will go through. If not there won't be a working
3294                    // version of the app
3295                    // writer
3296                    synchronized (mPackages) {
3297                        // Just remove the loaded entries from package lists.
3298                        mPackages.remove(ps.name);
3299                    }
3300                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
3301                            + "reverting from " + ps.codePathString
3302                            + ": new version " + pkg.mVersionCode
3303                            + " better than installed " + ps.versionCode);
3304
3305                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3306                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3307                    synchronized (mInstallLock) {
3308                        args.cleanUpResourcesLI();
3309                    }
3310                    synchronized (mPackages) {
3311                        mSettings.enableSystemPackageLPw(ps.name);
3312                    }
3313                }
3314            }
3315        }
3316
3317        if (updatedPkg != null) {
3318            // An updated system app will not have the PARSE_IS_SYSTEM flag set
3319            // initially
3320            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
3321        }
3322        // Verify certificates against what was last scanned
3323        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
3324            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
3325            return null;
3326        }
3327
3328        /*
3329         * A new system app appeared, but we already had a non-system one of the
3330         * same name installed earlier.
3331         */
3332        boolean shouldHideSystemApp = false;
3333        if (updatedPkg == null && ps != null
3334                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
3335            /*
3336             * Check to make sure the signatures match first. If they don't,
3337             * wipe the installed application and its data.
3338             */
3339            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
3340                    != PackageManager.SIGNATURE_MATCH) {
3341                deletePackageLI(pkg.packageName, null, true, 0, null, false);
3342                ps = null;
3343            } else {
3344                /*
3345                 * If the newly-added system app is an older version than the
3346                 * already installed version, hide it. It will be scanned later
3347                 * and re-added like an update.
3348                 */
3349                if (pkg.mVersionCode < ps.versionCode) {
3350                    shouldHideSystemApp = true;
3351                } else {
3352                    /*
3353                     * The newly found system app is a newer version that the
3354                     * one previously installed. Simply remove the
3355                     * already-installed application and replace it with our own
3356                     * while keeping the application data.
3357                     */
3358                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
3359                            + ps.codePathString + ": new version " + pkg.mVersionCode
3360                            + " better than installed " + ps.versionCode);
3361                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
3362                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
3363                    synchronized (mInstallLock) {
3364                        args.cleanUpResourcesLI();
3365                    }
3366                }
3367            }
3368        }
3369
3370        // The apk is forward locked (not public) if its code and resources
3371        // are kept in different files.
3372        // TODO grab this value from PackageSettings
3373        if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
3374            parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
3375        }
3376
3377        String codePath = null;
3378        String resPath = null;
3379        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
3380            if (ps != null && ps.resourcePathString != null) {
3381                resPath = ps.resourcePathString;
3382            } else {
3383                // Should not happen at all. Just log an error.
3384                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
3385            }
3386        } else {
3387            resPath = pkg.mScanPath;
3388        }
3389        codePath = pkg.mScanPath;
3390        // Set application objects path explicitly.
3391        setApplicationInfoPaths(pkg, codePath, resPath);
3392        // Note that we invoke the following method only if we are about to unpack an application
3393        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
3394                | SCAN_UPDATE_SIGNATURE, currentTime, user);
3395
3396        /*
3397         * If the system app should be overridden by a previously installed
3398         * data, hide the system app now and let the /data/app scan pick it up
3399         * again.
3400         */
3401        if (shouldHideSystemApp) {
3402            synchronized (mPackages) {
3403                /*
3404                 * We have to grant systems permissions before we hide, because
3405                 * grantPermissions will assume the package update is trying to
3406                 * expand its permissions.
3407                 */
3408                grantPermissionsLPw(pkg, true);
3409                mSettings.disableSystemPackageLPw(pkg.packageName);
3410            }
3411        }
3412
3413        return scannedPkg;
3414    }
3415
3416    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
3417            String destResPath) {
3418        pkg.mPath = pkg.mScanPath = destCodePath;
3419        pkg.applicationInfo.sourceDir = destCodePath;
3420        pkg.applicationInfo.publicSourceDir = destResPath;
3421    }
3422
3423    private static String fixProcessName(String defProcessName,
3424            String processName, int uid) {
3425        if (processName == null) {
3426            return defProcessName;
3427        }
3428        return processName;
3429    }
3430
3431    private boolean verifySignaturesLP(PackageSetting pkgSetting,
3432            PackageParser.Package pkg) {
3433        if (pkgSetting.signatures.mSignatures != null) {
3434            // Already existing package. Make sure signatures match
3435            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
3436                PackageManager.SIGNATURE_MATCH) {
3437                    Slog.e(TAG, "Package " + pkg.packageName
3438                            + " signatures do not match the previously installed version; ignoring!");
3439                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3440                    return false;
3441                }
3442        }
3443        // Check for shared user signatures
3444        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
3445            if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3446                    pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3447                Slog.e(TAG, "Package " + pkg.packageName
3448                        + " has no signatures that match those in shared user "
3449                        + pkgSetting.sharedUser.name + "; ignoring!");
3450                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
3451                return false;
3452            }
3453        }
3454        return true;
3455    }
3456
3457    /**
3458     * Enforces that only the system UID or root's UID can call a method exposed
3459     * via Binder.
3460     *
3461     * @param message used as message if SecurityException is thrown
3462     * @throws SecurityException if the caller is not system or root
3463     */
3464    private static final void enforceSystemOrRoot(String message) {
3465        final int uid = Binder.getCallingUid();
3466        if (uid != Process.SYSTEM_UID && uid != 0) {
3467            throw new SecurityException(message);
3468        }
3469    }
3470
3471    public void performBootDexOpt() {
3472        ArrayList<PackageParser.Package> pkgs = null;
3473        synchronized (mPackages) {
3474            if (mDeferredDexOpt.size() > 0) {
3475                pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt);
3476                mDeferredDexOpt.clear();
3477            }
3478        }
3479        if (pkgs != null) {
3480            for (int i=0; i<pkgs.size(); i++) {
3481                if (!isFirstBoot()) {
3482                    try {
3483                        ActivityManagerNative.getDefault().showBootMessage(
3484                                mContext.getResources().getString(
3485                                        com.android.internal.R.string.android_upgrading_apk,
3486                                        i+1, pkgs.size()), true);
3487                    } catch (RemoteException e) {
3488                    }
3489                }
3490                PackageParser.Package p = pkgs.get(i);
3491                synchronized (mInstallLock) {
3492                    if (!p.mDidDexOpt) {
3493                        performDexOptLI(p, false, false);
3494                    }
3495                }
3496            }
3497        }
3498    }
3499
3500    public boolean performDexOpt(String packageName) {
3501        enforceSystemOrRoot("Only the system can request dexopt be performed");
3502
3503        if (!mNoDexOpt) {
3504            return false;
3505        }
3506
3507        PackageParser.Package p;
3508        synchronized (mPackages) {
3509            p = mPackages.get(packageName);
3510            if (p == null || p.mDidDexOpt) {
3511                return false;
3512            }
3513        }
3514        synchronized (mInstallLock) {
3515            return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED;
3516        }
3517    }
3518
3519    static final int DEX_OPT_SKIPPED = 0;
3520    static final int DEX_OPT_PERFORMED = 1;
3521    static final int DEX_OPT_DEFERRED = 2;
3522    static final int DEX_OPT_FAILED = -1;
3523
3524    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) {
3525        boolean performed = false;
3526        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3527            String path = pkg.mScanPath;
3528            int ret = 0;
3529            try {
3530                if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
3531                    if (!forceDex && defer) {
3532                        mDeferredDexOpt.add(pkg);
3533                        return DEX_OPT_DEFERRED;
3534                    } else {
3535                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
3536                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3537                        ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
3538                        pkg.mDidDexOpt = true;
3539                        performed = true;
3540                    }
3541                }
3542            } catch (FileNotFoundException e) {
3543                Slog.w(TAG, "Apk not found for dexopt: " + path);
3544                ret = -1;
3545            } catch (IOException e) {
3546                Slog.w(TAG, "IOException reading apk: " + path, e);
3547                ret = -1;
3548            } catch (dalvik.system.StaleDexCacheError e) {
3549                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
3550                ret = -1;
3551            } catch (Exception e) {
3552                Slog.w(TAG, "Exception when doing dexopt : ", e);
3553                ret = -1;
3554            }
3555            if (ret < 0) {
3556                //error from installer
3557                return DEX_OPT_FAILED;
3558            }
3559        }
3560
3561        return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
3562    }
3563
3564    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
3565        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
3566            Slog.w(TAG, "Unable to update from " + oldPkg.name
3567                    + " to " + newPkg.packageName
3568                    + ": old package not in system partition");
3569            return false;
3570        } else if (mPackages.get(oldPkg.name) != null) {
3571            Slog.w(TAG, "Unable to update from " + oldPkg.name
3572                    + " to " + newPkg.packageName
3573                    + ": old package still exists");
3574            return false;
3575        }
3576        return true;
3577    }
3578
3579    File getDataPathForUser(int userId) {
3580        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
3581    }
3582
3583    private File getDataPathForPackage(String packageName, int userId) {
3584        /*
3585         * Until we fully support multiple users, return the directory we
3586         * previously would have. The PackageManagerTests will need to be
3587         * revised when this is changed back..
3588         */
3589        if (userId == 0) {
3590            return new File(mAppDataDir, packageName);
3591        } else {
3592            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
3593                + File.separator + packageName);
3594        }
3595    }
3596
3597    private int createDataDirsLI(String packageName, int uid) {
3598        int[] users = sUserManager.getUserIds();
3599        int res = mInstaller.install(packageName, uid, uid);
3600        if (res < 0) {
3601            return res;
3602        }
3603        for (int user : users) {
3604            if (user != 0) {
3605                res = mInstaller.createUserData(packageName,
3606                        UserHandle.getUid(user, uid), user);
3607                if (res < 0) {
3608                    return res;
3609                }
3610            }
3611        }
3612        return res;
3613    }
3614
3615    private int removeDataDirsLI(String packageName) {
3616        int[] users = sUserManager.getUserIds();
3617        int res = 0;
3618        for (int user : users) {
3619            int resInner = mInstaller.remove(packageName, user);
3620            if (resInner < 0) {
3621                res = resInner;
3622            }
3623        }
3624
3625        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
3626        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
3627        if (!nativeLibraryFile.delete()) {
3628            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
3629        }
3630
3631        return res;
3632    }
3633
3634    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
3635            int parseFlags, int scanMode, long currentTime, UserHandle user) {
3636        File scanFile = new File(pkg.mScanPath);
3637        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
3638                pkg.applicationInfo.publicSourceDir == null) {
3639            // Bail out. The resource and code paths haven't been set.
3640            Slog.w(TAG, " Code and resource paths haven't been set correctly");
3641            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
3642            return null;
3643        }
3644        mScanningPath = scanFile;
3645
3646        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3647            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
3648        }
3649
3650        if (pkg.packageName.equals("android")) {
3651            synchronized (mPackages) {
3652                if (mAndroidApplication != null) {
3653                    Slog.w(TAG, "*************************************************");
3654                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
3655                    Slog.w(TAG, " file=" + mScanningPath);
3656                    Slog.w(TAG, "*************************************************");
3657                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3658                    return null;
3659                }
3660
3661                // Set up information for our fall-back user intent resolution
3662                // activity.
3663                mPlatformPackage = pkg;
3664                pkg.mVersionCode = mSdkVersion;
3665                mAndroidApplication = pkg.applicationInfo;
3666                mResolveActivity.applicationInfo = mAndroidApplication;
3667                mResolveActivity.name = ResolverActivity.class.getName();
3668                mResolveActivity.packageName = mAndroidApplication.packageName;
3669                mResolveActivity.processName = "system:ui";
3670                mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
3671                mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
3672                mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
3673                mResolveActivity.exported = true;
3674                mResolveActivity.enabled = true;
3675                mResolveInfo.activityInfo = mResolveActivity;
3676                mResolveInfo.priority = 0;
3677                mResolveInfo.preferredOrder = 0;
3678                mResolveInfo.match = 0;
3679                mResolveComponentName = new ComponentName(
3680                        mAndroidApplication.packageName, mResolveActivity.name);
3681            }
3682        }
3683
3684        if (DEBUG_PACKAGE_SCANNING) {
3685            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3686                Log.d(TAG, "Scanning package " + pkg.packageName);
3687        }
3688
3689        if (mPackages.containsKey(pkg.packageName)
3690                || mSharedLibraries.containsKey(pkg.packageName)) {
3691            Slog.w(TAG, "Application package " + pkg.packageName
3692                    + " already installed.  Skipping duplicate.");
3693            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
3694            return null;
3695        }
3696
3697        // Initialize package source and resource directories
3698        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
3699        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
3700
3701        SharedUserSetting suid = null;
3702        PackageSetting pkgSetting = null;
3703
3704        if (!isSystemApp(pkg)) {
3705            // Only system apps can use these features.
3706            pkg.mOriginalPackages = null;
3707            pkg.mRealPackage = null;
3708            pkg.mAdoptPermissions = null;
3709        }
3710
3711        // writer
3712        synchronized (mPackages) {
3713            // Check all shared libraries and map to their actual file path.
3714            if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
3715                if (mTmpSharedLibraries == null ||
3716                        mTmpSharedLibraries.length < mSharedLibraries.size()) {
3717                    mTmpSharedLibraries = new String[mSharedLibraries.size()];
3718                }
3719                int num = 0;
3720                int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
3721                for (int i=0; i<N; i++) {
3722                    final String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
3723                    if (file == null) {
3724                        Slog.e(TAG, "Package " + pkg.packageName
3725                                + " requires unavailable shared library "
3726                                + pkg.usesLibraries.get(i) + "; failing!");
3727                        mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
3728                        return null;
3729                    }
3730                    mTmpSharedLibraries[num] = file;
3731                    num++;
3732                }
3733                N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
3734                for (int i=0; i<N; i++) {
3735                    final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
3736                    if (file == null) {
3737                        Slog.w(TAG, "Package " + pkg.packageName
3738                                + " desires unavailable shared library "
3739                                + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
3740                    } else {
3741                        mTmpSharedLibraries[num] = file;
3742                        num++;
3743                    }
3744                }
3745                if (num > 0) {
3746                    pkg.usesLibraryFiles = new String[num];
3747                    System.arraycopy(mTmpSharedLibraries, 0,
3748                            pkg.usesLibraryFiles, 0, num);
3749                }
3750            }
3751
3752            if (pkg.mSharedUserId != null) {
3753                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
3754                        pkg.applicationInfo.flags, true);
3755                if (suid == null) {
3756                    Slog.w(TAG, "Creating application package " + pkg.packageName
3757                            + " for shared user failed");
3758                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3759                    return null;
3760                }
3761                if (DEBUG_PACKAGE_SCANNING) {
3762                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
3763                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
3764                                + "): packages=" + suid.packages);
3765                }
3766            }
3767
3768            // Check if we are renaming from an original package name.
3769            PackageSetting origPackage = null;
3770            String realName = null;
3771            if (pkg.mOriginalPackages != null) {
3772                // This package may need to be renamed to a previously
3773                // installed name.  Let's check on that...
3774                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
3775                if (pkg.mOriginalPackages.contains(renamed)) {
3776                    // This package had originally been installed as the
3777                    // original name, and we have already taken care of
3778                    // transitioning to the new one.  Just update the new
3779                    // one to continue using the old name.
3780                    realName = pkg.mRealPackage;
3781                    if (!pkg.packageName.equals(renamed)) {
3782                        // Callers into this function may have already taken
3783                        // care of renaming the package; only do it here if
3784                        // it is not already done.
3785                        pkg.setPackageName(renamed);
3786                    }
3787
3788                } else {
3789                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
3790                        if ((origPackage = mSettings.peekPackageLPr(
3791                                pkg.mOriginalPackages.get(i))) != null) {
3792                            // We do have the package already installed under its
3793                            // original name...  should we use it?
3794                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
3795                                // New package is not compatible with original.
3796                                origPackage = null;
3797                                continue;
3798                            } else if (origPackage.sharedUser != null) {
3799                                // Make sure uid is compatible between packages.
3800                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
3801                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
3802                                            + " to " + pkg.packageName + ": old uid "
3803                                            + origPackage.sharedUser.name
3804                                            + " differs from " + pkg.mSharedUserId);
3805                                    origPackage = null;
3806                                    continue;
3807                                }
3808                            } else {
3809                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3810                                        + pkg.packageName + " to old name " + origPackage.name);
3811                            }
3812                            break;
3813                        }
3814                    }
3815                }
3816            }
3817
3818            if (mTransferedPackages.contains(pkg.packageName)) {
3819                Slog.w(TAG, "Package " + pkg.packageName
3820                        + " was transferred to another, but its .apk remains");
3821            }
3822
3823            // Just create the setting, don't add it yet. For already existing packages
3824            // the PkgSetting exists already and doesn't have to be created.
3825            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
3826                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3827                    pkg.applicationInfo.flags, user, false);
3828            if (pkgSetting == null) {
3829                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
3830                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3831                return null;
3832            }
3833
3834            if (pkgSetting.origPackage != null) {
3835                // If we are first transitioning from an original package,
3836                // fix up the new package's name now.  We need to do this after
3837                // looking up the package under its new name, so getPackageLP
3838                // can take care of fiddling things correctly.
3839                pkg.setPackageName(origPackage.name);
3840
3841                // File a report about this.
3842                String msg = "New package " + pkgSetting.realName
3843                        + " renamed to replace old package " + pkgSetting.name;
3844                reportSettingsProblem(Log.WARN, msg);
3845
3846                // Make a note of it.
3847                mTransferedPackages.add(origPackage.name);
3848
3849                // No longer need to retain this.
3850                pkgSetting.origPackage = null;
3851            }
3852
3853            if (realName != null) {
3854                // Make a note of it.
3855                mTransferedPackages.add(pkg.packageName);
3856            }
3857
3858            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
3859                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3860            }
3861
3862            pkg.applicationInfo.uid = pkgSetting.appId;
3863            pkg.mExtras = pkgSetting;
3864
3865            if (!verifySignaturesLP(pkgSetting, pkg)) {
3866                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
3867                    return null;
3868                }
3869                // The signature has changed, but this package is in the system
3870                // image...  let's recover!
3871                pkgSetting.signatures.mSignatures = pkg.mSignatures;
3872                // However...  if this package is part of a shared user, but it
3873                // doesn't match the signature of the shared user, let's fail.
3874                // What this means is that you can't change the signatures
3875                // associated with an overall shared user, which doesn't seem all
3876                // that unreasonable.
3877                if (pkgSetting.sharedUser != null) {
3878                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
3879                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3880                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
3881                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3882                        return null;
3883                    }
3884                }
3885                // File a report about this.
3886                String msg = "System package " + pkg.packageName
3887                        + " signature changed; retaining data.";
3888                reportSettingsProblem(Log.WARN, msg);
3889            }
3890
3891            // Verify that this new package doesn't have any content providers
3892            // that conflict with existing packages.  Only do this if the
3893            // package isn't already installed, since we don't want to break
3894            // things that are installed.
3895            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3896                final int N = pkg.providers.size();
3897                int i;
3898                for (i=0; i<N; i++) {
3899                    PackageParser.Provider p = pkg.providers.get(i);
3900                    if (p.info.authority != null) {
3901                        String names[] = p.info.authority.split(";");
3902                        for (int j = 0; j < names.length; j++) {
3903                            if (mProviders.containsKey(names[j])) {
3904                                PackageParser.Provider other = mProviders.get(names[j]);
3905                                Slog.w(TAG, "Can't install because provider name " + names[j] +
3906                                        " (in package " + pkg.applicationInfo.packageName +
3907                                        ") is already used by "
3908                                        + ((other != null && other.getComponentName() != null)
3909                                                ? other.getComponentName().getPackageName() : "?"));
3910                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3911                                return null;
3912                            }
3913                        }
3914                    }
3915                }
3916            }
3917
3918            if (pkg.mAdoptPermissions != null) {
3919                // This package wants to adopt ownership of permissions from
3920                // another package.
3921                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
3922                    final String origName = pkg.mAdoptPermissions.get(i);
3923                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
3924                    if (orig != null) {
3925                        if (verifyPackageUpdateLPr(orig, pkg)) {
3926                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
3927                                    + pkg.packageName);
3928                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
3929                        }
3930                    }
3931                }
3932            }
3933        }
3934
3935        final String pkgName = pkg.packageName;
3936
3937        final long scanFileTime = scanFile.lastModified();
3938        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3939        pkg.applicationInfo.processName = fixProcessName(
3940                pkg.applicationInfo.packageName,
3941                pkg.applicationInfo.processName,
3942                pkg.applicationInfo.uid);
3943
3944        File dataPath;
3945        if (mPlatformPackage == pkg) {
3946            // The system package is special.
3947            dataPath = new File (Environment.getDataDirectory(), "system");
3948            pkg.applicationInfo.dataDir = dataPath.getPath();
3949        } else {
3950            // This is a normal package, need to make its data directory.
3951            dataPath = getDataPathForPackage(pkg.packageName, 0);
3952
3953            boolean uidError = false;
3954
3955            if (dataPath.exists()) {
3956                int currentUid = 0;
3957                try {
3958                    StructStat stat = Libcore.os.stat(dataPath.getPath());
3959                    currentUid = stat.st_uid;
3960                } catch (ErrnoException e) {
3961                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
3962                }
3963
3964                // If we have mismatched owners for the data path, we have a problem.
3965                if (currentUid != pkg.applicationInfo.uid) {
3966                    boolean recovered = false;
3967                    if (currentUid == 0) {
3968                        // The directory somehow became owned by root.  Wow.
3969                        // This is probably because the system was stopped while
3970                        // installd was in the middle of messing with its libs
3971                        // directory.  Ask installd to fix that.
3972                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
3973                                pkg.applicationInfo.uid);
3974                        if (ret >= 0) {
3975                            recovered = true;
3976                            String msg = "Package " + pkg.packageName
3977                                    + " unexpectedly changed to uid 0; recovered to " +
3978                                    + pkg.applicationInfo.uid;
3979                            reportSettingsProblem(Log.WARN, msg);
3980                        }
3981                    }
3982                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3983                            || (scanMode&SCAN_BOOTING) != 0)) {
3984                        // If this is a system app, we can at least delete its
3985                        // current data so the application will still work.
3986                        int ret = removeDataDirsLI(pkgName);
3987                        if (ret >= 0) {
3988                            // TODO: Kill the processes first
3989                            // Old data gone!
3990                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
3991                                    ? "System package " : "Third party package ";
3992                            String msg = prefix + pkg.packageName
3993                                    + " has changed from uid: "
3994                                    + currentUid + " to "
3995                                    + pkg.applicationInfo.uid + "; old data erased";
3996                            reportSettingsProblem(Log.WARN, msg);
3997                            recovered = true;
3998
3999                            // And now re-install the app.
4000                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
4001                            if (ret == -1) {
4002                                // Ack should not happen!
4003                                msg = prefix + pkg.packageName
4004                                        + " could not have data directory re-created after delete.";
4005                                reportSettingsProblem(Log.WARN, msg);
4006                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4007                                return null;
4008                            }
4009                        }
4010                        if (!recovered) {
4011                            mHasSystemUidErrors = true;
4012                        }
4013                    } else if (!recovered) {
4014                        // If we allow this install to proceed, we will be broken.
4015                        // Abort, abort!
4016                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
4017                        return null;
4018                    }
4019                    if (!recovered) {
4020                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
4021                            + pkg.applicationInfo.uid + "/fs_"
4022                            + currentUid;
4023                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
4024                        String msg = "Package " + pkg.packageName
4025                                + " has mismatched uid: "
4026                                + currentUid + " on disk, "
4027                                + pkg.applicationInfo.uid + " in settings";
4028                        // writer
4029                        synchronized (mPackages) {
4030                            mSettings.mReadMessages.append(msg);
4031                            mSettings.mReadMessages.append('\n');
4032                            uidError = true;
4033                            if (!pkgSetting.uidError) {
4034                                reportSettingsProblem(Log.ERROR, msg);
4035                            }
4036                        }
4037                    }
4038                }
4039                pkg.applicationInfo.dataDir = dataPath.getPath();
4040            } else {
4041                if (DEBUG_PACKAGE_SCANNING) {
4042                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4043                        Log.v(TAG, "Want this data dir: " + dataPath);
4044                }
4045                //invoke installer to do the actual installation
4046                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid);
4047                if (ret < 0) {
4048                    // Error from installer
4049                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4050                    return null;
4051                }
4052
4053                if (dataPath.exists()) {
4054                    pkg.applicationInfo.dataDir = dataPath.getPath();
4055                } else {
4056                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
4057                    pkg.applicationInfo.dataDir = null;
4058                }
4059            }
4060
4061            /*
4062             * Set the data dir to the default "/data/data/<package name>/lib"
4063             * if we got here without anyone telling us different (e.g., apps
4064             * stored on SD card have their native libraries stored in the ASEC
4065             * container with the APK).
4066             *
4067             * This happens during an upgrade from a package settings file that
4068             * doesn't have a native library path attribute at all.
4069             */
4070            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
4071                if (pkgSetting.nativeLibraryPathString == null) {
4072                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
4073                } else {
4074                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
4075                }
4076            }
4077
4078            pkgSetting.uidError = uidError;
4079        }
4080
4081        String path = scanFile.getPath();
4082        /* Note: We don't want to unpack the native binaries for
4083         *        system applications, unless they have been updated
4084         *        (the binaries are already under /system/lib).
4085         *        Also, don't unpack libs for apps on the external card
4086         *        since they should have their libraries in the ASEC
4087         *        container already.
4088         *
4089         *        In other words, we're going to unpack the binaries
4090         *        only for non-system apps and system app upgrades.
4091         */
4092        if (pkg.applicationInfo.nativeLibraryDir != null) {
4093            try {
4094                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4095                final String dataPathString = dataPath.getCanonicalPath();
4096
4097                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4098                    /*
4099                     * Upgrading from a previous version of the OS sometimes
4100                     * leaves native libraries in the /data/data/<app>/lib
4101                     * directory for system apps even when they shouldn't be.
4102                     * Recent changes in the JNI library search path
4103                     * necessitates we remove those to match previous behavior.
4104                     */
4105                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
4106                        Log.i(TAG, "removed obsolete native libraries for system package "
4107                                + path);
4108                    }
4109                } else if (!isForwardLocked(pkg) && !isExternal(pkg)) {
4110                    // Update native library dir if it starts with /data/data
4111                    if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
4112                        setInternalAppNativeLibraryPath(pkg, pkgSetting);
4113                        nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
4114                    }
4115
4116                    try {
4117                        if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
4118                            Slog.e(TAG, "Unable to copy native libraries");
4119                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4120                            return null;
4121                        }
4122                    } catch (IOException e) {
4123                        Slog.e(TAG, "Unable to copy native libraries", e);
4124                        mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4125                        return null;
4126                    }
4127
4128                    if (mInstaller.linkNativeLibraryDirectory(dataPathString,
4129                            pkg.applicationInfo.nativeLibraryDir) == -1) {
4130                        Slog.e(TAG, "Unable to link native library directory");
4131                        mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4132                        return null;
4133                    }
4134                } else {
4135                    Slog.i(TAG, "Linking native library dir for " + path);
4136                    int ret = mInstaller.linkNativeLibraryDirectory(dataPathString,
4137                            pkg.applicationInfo.nativeLibraryDir);
4138                    if (ret < 0) {
4139                        Slog.w(TAG, "Failed linking native library dir for " + path);
4140                        mLastScanError = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4141                        return null;
4142                    }
4143                }
4144            } catch (IOException ioe) {
4145                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
4146            }
4147        }
4148        pkg.mScanPath = path;
4149
4150        if ((scanMode&SCAN_NO_DEX) == 0) {
4151            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0)
4152                    == DEX_OPT_FAILED) {
4153                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
4154                return null;
4155            }
4156        }
4157
4158        if (mFactoryTest && pkg.requestedPermissions.contains(
4159                android.Manifest.permission.FACTORY_TEST)) {
4160            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
4161        }
4162
4163        // Request the ActivityManager to kill the process(only for existing packages)
4164        // so that we do not end up in a confused state while the user is still using the older
4165        // version of the application while the new one gets installed.
4166        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4167            killApplication(pkg.applicationInfo.packageName,
4168                        pkg.applicationInfo.uid);
4169        }
4170
4171        // writer
4172        synchronized (mPackages) {
4173            // We don't expect installation to fail beyond this point,
4174            if ((scanMode&SCAN_MONITOR) != 0) {
4175                mAppDirs.put(pkg.mPath, pkg);
4176            }
4177            // Add the new setting to mSettings
4178            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
4179            // Add the new setting to mPackages
4180            mPackages.put(pkg.applicationInfo.packageName, pkg);
4181            // Make sure we don't accidentally delete its data.
4182            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
4183            while (iter.hasNext()) {
4184                PackageCleanItem item = iter.next();
4185                if (pkgName.equals(item.packageName)) {
4186                    iter.remove();
4187                }
4188            }
4189
4190            // Take care of first install / last update times.
4191            if (currentTime != 0) {
4192                if (pkgSetting.firstInstallTime == 0) {
4193                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
4194                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
4195                    pkgSetting.lastUpdateTime = currentTime;
4196                }
4197            } else if (pkgSetting.firstInstallTime == 0) {
4198                // We need *something*.  Take time time stamp of the file.
4199                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
4200            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
4201                if (scanFileTime != pkgSetting.timeStamp) {
4202                    // A package on the system image has changed; consider this
4203                    // to be an update.
4204                    pkgSetting.lastUpdateTime = scanFileTime;
4205                }
4206            }
4207
4208            int N = pkg.providers.size();
4209            StringBuilder r = null;
4210            int i;
4211            for (i=0; i<N; i++) {
4212                PackageParser.Provider p = pkg.providers.get(i);
4213                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
4214                        p.info.processName, pkg.applicationInfo.uid);
4215                mProvidersByComponent.put(new ComponentName(p.info.packageName,
4216                        p.info.name), p);
4217                p.syncable = p.info.isSyncable;
4218                if (p.info.authority != null) {
4219                    String names[] = p.info.authority.split(";");
4220                    p.info.authority = null;
4221                    for (int j = 0; j < names.length; j++) {
4222                        if (j == 1 && p.syncable) {
4223                            // We only want the first authority for a provider to possibly be
4224                            // syncable, so if we already added this provider using a different
4225                            // authority clear the syncable flag. We copy the provider before
4226                            // changing it because the mProviders object contains a reference
4227                            // to a provider that we don't want to change.
4228                            // Only do this for the second authority since the resulting provider
4229                            // object can be the same for all future authorities for this provider.
4230                            p = new PackageParser.Provider(p);
4231                            p.syncable = false;
4232                        }
4233                        if (!mProviders.containsKey(names[j])) {
4234                            mProviders.put(names[j], p);
4235                            if (p.info.authority == null) {
4236                                p.info.authority = names[j];
4237                            } else {
4238                                p.info.authority = p.info.authority + ";" + names[j];
4239                            }
4240                            if (DEBUG_PACKAGE_SCANNING) {
4241                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4242                                    Log.d(TAG, "Registered content provider: " + names[j]
4243                                            + ", className = " + p.info.name + ", isSyncable = "
4244                                            + p.info.isSyncable);
4245                            }
4246                        } else {
4247                            PackageParser.Provider other = mProviders.get(names[j]);
4248                            Slog.w(TAG, "Skipping provider name " + names[j] +
4249                                    " (in package " + pkg.applicationInfo.packageName +
4250                                    "): name already used by "
4251                                    + ((other != null && other.getComponentName() != null)
4252                                            ? other.getComponentName().getPackageName() : "?"));
4253                        }
4254                    }
4255                }
4256                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4257                    if (r == null) {
4258                        r = new StringBuilder(256);
4259                    } else {
4260                        r.append(' ');
4261                    }
4262                    r.append(p.info.name);
4263                }
4264            }
4265            if (r != null) {
4266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
4267            }
4268
4269            N = pkg.services.size();
4270            r = null;
4271            for (i=0; i<N; i++) {
4272                PackageParser.Service s = pkg.services.get(i);
4273                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
4274                        s.info.processName, pkg.applicationInfo.uid);
4275                mServices.addService(s);
4276                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4277                    if (r == null) {
4278                        r = new StringBuilder(256);
4279                    } else {
4280                        r.append(' ');
4281                    }
4282                    r.append(s.info.name);
4283                }
4284            }
4285            if (r != null) {
4286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
4287            }
4288
4289            N = pkg.receivers.size();
4290            r = null;
4291            for (i=0; i<N; i++) {
4292                PackageParser.Activity a = pkg.receivers.get(i);
4293                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4294                        a.info.processName, pkg.applicationInfo.uid);
4295                mReceivers.addActivity(a, "receiver");
4296                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4297                    if (r == null) {
4298                        r = new StringBuilder(256);
4299                    } else {
4300                        r.append(' ');
4301                    }
4302                    r.append(a.info.name);
4303                }
4304            }
4305            if (r != null) {
4306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
4307            }
4308
4309            N = pkg.activities.size();
4310            r = null;
4311            for (i=0; i<N; i++) {
4312                PackageParser.Activity a = pkg.activities.get(i);
4313                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
4314                        a.info.processName, pkg.applicationInfo.uid);
4315                mActivities.addActivity(a, "activity");
4316                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4317                    if (r == null) {
4318                        r = new StringBuilder(256);
4319                    } else {
4320                        r.append(' ');
4321                    }
4322                    r.append(a.info.name);
4323                }
4324            }
4325            if (r != null) {
4326                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
4327            }
4328
4329            N = pkg.permissionGroups.size();
4330            r = null;
4331            for (i=0; i<N; i++) {
4332                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
4333                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
4334                if (cur == null) {
4335                    mPermissionGroups.put(pg.info.name, pg);
4336                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4337                        if (r == null) {
4338                            r = new StringBuilder(256);
4339                        } else {
4340                            r.append(' ');
4341                        }
4342                        r.append(pg.info.name);
4343                    }
4344                } else {
4345                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
4346                            + pg.info.packageName + " ignored: original from "
4347                            + cur.info.packageName);
4348                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4349                        if (r == null) {
4350                            r = new StringBuilder(256);
4351                        } else {
4352                            r.append(' ');
4353                        }
4354                        r.append("DUP:");
4355                        r.append(pg.info.name);
4356                    }
4357                }
4358            }
4359            if (r != null) {
4360                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
4361            }
4362
4363            N = pkg.permissions.size();
4364            r = null;
4365            for (i=0; i<N; i++) {
4366                PackageParser.Permission p = pkg.permissions.get(i);
4367                HashMap<String, BasePermission> permissionMap =
4368                        p.tree ? mSettings.mPermissionTrees
4369                        : mSettings.mPermissions;
4370                p.group = mPermissionGroups.get(p.info.group);
4371                if (p.info.group == null || p.group != null) {
4372                    BasePermission bp = permissionMap.get(p.info.name);
4373                    if (bp == null) {
4374                        bp = new BasePermission(p.info.name, p.info.packageName,
4375                                BasePermission.TYPE_NORMAL);
4376                        permissionMap.put(p.info.name, bp);
4377                    }
4378                    if (bp.perm == null) {
4379                        if (bp.sourcePackage == null
4380                                || bp.sourcePackage.equals(p.info.packageName)) {
4381                            BasePermission tree = findPermissionTreeLP(p.info.name);
4382                            if (tree == null
4383                                    || tree.sourcePackage.equals(p.info.packageName)) {
4384                                bp.packageSetting = pkgSetting;
4385                                bp.perm = p;
4386                                bp.uid = pkg.applicationInfo.uid;
4387                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4388                                    if (r == null) {
4389                                        r = new StringBuilder(256);
4390                                    } else {
4391                                        r.append(' ');
4392                                    }
4393                                    r.append(p.info.name);
4394                                }
4395                            } else {
4396                                Slog.w(TAG, "Permission " + p.info.name + " from package "
4397                                        + p.info.packageName + " ignored: base tree "
4398                                        + tree.name + " is from package "
4399                                        + tree.sourcePackage);
4400                            }
4401                        } else {
4402                            Slog.w(TAG, "Permission " + p.info.name + " from package "
4403                                    + p.info.packageName + " ignored: original from "
4404                                    + bp.sourcePackage);
4405                        }
4406                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4407                        if (r == null) {
4408                            r = new StringBuilder(256);
4409                        } else {
4410                            r.append(' ');
4411                        }
4412                        r.append("DUP:");
4413                        r.append(p.info.name);
4414                    }
4415                    if (bp.perm == p) {
4416                        bp.protectionLevel = p.info.protectionLevel;
4417                    }
4418                } else {
4419                    Slog.w(TAG, "Permission " + p.info.name + " from package "
4420                            + p.info.packageName + " ignored: no group "
4421                            + p.group);
4422                }
4423            }
4424            if (r != null) {
4425                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
4426            }
4427
4428            N = pkg.instrumentation.size();
4429            r = null;
4430            for (i=0; i<N; i++) {
4431                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4432                a.info.packageName = pkg.applicationInfo.packageName;
4433                a.info.sourceDir = pkg.applicationInfo.sourceDir;
4434                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
4435                a.info.dataDir = pkg.applicationInfo.dataDir;
4436                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
4437                mInstrumentation.put(a.getComponentName(), a);
4438                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
4439                    if (r == null) {
4440                        r = new StringBuilder(256);
4441                    } else {
4442                        r.append(' ');
4443                    }
4444                    r.append(a.info.name);
4445                }
4446            }
4447            if (r != null) {
4448                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
4449            }
4450
4451            if (pkg.protectedBroadcasts != null) {
4452                N = pkg.protectedBroadcasts.size();
4453                for (i=0; i<N; i++) {
4454                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
4455                }
4456            }
4457
4458            pkgSetting.setTimeStamp(scanFileTime);
4459        }
4460
4461        return pkg;
4462    }
4463
4464    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
4465            PackageSetting pkgSetting) {
4466        final String apkLibPath = getApkName(pkgSetting.codePathString);
4467        final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
4468        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
4469        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
4470    }
4471
4472    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
4473            throws IOException {
4474        if (!nativeLibraryDir.isDirectory()) {
4475            nativeLibraryDir.delete();
4476
4477            if (!nativeLibraryDir.mkdir()) {
4478                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
4479            }
4480
4481            try {
4482                Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
4483                        | S_IXOTH);
4484            } catch (ErrnoException e) {
4485                throw new IOException("Cannot chmod native library directory "
4486                        + nativeLibraryDir.getPath(), e);
4487            }
4488        } else if (!SELinux.restorecon(nativeLibraryDir)) {
4489            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
4490        }
4491
4492        /*
4493         * If this is an internal application or our nativeLibraryPath points to
4494         * the app-lib directory, unpack the libraries if necessary.
4495         */
4496        return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
4497    }
4498
4499    private void killApplication(String pkgName, int appId) {
4500        // Request the ActivityManager to kill the process(only for existing packages)
4501        // so that we do not end up in a confused state while the user is still using the older
4502        // version of the application while the new one gets installed.
4503        IActivityManager am = ActivityManagerNative.getDefault();
4504        if (am != null) {
4505            try {
4506                am.killApplicationWithAppId(pkgName, appId);
4507            } catch (RemoteException e) {
4508            }
4509        }
4510    }
4511
4512    void removePackageLI(PackageSetting ps, boolean chatty) {
4513        if (DEBUG_INSTALL) {
4514            if (chatty)
4515                Log.d(TAG, "Removing package " + ps.name);
4516        }
4517
4518        // writer
4519        synchronized (mPackages) {
4520            mPackages.remove(ps.name);
4521            if (ps.codePathString != null) {
4522                mAppDirs.remove(ps.codePathString);
4523            }
4524
4525            final PackageParser.Package pkg = ps.pkg;
4526            if (pkg != null) {
4527                cleanPackageDataStructuresLILPw(pkg, chatty);
4528            }
4529        }
4530    }
4531
4532    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
4533        if (DEBUG_INSTALL) {
4534            if (chatty)
4535                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
4536        }
4537
4538        // writer
4539        synchronized (mPackages) {
4540            mPackages.remove(pkg.applicationInfo.packageName);
4541            if (pkg.mPath != null) {
4542                mAppDirs.remove(pkg.mPath);
4543            }
4544            cleanPackageDataStructuresLILPw(pkg, chatty);
4545        }
4546    }
4547
4548    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
4549        int N = pkg.providers.size();
4550        StringBuilder r = null;
4551        int i;
4552        for (i=0; i<N; i++) {
4553            PackageParser.Provider p = pkg.providers.get(i);
4554            mProvidersByComponent.remove(new ComponentName(p.info.packageName,
4555                    p.info.name));
4556            if (p.info.authority == null) {
4557
4558                /* There was another ContentProvider with this authority when
4559                 * this app was installed so this authority is null,
4560                 * Ignore it as we don't have to unregister the provider.
4561                 */
4562                continue;
4563            }
4564            String names[] = p.info.authority.split(";");
4565            for (int j = 0; j < names.length; j++) {
4566                if (mProviders.get(names[j]) == p) {
4567                    mProviders.remove(names[j]);
4568                    if (DEBUG_REMOVE) {
4569                        if (chatty)
4570                            Log.d(TAG, "Unregistered content provider: " + names[j]
4571                                    + ", className = " + p.info.name + ", isSyncable = "
4572                                    + p.info.isSyncable);
4573                    }
4574                }
4575            }
4576            if (chatty) {
4577                if (r == null) {
4578                    r = new StringBuilder(256);
4579                } else {
4580                    r.append(' ');
4581                }
4582                r.append(p.info.name);
4583            }
4584        }
4585        if (r != null) {
4586            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
4587        }
4588
4589        N = pkg.services.size();
4590        r = null;
4591        for (i=0; i<N; i++) {
4592            PackageParser.Service s = pkg.services.get(i);
4593            mServices.removeService(s);
4594            if (chatty) {
4595                if (r == null) {
4596                    r = new StringBuilder(256);
4597                } else {
4598                    r.append(' ');
4599                }
4600                r.append(s.info.name);
4601            }
4602        }
4603        if (r != null) {
4604            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
4605        }
4606
4607        N = pkg.receivers.size();
4608        r = null;
4609        for (i=0; i<N; i++) {
4610            PackageParser.Activity a = pkg.receivers.get(i);
4611            mReceivers.removeActivity(a, "receiver");
4612            if (chatty) {
4613                if (r == null) {
4614                    r = new StringBuilder(256);
4615                } else {
4616                    r.append(' ');
4617                }
4618                r.append(a.info.name);
4619            }
4620        }
4621        if (r != null) {
4622            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
4623        }
4624
4625        N = pkg.activities.size();
4626        r = null;
4627        for (i=0; i<N; i++) {
4628            PackageParser.Activity a = pkg.activities.get(i);
4629            mActivities.removeActivity(a, "activity");
4630            if (chatty) {
4631                if (r == null) {
4632                    r = new StringBuilder(256);
4633                } else {
4634                    r.append(' ');
4635                }
4636                r.append(a.info.name);
4637            }
4638        }
4639        if (r != null) {
4640            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
4641        }
4642
4643        N = pkg.permissions.size();
4644        r = null;
4645        for (i=0; i<N; i++) {
4646            PackageParser.Permission p = pkg.permissions.get(i);
4647            BasePermission bp = mSettings.mPermissions.get(p.info.name);
4648            if (bp == null) {
4649                bp = mSettings.mPermissionTrees.get(p.info.name);
4650            }
4651            if (bp != null && bp.perm == p) {
4652                bp.perm = null;
4653                if (chatty) {
4654                    if (r == null) {
4655                        r = new StringBuilder(256);
4656                    } else {
4657                        r.append(' ');
4658                    }
4659                    r.append(p.info.name);
4660                }
4661            }
4662        }
4663        if (r != null) {
4664            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
4665        }
4666
4667        N = pkg.instrumentation.size();
4668        r = null;
4669        for (i=0; i<N; i++) {
4670            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
4671            mInstrumentation.remove(a.getComponentName());
4672            if (chatty) {
4673                if (r == null) {
4674                    r = new StringBuilder(256);
4675                } else {
4676                    r.append(' ');
4677                }
4678                r.append(a.info.name);
4679            }
4680        }
4681        if (r != null) {
4682            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
4683        }
4684    }
4685
4686    private static final boolean isPackageFilename(String name) {
4687        return name != null && name.endsWith(".apk");
4688    }
4689
4690    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4691        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4692            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4693                return true;
4694            }
4695        }
4696        return false;
4697    }
4698
4699    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
4700    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
4701    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
4702
4703    private void updatePermissionsLPw(String changingPkg,
4704            PackageParser.Package pkgInfo, int flags) {
4705        // Make sure there are no dangling permission trees.
4706        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
4707        while (it.hasNext()) {
4708            final BasePermission bp = it.next();
4709            if (bp.packageSetting == null) {
4710                // We may not yet have parsed the package, so just see if
4711                // we still know about its settings.
4712                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4713            }
4714            if (bp.packageSetting == null) {
4715                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
4716                        + " from package " + bp.sourcePackage);
4717                it.remove();
4718            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4719                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4720                    Slog.i(TAG, "Removing old permission tree: " + bp.name
4721                            + " from package " + bp.sourcePackage);
4722                    flags |= UPDATE_PERMISSIONS_ALL;
4723                    it.remove();
4724                }
4725            }
4726        }
4727
4728        // Make sure all dynamic permissions have been assigned to a package,
4729        // and make sure there are no dangling permissions.
4730        it = mSettings.mPermissions.values().iterator();
4731        while (it.hasNext()) {
4732            final BasePermission bp = it.next();
4733            if (bp.type == BasePermission.TYPE_DYNAMIC) {
4734                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4735                        + bp.name + " pkg=" + bp.sourcePackage
4736                        + " info=" + bp.pendingInfo);
4737                if (bp.packageSetting == null && bp.pendingInfo != null) {
4738                    final BasePermission tree = findPermissionTreeLP(bp.name);
4739                    if (tree != null && tree.perm != null) {
4740                        bp.packageSetting = tree.packageSetting;
4741                        bp.perm = new PackageParser.Permission(tree.perm.owner,
4742                                new PermissionInfo(bp.pendingInfo));
4743                        bp.perm.info.packageName = tree.perm.info.packageName;
4744                        bp.perm.info.name = bp.name;
4745                        bp.uid = tree.uid;
4746                    }
4747                }
4748            }
4749            if (bp.packageSetting == null) {
4750                // We may not yet have parsed the package, so just see if
4751                // we still know about its settings.
4752                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4753            }
4754            if (bp.packageSetting == null) {
4755                Slog.w(TAG, "Removing dangling permission: " + bp.name
4756                        + " from package " + bp.sourcePackage);
4757                it.remove();
4758            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4759                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4760                    Slog.i(TAG, "Removing old permission: " + bp.name
4761                            + " from package " + bp.sourcePackage);
4762                    flags |= UPDATE_PERMISSIONS_ALL;
4763                    it.remove();
4764                }
4765            }
4766        }
4767
4768        // Now update the permissions for all packages, in particular
4769        // replace the granted permissions of the system packages.
4770        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
4771            for (PackageParser.Package pkg : mPackages.values()) {
4772                if (pkg != pkgInfo) {
4773                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
4774                }
4775            }
4776        }
4777
4778        if (pkgInfo != null) {
4779            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
4780        }
4781    }
4782
4783    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
4784        final PackageSetting ps = (PackageSetting) pkg.mExtras;
4785        if (ps == null) {
4786            return;
4787        }
4788        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
4789        HashSet<String> origPermissions = gp.grantedPermissions;
4790        boolean changedPermission = false;
4791
4792        if (replace) {
4793            ps.permissionsFixed = false;
4794            if (gp == ps) {
4795                origPermissions = new HashSet<String>(gp.grantedPermissions);
4796                gp.grantedPermissions.clear();
4797                gp.gids = mGlobalGids;
4798            }
4799        }
4800
4801        if (gp.gids == null) {
4802            gp.gids = mGlobalGids;
4803        }
4804
4805        final int N = pkg.requestedPermissions.size();
4806        for (int i=0; i<N; i++) {
4807            final String name = pkg.requestedPermissions.get(i);
4808            //final boolean required = pkg.requestedPermssionsRequired.get(i);
4809            final BasePermission bp = mSettings.mPermissions.get(name);
4810            if (DEBUG_INSTALL) {
4811                if (gp != ps) {
4812                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
4813                }
4814            }
4815            if (bp != null && bp.packageSetting != null) {
4816                final String perm = bp.name;
4817                boolean allowed;
4818                boolean allowedSig = false;
4819                final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
4820                if (level == PermissionInfo.PROTECTION_NORMAL
4821                        || level == PermissionInfo.PROTECTION_DANGEROUS) {
4822                    allowed = true;
4823                } else if (bp.packageSetting == null) {
4824                    // This permission is invalid; skip it.
4825                    allowed = false;
4826                } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
4827                    allowed = (compareSignatures(
4828                            bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
4829                                    == PackageManager.SIGNATURE_MATCH)
4830                            || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
4831                                    == PackageManager.SIGNATURE_MATCH);
4832                    if (!allowed && (bp.protectionLevel
4833                            & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
4834                        if (isSystemApp(pkg)) {
4835                            // For updated system applications, a system permission
4836                            // is granted only if it had been defined by the original application.
4837                            if (isUpdatedSystemApp(pkg)) {
4838                                final PackageSetting sysPs = mSettings
4839                                        .getDisabledSystemPkgLPr(pkg.packageName);
4840                                final GrantedPermissions origGp = sysPs.sharedUser != null
4841                                        ? sysPs.sharedUser : sysPs;
4842                                if (origGp.grantedPermissions.contains(perm)) {
4843                                    allowed = true;
4844                                } else {
4845                                    allowed = false;
4846                                }
4847                            } else {
4848                                allowed = true;
4849                            }
4850                        }
4851                    }
4852                    if (!allowed && (bp.protectionLevel
4853                            & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
4854                        // For development permissions, a development permission
4855                        // is granted only if it was already granted.
4856                        if (origPermissions.contains(perm)) {
4857                            allowed = true;
4858                        } else {
4859                            allowed = false;
4860                        }
4861                    }
4862                    if (allowed) {
4863                        allowedSig = true;
4864                    }
4865                } else {
4866                    allowed = false;
4867                }
4868                if (DEBUG_INSTALL) {
4869                    if (gp != ps) {
4870                        Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4871                    }
4872                }
4873                if (allowed) {
4874                    if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4875                            && ps.permissionsFixed) {
4876                        // If this is an existing, non-system package, then
4877                        // we can't add any new permissions to it.
4878                        if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
4879                            allowed = false;
4880                            // Except...  if this is a permission that was added
4881                            // to the platform (note: need to only do this when
4882                            // updating the platform).
4883                            final int NP = PackageParser.NEW_PERMISSIONS.length;
4884                            for (int ip=0; ip<NP; ip++) {
4885                                final PackageParser.NewPermissionInfo npi
4886                                        = PackageParser.NEW_PERMISSIONS[ip];
4887                                if (npi.name.equals(perm)
4888                                        && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4889                                    allowed = true;
4890                                    Log.i(TAG, "Auto-granting " + perm + " to old pkg "
4891                                            + pkg.packageName);
4892                                    break;
4893                                }
4894                            }
4895                        }
4896                    }
4897                    if (allowed) {
4898                        if (!gp.grantedPermissions.contains(perm)) {
4899                            changedPermission = true;
4900                            gp.grantedPermissions.add(perm);
4901                            gp.gids = appendInts(gp.gids, bp.gids);
4902                        } else if (!ps.haveGids) {
4903                            gp.gids = appendInts(gp.gids, bp.gids);
4904                        }
4905                    } else {
4906                        Slog.w(TAG, "Not granting permission " + perm
4907                                + " to package " + pkg.packageName
4908                                + " because it was previously installed without");
4909                    }
4910                } else {
4911                    if (gp.grantedPermissions.remove(perm)) {
4912                        changedPermission = true;
4913                        gp.gids = removeInts(gp.gids, bp.gids);
4914                        Slog.i(TAG, "Un-granting permission " + perm
4915                                + " from package " + pkg.packageName
4916                                + " (protectionLevel=" + bp.protectionLevel
4917                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4918                                + ")");
4919                    } else {
4920                        Slog.w(TAG, "Not granting permission " + perm
4921                                + " to package " + pkg.packageName
4922                                + " (protectionLevel=" + bp.protectionLevel
4923                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4924                                + ")");
4925                    }
4926                }
4927            } else {
4928                Slog.w(TAG, "Unknown permission " + name
4929                        + " in package " + pkg.packageName);
4930            }
4931        }
4932
4933        if ((changedPermission || replace) && !ps.permissionsFixed &&
4934                ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4935                ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
4936            // This is the first that we have heard about this package, so the
4937            // permissions we have now selected are fixed until explicitly
4938            // changed.
4939            ps.permissionsFixed = true;
4940        }
4941        ps.haveGids = true;
4942    }
4943
4944    private final class ActivityIntentResolver
4945            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
4946        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
4947                boolean defaultOnly, int userId) {
4948            if (!sUserManager.exists(userId)) return null;
4949            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
4950            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
4951        }
4952
4953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
4954                int userId) {
4955            if (!sUserManager.exists(userId)) return null;
4956            mFlags = flags;
4957            return super.queryIntent(intent, resolvedType,
4958                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
4959        }
4960
4961        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
4962                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
4963            if (!sUserManager.exists(userId)) return null;
4964            if (packageActivities == null) {
4965                return null;
4966            }
4967            mFlags = flags;
4968            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4969            final int N = packageActivities.size();
4970            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
4971                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
4972
4973            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
4974            for (int i = 0; i < N; ++i) {
4975                intentFilters = packageActivities.get(i).intents;
4976                if (intentFilters != null && intentFilters.size() > 0) {
4977                    PackageParser.ActivityIntentInfo[] array =
4978                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
4979                    intentFilters.toArray(array);
4980                    listCut.add(array);
4981                }
4982            }
4983            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
4984        }
4985
4986        public final void addActivity(PackageParser.Activity a, String type) {
4987            final boolean systemApp = isSystemApp(a.info.applicationInfo);
4988            mActivities.put(a.getComponentName(), a);
4989            if (DEBUG_SHOW_INFO)
4990                Log.v(
4991                TAG, "  " + type + " " +
4992                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4993            if (DEBUG_SHOW_INFO)
4994                Log.v(TAG, "    Class=" + a.info.name);
4995            final int NI = a.intents.size();
4996            for (int j=0; j<NI; j++) {
4997                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4998                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4999                    intent.setPriority(0);
5000                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
5001                            + a.className + " with priority > 0, forcing to 0");
5002                }
5003                if (DEBUG_SHOW_INFO) {
5004                    Log.v(TAG, "    IntentFilter:");
5005                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5006                }
5007                if (!intent.debugCheck()) {
5008                    Log.w(TAG, "==> For Activity " + a.info.name);
5009                }
5010                addFilter(intent);
5011            }
5012        }
5013
5014        public final void removeActivity(PackageParser.Activity a, String type) {
5015            mActivities.remove(a.getComponentName());
5016            if (DEBUG_SHOW_INFO) {
5017                Log.v(TAG, "  " + type + " "
5018                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
5019                                : a.info.name) + ":");
5020                Log.v(TAG, "    Class=" + a.info.name);
5021            }
5022            final int NI = a.intents.size();
5023            for (int j=0; j<NI; j++) {
5024                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
5025                if (DEBUG_SHOW_INFO) {
5026                    Log.v(TAG, "    IntentFilter:");
5027                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5028                }
5029                removeFilter(intent);
5030            }
5031        }
5032
5033        @Override
5034        protected boolean allowFilterResult(
5035                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
5036            ActivityInfo filterAi = filter.activity.info;
5037            for (int i=dest.size()-1; i>=0; i--) {
5038                ActivityInfo destAi = dest.get(i).activityInfo;
5039                if (destAi.name == filterAi.name
5040                        && destAi.packageName == filterAi.packageName) {
5041                    return false;
5042                }
5043            }
5044            return true;
5045        }
5046
5047        @Override
5048        protected ActivityIntentInfo[] newArray(int size) {
5049            return new ActivityIntentInfo[size];
5050        }
5051
5052        @Override
5053        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
5054            if (!sUserManager.exists(userId)) return true;
5055            PackageParser.Package p = filter.activity.owner;
5056            if (p != null) {
5057                PackageSetting ps = (PackageSetting)p.mExtras;
5058                if (ps != null) {
5059                    // System apps are never considered stopped for purposes of
5060                    // filtering, because there may be no way for the user to
5061                    // actually re-launch them.
5062                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
5063                            && ps.getStopped(userId);
5064                }
5065            }
5066            return false;
5067        }
5068
5069        @Override
5070        protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
5071            return info.activity.owner.packageName;
5072        }
5073
5074        @Override
5075        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
5076                int match, int userId) {
5077            if (!sUserManager.exists(userId)) return null;
5078            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
5079                return null;
5080            }
5081            final PackageParser.Activity activity = info.activity;
5082            if (mSafeMode && (activity.info.applicationInfo.flags
5083                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5084                return null;
5085            }
5086            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
5087            if (ps == null) {
5088                return null;
5089            }
5090            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
5091                    ps.readUserState(userId), userId);
5092            if (ai == null) {
5093                return null;
5094            }
5095            final ResolveInfo res = new ResolveInfo();
5096            res.activityInfo = ai;
5097            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5098                res.filter = info;
5099            }
5100            res.priority = info.getPriority();
5101            res.preferredOrder = activity.owner.mPreferredOrder;
5102            //System.out.println("Result: " + res.activityInfo.className +
5103            //                   " = " + res.priority);
5104            res.match = match;
5105            res.isDefault = info.hasDefault;
5106            res.labelRes = info.labelRes;
5107            res.nonLocalizedLabel = info.nonLocalizedLabel;
5108            res.icon = info.icon;
5109            res.system = isSystemApp(res.activityInfo.applicationInfo);
5110            return res;
5111        }
5112
5113        @Override
5114        protected void sortResults(List<ResolveInfo> results) {
5115            Collections.sort(results, mResolvePrioritySorter);
5116        }
5117
5118        @Override
5119        protected void dumpFilter(PrintWriter out, String prefix,
5120                PackageParser.ActivityIntentInfo filter) {
5121            out.print(prefix); out.print(
5122                    Integer.toHexString(System.identityHashCode(filter.activity)));
5123                    out.print(' ');
5124                    out.print(filter.activity.getComponentShortName());
5125                    out.print(" filter ");
5126                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5127        }
5128
5129//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5130//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5131//            final List<ResolveInfo> retList = Lists.newArrayList();
5132//            while (i.hasNext()) {
5133//                final ResolveInfo resolveInfo = i.next();
5134//                if (isEnabledLP(resolveInfo.activityInfo)) {
5135//                    retList.add(resolveInfo);
5136//                }
5137//            }
5138//            return retList;
5139//        }
5140
5141        // Keys are String (activity class name), values are Activity.
5142        private final HashMap<ComponentName, PackageParser.Activity> mActivities
5143                = new HashMap<ComponentName, PackageParser.Activity>();
5144        private int mFlags;
5145    }
5146
5147    private final class ServiceIntentResolver
5148            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
5149        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
5150                boolean defaultOnly, int userId) {
5151            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
5152            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
5153        }
5154
5155        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
5156                int userId) {
5157            if (!sUserManager.exists(userId)) return null;
5158            mFlags = flags;
5159            return super.queryIntent(intent, resolvedType,
5160                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
5161        }
5162
5163        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
5164                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
5165            if (!sUserManager.exists(userId)) return null;
5166            if (packageServices == null) {
5167                return null;
5168            }
5169            mFlags = flags;
5170            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
5171            final int N = packageServices.size();
5172            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
5173                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
5174
5175            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
5176            for (int i = 0; i < N; ++i) {
5177                intentFilters = packageServices.get(i).intents;
5178                if (intentFilters != null && intentFilters.size() > 0) {
5179                    PackageParser.ServiceIntentInfo[] array =
5180                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
5181                    intentFilters.toArray(array);
5182                    listCut.add(array);
5183                }
5184            }
5185            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
5186        }
5187
5188        public final void addService(PackageParser.Service s) {
5189            mServices.put(s.getComponentName(), s);
5190            if (DEBUG_SHOW_INFO) {
5191                Log.v(TAG, "  "
5192                        + (s.info.nonLocalizedLabel != null
5193                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5194                Log.v(TAG, "    Class=" + s.info.name);
5195            }
5196            final int NI = s.intents.size();
5197            int j;
5198            for (j=0; j<NI; j++) {
5199                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5200                if (DEBUG_SHOW_INFO) {
5201                    Log.v(TAG, "    IntentFilter:");
5202                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5203                }
5204                if (!intent.debugCheck()) {
5205                    Log.w(TAG, "==> For Service " + s.info.name);
5206                }
5207                addFilter(intent);
5208            }
5209        }
5210
5211        public final void removeService(PackageParser.Service s) {
5212            mServices.remove(s.getComponentName());
5213            if (DEBUG_SHOW_INFO) {
5214                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
5215                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
5216                Log.v(TAG, "    Class=" + s.info.name);
5217            }
5218            final int NI = s.intents.size();
5219            int j;
5220            for (j=0; j<NI; j++) {
5221                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
5222                if (DEBUG_SHOW_INFO) {
5223                    Log.v(TAG, "    IntentFilter:");
5224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
5225                }
5226                removeFilter(intent);
5227            }
5228        }
5229
5230        @Override
5231        protected boolean allowFilterResult(
5232                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
5233            ServiceInfo filterSi = filter.service.info;
5234            for (int i=dest.size()-1; i>=0; i--) {
5235                ServiceInfo destAi = dest.get(i).serviceInfo;
5236                if (destAi.name == filterSi.name
5237                        && destAi.packageName == filterSi.packageName) {
5238                    return false;
5239                }
5240            }
5241            return true;
5242        }
5243
5244        @Override
5245        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
5246            return new PackageParser.ServiceIntentInfo[size];
5247        }
5248
5249        @Override
5250        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
5251            if (!sUserManager.exists(userId)) return true;
5252            PackageParser.Package p = filter.service.owner;
5253            if (p != null) {
5254                PackageSetting ps = (PackageSetting)p.mExtras;
5255                if (ps != null) {
5256                    // System apps are never considered stopped for purposes of
5257                    // filtering, because there may be no way for the user to
5258                    // actually re-launch them.
5259                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
5260                            && ps.getStopped(userId);
5261                }
5262            }
5263            return false;
5264        }
5265
5266        @Override
5267        protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
5268            return info.service.owner.packageName;
5269        }
5270
5271        @Override
5272        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
5273                int match, int userId) {
5274            if (!sUserManager.exists(userId)) return null;
5275            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
5276            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
5277                return null;
5278            }
5279            final PackageParser.Service service = info.service;
5280            if (mSafeMode && (service.info.applicationInfo.flags
5281                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
5282                return null;
5283            }
5284            PackageSetting ps = (PackageSetting) service.owner.mExtras;
5285            if (ps == null) {
5286                return null;
5287            }
5288            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
5289                    ps.readUserState(userId), userId);
5290            if (si == null) {
5291                return null;
5292            }
5293            final ResolveInfo res = new ResolveInfo();
5294            res.serviceInfo = si;
5295            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
5296                res.filter = filter;
5297            }
5298            res.priority = info.getPriority();
5299            res.preferredOrder = service.owner.mPreferredOrder;
5300            //System.out.println("Result: " + res.activityInfo.className +
5301            //                   " = " + res.priority);
5302            res.match = match;
5303            res.isDefault = info.hasDefault;
5304            res.labelRes = info.labelRes;
5305            res.nonLocalizedLabel = info.nonLocalizedLabel;
5306            res.icon = info.icon;
5307            res.system = isSystemApp(res.serviceInfo.applicationInfo);
5308            return res;
5309        }
5310
5311        @Override
5312        protected void sortResults(List<ResolveInfo> results) {
5313            Collections.sort(results, mResolvePrioritySorter);
5314        }
5315
5316        @Override
5317        protected void dumpFilter(PrintWriter out, String prefix,
5318                PackageParser.ServiceIntentInfo filter) {
5319            out.print(prefix); out.print(
5320                    Integer.toHexString(System.identityHashCode(filter.service)));
5321                    out.print(' ');
5322                    out.print(filter.service.getComponentShortName());
5323                    out.print(" filter ");
5324                    out.println(Integer.toHexString(System.identityHashCode(filter)));
5325        }
5326
5327//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
5328//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
5329//            final List<ResolveInfo> retList = Lists.newArrayList();
5330//            while (i.hasNext()) {
5331//                final ResolveInfo resolveInfo = (ResolveInfo) i;
5332//                if (isEnabledLP(resolveInfo.serviceInfo)) {
5333//                    retList.add(resolveInfo);
5334//                }
5335//            }
5336//            return retList;
5337//        }
5338
5339        // Keys are String (activity class name), values are Activity.
5340        private final HashMap<ComponentName, PackageParser.Service> mServices
5341                = new HashMap<ComponentName, PackageParser.Service>();
5342        private int mFlags;
5343    };
5344
5345    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
5346            new Comparator<ResolveInfo>() {
5347        public int compare(ResolveInfo r1, ResolveInfo r2) {
5348            int v1 = r1.priority;
5349            int v2 = r2.priority;
5350            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
5351            if (v1 != v2) {
5352                return (v1 > v2) ? -1 : 1;
5353            }
5354            v1 = r1.preferredOrder;
5355            v2 = r2.preferredOrder;
5356            if (v1 != v2) {
5357                return (v1 > v2) ? -1 : 1;
5358            }
5359            if (r1.isDefault != r2.isDefault) {
5360                return r1.isDefault ? -1 : 1;
5361            }
5362            v1 = r1.match;
5363            v2 = r2.match;
5364            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
5365            if (v1 != v2) {
5366                return (v1 > v2) ? -1 : 1;
5367            }
5368            if (r1.system != r2.system) {
5369                return r1.system ? -1 : 1;
5370            }
5371            return 0;
5372        }
5373    };
5374
5375    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
5376            new Comparator<ProviderInfo>() {
5377        public int compare(ProviderInfo p1, ProviderInfo p2) {
5378            final int v1 = p1.initOrder;
5379            final int v2 = p2.initOrder;
5380            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
5381        }
5382    };
5383
5384    static final void sendPackageBroadcast(String action, String pkg,
5385            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
5386            int[] userIds) {
5387        IActivityManager am = ActivityManagerNative.getDefault();
5388        if (am != null) {
5389            try {
5390                if (userIds == null) {
5391                    userIds = am.getRunningUserIds();
5392                }
5393                for (int id : userIds) {
5394                    final Intent intent = new Intent(action,
5395                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
5396                    if (extras != null) {
5397                        intent.putExtras(extras);
5398                    }
5399                    if (targetPkg != null) {
5400                        intent.setPackage(targetPkg);
5401                    }
5402                    // Modify the UID when posting to other users
5403                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
5404                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
5405                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
5406                        intent.putExtra(Intent.EXTRA_UID, uid);
5407                    }
5408                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
5409                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5410                    if (DEBUG_BROADCASTS) {
5411                        RuntimeException here = new RuntimeException("here");
5412                        here.fillInStackTrace();
5413                        Slog.d(TAG, "Sending to user " + id + ": "
5414                                + intent.toShortString(false, true, false, false)
5415                                + " " + intent.getExtras(), here);
5416                    }
5417                    am.broadcastIntent(null, intent, null, finishedReceiver,
5418                            0, null, null, null, finishedReceiver != null, false, id);
5419                }
5420            } catch (RemoteException ex) {
5421            }
5422        }
5423    }
5424
5425    /**
5426     * Check if the external storage media is available. This is true if there
5427     * is a mounted external storage medium or if the external storage is
5428     * emulated.
5429     */
5430    private boolean isExternalMediaAvailable() {
5431        return mMediaMounted || Environment.isExternalStorageEmulated();
5432    }
5433
5434    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
5435        // writer
5436        synchronized (mPackages) {
5437            if (!isExternalMediaAvailable()) {
5438                // If the external storage is no longer mounted at this point,
5439                // the caller may not have been able to delete all of this
5440                // packages files and can not delete any more.  Bail.
5441                return null;
5442            }
5443            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
5444            if (lastPackage != null) {
5445                pkgs.remove(lastPackage);
5446            }
5447            if (pkgs.size() > 0) {
5448                return pkgs.get(0);
5449            }
5450        }
5451        return null;
5452    }
5453
5454    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
5455        if (false) {
5456            RuntimeException here = new RuntimeException("here");
5457            here.fillInStackTrace();
5458            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
5459                    + " andCode=" + andCode, here);
5460        }
5461        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
5462                userId, andCode ? 1 : 0, packageName));
5463    }
5464
5465    void startCleaningPackages() {
5466        // reader
5467        synchronized (mPackages) {
5468            if (!isExternalMediaAvailable()) {
5469                return;
5470            }
5471            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
5472                return;
5473            }
5474        }
5475        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
5476        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
5477        IActivityManager am = ActivityManagerNative.getDefault();
5478        if (am != null) {
5479            try {
5480                am.startService(null, intent, null, UserHandle.USER_OWNER);
5481            } catch (RemoteException e) {
5482            }
5483        }
5484    }
5485
5486    private final class AppDirObserver extends FileObserver {
5487        public AppDirObserver(String path, int mask, boolean isrom) {
5488            super(path, mask);
5489            mRootDir = path;
5490            mIsRom = isrom;
5491        }
5492
5493        public void onEvent(int event, String path) {
5494            String removedPackage = null;
5495            int removedAppId = -1;
5496            int[] removedUsers = null;
5497            String addedPackage = null;
5498            int addedAppId = -1;
5499            int[] addedUsers = null;
5500
5501            // TODO post a message to the handler to obtain serial ordering
5502            synchronized (mInstallLock) {
5503                String fullPathStr = null;
5504                File fullPath = null;
5505                if (path != null) {
5506                    fullPath = new File(mRootDir, path);
5507                    fullPathStr = fullPath.getPath();
5508                }
5509
5510                if (DEBUG_APP_DIR_OBSERVER)
5511                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
5512
5513                if (!isPackageFilename(path)) {
5514                    if (DEBUG_APP_DIR_OBSERVER)
5515                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
5516                    return;
5517                }
5518
5519                // Ignore packages that are being installed or
5520                // have just been installed.
5521                if (ignoreCodePath(fullPathStr)) {
5522                    return;
5523                }
5524                PackageParser.Package p = null;
5525                PackageSetting ps = null;
5526                // reader
5527                synchronized (mPackages) {
5528                    p = mAppDirs.get(fullPathStr);
5529                    if (p != null) {
5530                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
5531                        if (ps != null) {
5532                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
5533                        } else {
5534                            removedUsers = sUserManager.getUserIds();
5535                        }
5536                    }
5537                    addedUsers = sUserManager.getUserIds();
5538                }
5539                if ((event&REMOVE_EVENTS) != 0) {
5540                    if (ps != null) {
5541                        removePackageLI(ps, true);
5542                        removedPackage = ps.name;
5543                        removedAppId = ps.appId;
5544                    }
5545                }
5546
5547                if ((event&ADD_EVENTS) != 0) {
5548                    if (p == null) {
5549                        p = scanPackageLI(fullPath,
5550                                (mIsRom ? PackageParser.PARSE_IS_SYSTEM
5551                                        | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
5552                                PackageParser.PARSE_CHATTY |
5553                                PackageParser.PARSE_MUST_BE_APK,
5554                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
5555                                System.currentTimeMillis(), UserHandle.ALL);
5556                        if (p != null) {
5557                            /*
5558                             * TODO this seems dangerous as the package may have
5559                             * changed since we last acquired the mPackages
5560                             * lock.
5561                             */
5562                            // writer
5563                            synchronized (mPackages) {
5564                                updatePermissionsLPw(p.packageName, p,
5565                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
5566                            }
5567                            addedPackage = p.applicationInfo.packageName;
5568                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
5569                        }
5570                    }
5571                }
5572
5573                // reader
5574                synchronized (mPackages) {
5575                    mSettings.writeLPr();
5576                }
5577            }
5578
5579            if (removedPackage != null) {
5580                Bundle extras = new Bundle(1);
5581                extras.putInt(Intent.EXTRA_UID, removedAppId);
5582                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
5583                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
5584                        extras, null, null, removedUsers);
5585            }
5586            if (addedPackage != null) {
5587                Bundle extras = new Bundle(1);
5588                extras.putInt(Intent.EXTRA_UID, addedAppId);
5589                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
5590                        extras, null, null, addedUsers);
5591            }
5592        }
5593
5594        private final String mRootDir;
5595        private final boolean mIsRom;
5596    }
5597
5598    /* Called when a downloaded package installation has been confirmed by the user */
5599    public void installPackage(
5600            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
5601        installPackage(packageURI, observer, flags, null);
5602    }
5603
5604    /* Called when a downloaded package installation has been confirmed by the user */
5605    public void installPackage(
5606            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
5607            final String installerPackageName) {
5608        installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
5609                null, null);
5610    }
5611
5612    @Override
5613    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
5614            int flags, String installerPackageName, Uri verificationURI,
5615            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
5616        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
5617                manifestDigest);
5618        installPackageWithVerificationAndEncryption(packageURI, observer, flags,
5619                installerPackageName, verificationParams, encryptionParams);
5620    }
5621
5622    public void installPackageWithVerificationAndEncryption(Uri packageURI,
5623            IPackageInstallObserver observer, int flags, String installerPackageName,
5624            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
5625        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5626                null);
5627
5628        final int uid = Binder.getCallingUid();
5629        UserHandle user;
5630        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
5631            user = UserHandle.ALL;
5632        } else {
5633            user = new UserHandle(UserHandle.getUserId(uid));
5634        }
5635
5636        final int filteredFlags;
5637
5638        if (uid == Process.SHELL_UID || uid == 0) {
5639            if (DEBUG_INSTALL) {
5640                Slog.v(TAG, "Install from ADB");
5641            }
5642            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
5643        } else {
5644            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
5645        }
5646
5647        verificationParams.setInstallerUid(uid);
5648
5649        final Message msg = mHandler.obtainMessage(INIT_COPY);
5650        msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
5651                verificationParams, encryptionParams, user);
5652        mHandler.sendMessage(msg);
5653    }
5654
5655    /**
5656     * @hide
5657     */
5658    @Override
5659    public int installExistingPackage(String packageName) {
5660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
5661                null);
5662        PackageSetting pkgSetting;
5663        final int uid = Binder.getCallingUid();
5664        final int userId = UserHandle.getUserId(uid);
5665
5666        long callingId = Binder.clearCallingIdentity();
5667        try {
5668            boolean sendAdded = false;
5669            Bundle extras = new Bundle(1);
5670
5671            // writer
5672            synchronized (mPackages) {
5673                pkgSetting = mSettings.mPackages.get(packageName);
5674                if (pkgSetting == null) {
5675                    return PackageManager.INSTALL_FAILED_INVALID_URI;
5676                }
5677                if (!pkgSetting.getInstalled(userId)) {
5678                    pkgSetting.setInstalled(true, userId);
5679                    mSettings.writePackageRestrictionsLPr(userId);
5680                    extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
5681                    sendAdded = true;
5682                }
5683            }
5684
5685            if (sendAdded) {
5686                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
5687                        packageName, extras, null, null, new int[] {userId});
5688            }
5689        } finally {
5690            Binder.restoreCallingIdentity(callingId);
5691        }
5692
5693        return PackageManager.INSTALL_SUCCEEDED;
5694    }
5695
5696    @Override
5697    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
5698        mContext.enforceCallingOrSelfPermission(
5699                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5700                "Only package verification agents can verify applications");
5701
5702        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5703        final PackageVerificationResponse response = new PackageVerificationResponse(
5704                verificationCode, Binder.getCallingUid());
5705        msg.arg1 = id;
5706        msg.obj = response;
5707        mHandler.sendMessage(msg);
5708    }
5709
5710    @Override
5711    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
5712            long millisecondsToDelay) {
5713        mContext.enforceCallingOrSelfPermission(
5714                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5715                "Only package verification agents can extend verification timeouts");
5716
5717        final PackageVerificationState state = mPendingVerification.get(id);
5718        final PackageVerificationResponse response = new PackageVerificationResponse(
5719                verificationCodeAtTimeout, Binder.getCallingUid());
5720
5721        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
5722            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
5723        }
5724        if (millisecondsToDelay < 0) {
5725            millisecondsToDelay = 0;
5726        }
5727        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
5728                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
5729            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
5730        }
5731
5732        if ((state != null) && !state.timeoutExtended()) {
5733            state.extendTimeout();
5734
5735            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
5736            msg.arg1 = id;
5737            msg.obj = response;
5738            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
5739        }
5740    }
5741
5742    private void broadcastPackageVerified(int verificationId, Uri packageUri,
5743            int verificationCode) {
5744        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
5745        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
5746        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5747        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
5748        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
5749
5750        mContext.sendBroadcast(intent, android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
5751    }
5752
5753    private ComponentName matchComponentForVerifier(String packageName,
5754            List<ResolveInfo> receivers) {
5755        ActivityInfo targetReceiver = null;
5756
5757        final int NR = receivers.size();
5758        for (int i = 0; i < NR; i++) {
5759            final ResolveInfo info = receivers.get(i);
5760            if (info.activityInfo == null) {
5761                continue;
5762            }
5763
5764            if (packageName.equals(info.activityInfo.packageName)) {
5765                targetReceiver = info.activityInfo;
5766                break;
5767            }
5768        }
5769
5770        if (targetReceiver == null) {
5771            return null;
5772        }
5773
5774        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
5775    }
5776
5777    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
5778            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
5779        if (pkgInfo.verifiers.length == 0) {
5780            return null;
5781        }
5782
5783        final int N = pkgInfo.verifiers.length;
5784        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
5785        for (int i = 0; i < N; i++) {
5786            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
5787
5788            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
5789                    receivers);
5790            if (comp == null) {
5791                continue;
5792            }
5793
5794            final int verifierUid = getUidForVerifier(verifierInfo);
5795            if (verifierUid == -1) {
5796                continue;
5797            }
5798
5799            if (DEBUG_VERIFY) {
5800                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
5801                        + " with the correct signature");
5802            }
5803            sufficientVerifiers.add(comp);
5804            verificationState.addSufficientVerifier(verifierUid);
5805        }
5806
5807        return sufficientVerifiers;
5808    }
5809
5810    private int getUidForVerifier(VerifierInfo verifierInfo) {
5811        synchronized (mPackages) {
5812            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
5813            if (pkg == null) {
5814                return -1;
5815            } else if (pkg.mSignatures.length != 1) {
5816                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5817                        + " has more than one signature; ignoring");
5818                return -1;
5819            }
5820
5821            /*
5822             * If the public key of the package's signature does not match
5823             * our expected public key, then this is a different package and
5824             * we should skip.
5825             */
5826
5827            final byte[] expectedPublicKey;
5828            try {
5829                final Signature verifierSig = pkg.mSignatures[0];
5830                final PublicKey publicKey = verifierSig.getPublicKey();
5831                expectedPublicKey = publicKey.getEncoded();
5832            } catch (CertificateException e) {
5833                return -1;
5834            }
5835
5836            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
5837
5838            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
5839                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
5840                        + " does not have the expected public key; ignoring");
5841                return -1;
5842            }
5843
5844            return pkg.applicationInfo.uid;
5845        }
5846    }
5847
5848    public void finishPackageInstall(int token) {
5849        enforceSystemOrRoot("Only the system is allowed to finish installs");
5850
5851        if (DEBUG_INSTALL) {
5852            Slog.v(TAG, "BM finishing package install for " + token);
5853        }
5854
5855        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
5856        mHandler.sendMessage(msg);
5857    }
5858
5859    /**
5860     * Get the verification agent timeout.
5861     *
5862     * @return verification timeout in milliseconds
5863     */
5864    private long getVerificationTimeout() {
5865        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
5866                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
5867                DEFAULT_VERIFICATION_TIMEOUT);
5868    }
5869
5870    /**
5871     * Get the default verification agent response code.
5872     *
5873     * @return default verification response code
5874     */
5875    private int getDefaultVerificationResponse() {
5876        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5877                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
5878                DEFAULT_VERIFICATION_RESPONSE);
5879    }
5880
5881    /**
5882     * Check whether or not package verification has been enabled.
5883     *
5884     * @return true if verification should be performed
5885     */
5886    private boolean isVerificationEnabled(int flags) {
5887        if (!DEFAULT_VERIFY_ENABLE) {
5888            return false;
5889        }
5890
5891        // Check if installing from ADB
5892        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
5893            // Check if the developer does not want package verification for ADB installs
5894            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5895                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
5896                return false;
5897            }
5898        }
5899
5900        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5901                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
5902    }
5903
5904    /**
5905     * Get the "allow unknown sources" setting.
5906     *
5907     * @return the current "allow unknown sources" setting
5908     */
5909    private int getUnknownSourcesSettings() {
5910        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
5911                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
5912                -1);
5913    }
5914
5915    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
5916        final int uid = Binder.getCallingUid();
5917        // writer
5918        synchronized (mPackages) {
5919            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
5920            if (targetPackageSetting == null) {
5921                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
5922            }
5923
5924            PackageSetting installerPackageSetting;
5925            if (installerPackageName != null) {
5926                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
5927                if (installerPackageSetting == null) {
5928                    throw new IllegalArgumentException("Unknown installer package: "
5929                            + installerPackageName);
5930                }
5931            } else {
5932                installerPackageSetting = null;
5933            }
5934
5935            Signature[] callerSignature;
5936            Object obj = mSettings.getUserIdLPr(uid);
5937            if (obj != null) {
5938                if (obj instanceof SharedUserSetting) {
5939                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
5940                } else if (obj instanceof PackageSetting) {
5941                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
5942                } else {
5943                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
5944                }
5945            } else {
5946                throw new SecurityException("Unknown calling uid " + uid);
5947            }
5948
5949            // Verify: can't set installerPackageName to a package that is
5950            // not signed with the same cert as the caller.
5951            if (installerPackageSetting != null) {
5952                if (compareSignatures(callerSignature,
5953                        installerPackageSetting.signatures.mSignatures)
5954                        != PackageManager.SIGNATURE_MATCH) {
5955                    throw new SecurityException(
5956                            "Caller does not have same cert as new installer package "
5957                            + installerPackageName);
5958                }
5959            }
5960
5961            // Verify: if target already has an installer package, it must
5962            // be signed with the same cert as the caller.
5963            if (targetPackageSetting.installerPackageName != null) {
5964                PackageSetting setting = mSettings.mPackages.get(
5965                        targetPackageSetting.installerPackageName);
5966                // If the currently set package isn't valid, then it's always
5967                // okay to change it.
5968                if (setting != null) {
5969                    if (compareSignatures(callerSignature,
5970                            setting.signatures.mSignatures)
5971                            != PackageManager.SIGNATURE_MATCH) {
5972                        throw new SecurityException(
5973                                "Caller does not have same cert as old installer package "
5974                                + targetPackageSetting.installerPackageName);
5975                    }
5976                }
5977            }
5978
5979            // Okay!
5980            targetPackageSetting.installerPackageName = installerPackageName;
5981            scheduleWriteSettingsLocked();
5982        }
5983    }
5984
5985    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
5986        // Queue up an async operation since the package installation may take a little while.
5987        mHandler.post(new Runnable() {
5988            public void run() {
5989                mHandler.removeCallbacks(this);
5990                 // Result object to be returned
5991                PackageInstalledInfo res = new PackageInstalledInfo();
5992                res.returnCode = currentStatus;
5993                res.uid = -1;
5994                res.pkg = null;
5995                res.removedInfo = new PackageRemovedInfo();
5996                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5997                    args.doPreInstall(res.returnCode);
5998                    synchronized (mInstallLock) {
5999                        installPackageLI(args, true, res);
6000                    }
6001                    args.doPostInstall(res.returnCode, res.uid);
6002                }
6003
6004                // A restore should be performed at this point if (a) the install
6005                // succeeded, (b) the operation is not an update, and (c) the new
6006                // package has a backupAgent defined.
6007                final boolean update = res.removedInfo.removedPackage != null;
6008                boolean doRestore = (!update
6009                        && res.pkg != null
6010                        && res.pkg.applicationInfo.backupAgentName != null);
6011
6012                // Set up the post-install work request bookkeeping.  This will be used
6013                // and cleaned up by the post-install event handling regardless of whether
6014                // there's a restore pass performed.  Token values are >= 1.
6015                int token;
6016                if (mNextInstallToken < 0) mNextInstallToken = 1;
6017                token = mNextInstallToken++;
6018
6019                PostInstallData data = new PostInstallData(args, res);
6020                mRunningInstalls.put(token, data);
6021                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
6022
6023                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
6024                    // Pass responsibility to the Backup Manager.  It will perform a
6025                    // restore if appropriate, then pass responsibility back to the
6026                    // Package Manager to run the post-install observer callbacks
6027                    // and broadcasts.
6028                    IBackupManager bm = IBackupManager.Stub.asInterface(
6029                            ServiceManager.getService(Context.BACKUP_SERVICE));
6030                    if (bm != null) {
6031                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
6032                                + " to BM for possible restore");
6033                        try {
6034                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
6035                        } catch (RemoteException e) {
6036                            // can't happen; the backup manager is local
6037                        } catch (Exception e) {
6038                            Slog.e(TAG, "Exception trying to enqueue restore", e);
6039                            doRestore = false;
6040                        }
6041                    } else {
6042                        Slog.e(TAG, "Backup Manager not found!");
6043                        doRestore = false;
6044                    }
6045                }
6046
6047                if (!doRestore) {
6048                    // No restore possible, or the Backup Manager was mysteriously not
6049                    // available -- just fire the post-install work request directly.
6050                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
6051                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
6052                    mHandler.sendMessage(msg);
6053                }
6054            }
6055        });
6056    }
6057
6058    private abstract class HandlerParams {
6059        private static final int MAX_RETRIES = 4;
6060
6061        /**
6062         * Number of times startCopy() has been attempted and had a non-fatal
6063         * error.
6064         */
6065        private int mRetries = 0;
6066
6067        /** User handle for the user requesting the information or installation. */
6068        private final UserHandle mUser;
6069
6070        HandlerParams(UserHandle user) {
6071            mUser = user;
6072        }
6073
6074        UserHandle getUser() {
6075            return mUser;
6076        }
6077
6078        final boolean startCopy() {
6079            boolean res;
6080            try {
6081                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
6082
6083                if (++mRetries > MAX_RETRIES) {
6084                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
6085                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
6086                    handleServiceError();
6087                    return false;
6088                } else {
6089                    handleStartCopy();
6090                    res = true;
6091                }
6092            } catch (RemoteException e) {
6093                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
6094                mHandler.sendEmptyMessage(MCS_RECONNECT);
6095                res = false;
6096            }
6097            handleReturnCode();
6098            return res;
6099        }
6100
6101        final void serviceError() {
6102            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
6103            handleServiceError();
6104            handleReturnCode();
6105        }
6106
6107        abstract void handleStartCopy() throws RemoteException;
6108        abstract void handleServiceError();
6109        abstract void handleReturnCode();
6110    }
6111
6112    class MeasureParams extends HandlerParams {
6113        private final PackageStats mStats;
6114        private boolean mSuccess;
6115
6116        private final IPackageStatsObserver mObserver;
6117
6118        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
6119            super(new UserHandle(stats.userHandle));
6120            mObserver = observer;
6121            mStats = stats;
6122        }
6123
6124        @Override
6125        void handleStartCopy() throws RemoteException {
6126            synchronized (mInstallLock) {
6127                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
6128            }
6129
6130            final boolean mounted;
6131            if (Environment.isExternalStorageEmulated()) {
6132                mounted = true;
6133            } else {
6134                final String status = Environment.getExternalStorageState();
6135                mounted = (Environment.MEDIA_MOUNTED.equals(status)
6136                        || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
6137            }
6138
6139            if (mounted) {
6140                final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
6141
6142                final File externalCacheDir = userEnv
6143                        .getExternalStorageAppCacheDirectory(mStats.packageName);
6144                final long externalCacheSize = mContainerService
6145                        .calculateDirectorySize(externalCacheDir.getPath());
6146                mStats.externalCacheSize = externalCacheSize;
6147
6148                final File externalDataDir = userEnv
6149                        .getExternalStorageAppDataDirectory(mStats.packageName);
6150                long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
6151                        .getPath());
6152
6153                if (externalCacheDir.getParentFile().equals(externalDataDir)) {
6154                    externalDataSize -= externalCacheSize;
6155                }
6156                mStats.externalDataSize = externalDataSize;
6157
6158                final File externalMediaDir = userEnv
6159                        .getExternalStorageAppMediaDirectory(mStats.packageName);
6160                mStats.externalMediaSize = mContainerService
6161                        .calculateDirectorySize(externalMediaDir.getPath());
6162
6163                final File externalObbDir = userEnv
6164                        .getExternalStorageAppObbDirectory(mStats.packageName);
6165                mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
6166                        .getPath());
6167            }
6168        }
6169
6170        @Override
6171        void handleReturnCode() {
6172            if (mObserver != null) {
6173                try {
6174                    mObserver.onGetStatsCompleted(mStats, mSuccess);
6175                } catch (RemoteException e) {
6176                    Slog.i(TAG, "Observer no longer exists.");
6177                }
6178            }
6179        }
6180
6181        @Override
6182        void handleServiceError() {
6183            Slog.e(TAG, "Could not measure application " + mStats.packageName
6184                            + " external storage");
6185        }
6186    }
6187
6188    class InstallParams extends HandlerParams {
6189        final IPackageInstallObserver observer;
6190        int flags;
6191
6192        private final Uri mPackageURI;
6193        final String installerPackageName;
6194        final VerificationParams verificationParams;
6195        private InstallArgs mArgs;
6196        private int mRet;
6197        private File mTempPackage;
6198        final ContainerEncryptionParams encryptionParams;
6199
6200        InstallParams(Uri packageURI,
6201                IPackageInstallObserver observer, int flags,
6202                String installerPackageName, VerificationParams verificationParams,
6203                ContainerEncryptionParams encryptionParams, UserHandle user) {
6204            super(user);
6205            this.mPackageURI = packageURI;
6206            this.flags = flags;
6207            this.observer = observer;
6208            this.installerPackageName = installerPackageName;
6209            this.verificationParams = verificationParams;
6210            this.encryptionParams = encryptionParams;
6211        }
6212
6213        public ManifestDigest getManifestDigest() {
6214            if (verificationParams == null) {
6215                return null;
6216            }
6217            return verificationParams.getManifestDigest();
6218        }
6219
6220        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
6221            String packageName = pkgLite.packageName;
6222            int installLocation = pkgLite.installLocation;
6223            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6224            // reader
6225            synchronized (mPackages) {
6226                PackageParser.Package pkg = mPackages.get(packageName);
6227                if (pkg != null) {
6228                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
6229                        // Check for downgrading.
6230                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
6231                            if (pkgLite.versionCode < pkg.mVersionCode) {
6232                                Slog.w(TAG, "Can't install update of " + packageName
6233                                        + " update version " + pkgLite.versionCode
6234                                        + " is older than installed version "
6235                                        + pkg.mVersionCode);
6236                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
6237                            }
6238                        }
6239                        // Check for updated system application.
6240                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6241                            if (onSd) {
6242                                Slog.w(TAG, "Cannot install update to system app on sdcard");
6243                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
6244                            }
6245                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6246                        } else {
6247                            if (onSd) {
6248                                // Install flag overrides everything.
6249                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6250                            }
6251                            // If current upgrade specifies particular preference
6252                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
6253                                // Application explicitly specified internal.
6254                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6255                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
6256                                // App explictly prefers external. Let policy decide
6257                            } else {
6258                                // Prefer previous location
6259                                if (isExternal(pkg)) {
6260                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6261                                }
6262                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
6263                            }
6264                        }
6265                    } else {
6266                        // Invalid install. Return error code
6267                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
6268                    }
6269                }
6270            }
6271            // All the special cases have been taken care of.
6272            // Return result based on recommended install location.
6273            if (onSd) {
6274                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
6275            }
6276            return pkgLite.recommendedInstallLocation;
6277        }
6278
6279        /*
6280         * Invoke remote method to get package information and install
6281         * location values. Override install location based on default
6282         * policy if needed and then create install arguments based
6283         * on the install location.
6284         */
6285        public void handleStartCopy() throws RemoteException {
6286            int ret = PackageManager.INSTALL_SUCCEEDED;
6287            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
6288            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
6289            PackageInfoLite pkgLite = null;
6290
6291            if (onInt && onSd) {
6292                // Check if both bits are set.
6293                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
6294                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6295            } else {
6296                final long lowThreshold;
6297
6298                final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6299                        .getService(DeviceStorageMonitorService.SERVICE);
6300                if (dsm == null) {
6301                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6302                    lowThreshold = 0L;
6303                } else {
6304                    lowThreshold = dsm.getMemoryLowThreshold();
6305                }
6306
6307                try {
6308                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
6309                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6310
6311                    final File packageFile;
6312                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
6313                        ParcelFileDescriptor out = null;
6314
6315                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
6316                        if (mTempPackage != null) {
6317                            try {
6318                                out = ParcelFileDescriptor.open(mTempPackage,
6319                                        ParcelFileDescriptor.MODE_READ_WRITE);
6320                            } catch (FileNotFoundException e) {
6321                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
6322                            }
6323
6324                            // Make a temporary file for decryption.
6325                            ret = mContainerService
6326                                    .copyResource(mPackageURI, encryptionParams, out);
6327
6328                            packageFile = mTempPackage;
6329
6330                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
6331                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
6332                                            | FileUtils.S_IROTH,
6333                                    -1, -1);
6334                        } else {
6335                            packageFile = null;
6336                        }
6337                    } else {
6338                        packageFile = new File(mPackageURI.getPath());
6339                    }
6340
6341                    if (packageFile != null) {
6342                        // Remote call to find out default install location
6343                        pkgLite = mContainerService.getMinimalPackageInfo(
6344                                packageFile.getAbsolutePath(), flags, lowThreshold);
6345                    }
6346                } finally {
6347                    mContext.revokeUriPermission(mPackageURI,
6348                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
6349                }
6350            }
6351
6352            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6353                int loc = pkgLite.recommendedInstallLocation;
6354                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
6355                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6356                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
6357                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
6358                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
6359                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6360                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
6361                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
6362                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
6363                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
6364                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
6365                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
6366                } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
6367                    ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
6368                } else {
6369                    // Override with defaults if needed.
6370                    loc = installLocationPolicy(pkgLite, flags);
6371                    if (!onSd && !onInt) {
6372                        // Override install location with flags
6373                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
6374                            // Set the flag to install on external media.
6375                            flags |= PackageManager.INSTALL_EXTERNAL;
6376                            flags &= ~PackageManager.INSTALL_INTERNAL;
6377                        } else {
6378                            // Make sure the flag for installing on external
6379                            // media is unset
6380                            flags |= PackageManager.INSTALL_INTERNAL;
6381                            flags &= ~PackageManager.INSTALL_EXTERNAL;
6382                        }
6383                    }
6384                }
6385            }
6386
6387            final InstallArgs args = createInstallArgs(this);
6388            mArgs = args;
6389
6390            if (ret == PackageManager.INSTALL_SUCCEEDED) {
6391                /*
6392                 * Determine if we have any installed package verifiers. If we
6393                 * do, then we'll defer to them to verify the packages.
6394                 */
6395                final int requiredUid = mRequiredVerifierPackage == null ? -1
6396                        : getPackageUid(mRequiredVerifierPackage, 0);
6397                if (requiredUid != -1 && isVerificationEnabled(flags)) {
6398                    final Intent verification = new Intent(
6399                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
6400                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
6401                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6402
6403                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
6404                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
6405                            0 /* TODO: Which userId? */);
6406
6407                    if (DEBUG_VERIFY) {
6408                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
6409                                + verification.toString() + " with " + pkgLite.verifiers.length
6410                                + " optional verifiers");
6411                    }
6412
6413                    final int verificationId = mPendingVerificationToken++;
6414
6415                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
6416
6417                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
6418                            installerPackageName);
6419
6420                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
6421
6422                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
6423                            pkgLite.packageName);
6424
6425                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
6426                            pkgLite.versionCode);
6427
6428                    if (verificationParams != null) {
6429                        if (verificationParams.getVerificationURI() != null) {
6430                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
6431                                 verificationParams.getVerificationURI());
6432                        }
6433                        if (verificationParams.getOriginatingURI() != null) {
6434                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
6435                                  verificationParams.getOriginatingURI());
6436                        }
6437                        if (verificationParams.getReferrer() != null) {
6438                            verification.putExtra(Intent.EXTRA_REFERRER,
6439                                  verificationParams.getReferrer());
6440                        }
6441                        if (verificationParams.getInstallerUid() >= 0) {
6442                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
6443                                  verificationParams.getInstallerUid());
6444                        }
6445                    }
6446
6447                    final PackageVerificationState verificationState = new PackageVerificationState(
6448                            requiredUid, args);
6449
6450                    mPendingVerification.append(verificationId, verificationState);
6451
6452                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
6453                            receivers, verificationState);
6454
6455                    /*
6456                     * If any sufficient verifiers were listed in the package
6457                     * manifest, attempt to ask them.
6458                     */
6459                    if (sufficientVerifiers != null) {
6460                        final int N = sufficientVerifiers.size();
6461                        if (N == 0) {
6462                            Slog.i(TAG, "Additional verifiers required, but none installed.");
6463                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
6464                        } else {
6465                            for (int i = 0; i < N; i++) {
6466                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
6467
6468                                final Intent sufficientIntent = new Intent(verification);
6469                                sufficientIntent.setComponent(verifierComponent);
6470
6471                                mContext.sendBroadcast(sufficientIntent);
6472                            }
6473                        }
6474                    }
6475
6476                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
6477                            mRequiredVerifierPackage, receivers);
6478                    if (ret == PackageManager.INSTALL_SUCCEEDED
6479                            && mRequiredVerifierPackage != null) {
6480                        /*
6481                         * Send the intent to the required verification agent,
6482                         * but only start the verification timeout after the
6483                         * target BroadcastReceivers have run.
6484                         */
6485                        verification.setComponent(requiredVerifierComponent);
6486                        mContext.sendOrderedBroadcast(verification,
6487                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6488                                new BroadcastReceiver() {
6489                                    @Override
6490                                    public void onReceive(Context context, Intent intent) {
6491                                        final Message msg = mHandler
6492                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
6493                                        msg.arg1 = verificationId;
6494                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
6495                                    }
6496                                }, null, 0, null, null);
6497
6498                        /*
6499                         * We don't want the copy to proceed until verification
6500                         * succeeds, so null out this field.
6501                         */
6502                        mArgs = null;
6503                    }
6504                } else {
6505                    /*
6506                     * No package verification is enabled, so immediately start
6507                     * the remote call to initiate copy using temporary file.
6508                     */
6509                    ret = args.copyApk(mContainerService, true);
6510                }
6511            }
6512
6513            mRet = ret;
6514        }
6515
6516        @Override
6517        void handleReturnCode() {
6518            // If mArgs is null, then MCS couldn't be reached. When it
6519            // reconnects, it will try again to install. At that point, this
6520            // will succeed.
6521            if (mArgs != null) {
6522                processPendingInstall(mArgs, mRet);
6523
6524                if (mTempPackage != null) {
6525                    if (!mTempPackage.delete()) {
6526                        Slog.w(TAG, "Couldn't delete temporary file: " +
6527                                mTempPackage.getAbsolutePath());
6528                    }
6529                }
6530            }
6531        }
6532
6533        @Override
6534        void handleServiceError() {
6535            mArgs = createInstallArgs(this);
6536            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6537        }
6538
6539        public boolean isForwardLocked() {
6540            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6541        }
6542
6543        public Uri getPackageUri() {
6544            if (mTempPackage != null) {
6545                return Uri.fromFile(mTempPackage);
6546            } else {
6547                return mPackageURI;
6548            }
6549        }
6550    }
6551
6552    /*
6553     * Utility class used in movePackage api.
6554     * srcArgs and targetArgs are not set for invalid flags and make
6555     * sure to do null checks when invoking methods on them.
6556     * We probably want to return ErrorPrams for both failed installs
6557     * and moves.
6558     */
6559    class MoveParams extends HandlerParams {
6560        final IPackageMoveObserver observer;
6561        final int flags;
6562        final String packageName;
6563        final InstallArgs srcArgs;
6564        final InstallArgs targetArgs;
6565        int uid;
6566        int mRet;
6567
6568        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
6569                String packageName, String dataDir, int uid, UserHandle user) {
6570            super(user);
6571            this.srcArgs = srcArgs;
6572            this.observer = observer;
6573            this.flags = flags;
6574            this.packageName = packageName;
6575            this.uid = uid;
6576            if (srcArgs != null) {
6577                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
6578                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
6579            } else {
6580                targetArgs = null;
6581            }
6582        }
6583
6584        public void handleStartCopy() throws RemoteException {
6585            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6586            // Check for storage space on target medium
6587            if (!targetArgs.checkFreeStorage(mContainerService)) {
6588                Log.w(TAG, "Insufficient storage to install");
6589                return;
6590            }
6591
6592            mRet = srcArgs.doPreCopy();
6593            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6594                return;
6595            }
6596
6597            mRet = targetArgs.copyApk(mContainerService, false);
6598            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6599                srcArgs.doPostCopy(uid);
6600                return;
6601            }
6602
6603            mRet = srcArgs.doPostCopy(uid);
6604            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6605                return;
6606            }
6607
6608            mRet = targetArgs.doPreInstall(mRet);
6609            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
6610                return;
6611            }
6612
6613            if (DEBUG_SD_INSTALL) {
6614                StringBuilder builder = new StringBuilder();
6615                if (srcArgs != null) {
6616                    builder.append("src: ");
6617                    builder.append(srcArgs.getCodePath());
6618                }
6619                if (targetArgs != null) {
6620                    builder.append(" target : ");
6621                    builder.append(targetArgs.getCodePath());
6622                }
6623                Log.i(TAG, builder.toString());
6624            }
6625        }
6626
6627        @Override
6628        void handleReturnCode() {
6629            targetArgs.doPostInstall(mRet, uid);
6630            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
6631            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
6632                currentStatus = PackageManager.MOVE_SUCCEEDED;
6633            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
6634                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
6635            }
6636            processPendingMove(this, currentStatus);
6637        }
6638
6639        @Override
6640        void handleServiceError() {
6641            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6642        }
6643    }
6644
6645    /**
6646     * Used during creation of InstallArgs
6647     *
6648     * @param flags package installation flags
6649     * @return true if should be installed on external storage
6650     */
6651    private static boolean installOnSd(int flags) {
6652        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
6653            return false;
6654        }
6655        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
6656            return true;
6657        }
6658        return false;
6659    }
6660
6661    /**
6662     * Used during creation of InstallArgs
6663     *
6664     * @param flags package installation flags
6665     * @return true if should be installed as forward locked
6666     */
6667    private static boolean installForwardLocked(int flags) {
6668        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6669    }
6670
6671    private InstallArgs createInstallArgs(InstallParams params) {
6672        if (installOnSd(params.flags) || params.isForwardLocked()) {
6673            return new AsecInstallArgs(params);
6674        } else {
6675            return new FileInstallArgs(params);
6676        }
6677    }
6678
6679    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
6680            String nativeLibraryPath) {
6681        final boolean isInAsec;
6682        if (installOnSd(flags)) {
6683            /* Apps on SD card are always in ASEC containers. */
6684            isInAsec = true;
6685        } else if (installForwardLocked(flags)
6686                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
6687            /*
6688             * Forward-locked apps are only in ASEC containers if they're the
6689             * new style
6690             */
6691            isInAsec = true;
6692        } else {
6693            isInAsec = false;
6694        }
6695
6696        if (isInAsec) {
6697            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
6698                    installOnSd(flags), installForwardLocked(flags));
6699        } else {
6700            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
6701        }
6702    }
6703
6704    // Used by package mover
6705    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
6706        if (installOnSd(flags) || installForwardLocked(flags)) {
6707            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
6708                    + AsecInstallArgs.RES_FILE_NAME);
6709            return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
6710                    installForwardLocked(flags));
6711        } else {
6712            return new FileInstallArgs(packageURI, pkgName, dataDir);
6713        }
6714    }
6715
6716    static abstract class InstallArgs {
6717        final IPackageInstallObserver observer;
6718        // Always refers to PackageManager flags only
6719        final int flags;
6720        final Uri packageURI;
6721        final String installerPackageName;
6722        final ManifestDigest manifestDigest;
6723        final UserHandle user;
6724
6725        InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
6726                String installerPackageName, ManifestDigest manifestDigest,
6727                UserHandle user) {
6728            this.packageURI = packageURI;
6729            this.flags = flags;
6730            this.observer = observer;
6731            this.installerPackageName = installerPackageName;
6732            this.manifestDigest = manifestDigest;
6733            this.user = user;
6734        }
6735
6736        abstract void createCopyFile();
6737        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
6738        abstract int doPreInstall(int status);
6739        abstract boolean doRename(int status, String pkgName, String oldCodePath);
6740
6741        abstract int doPostInstall(int status, int uid);
6742        abstract String getCodePath();
6743        abstract String getResourcePath();
6744        abstract String getNativeLibraryPath();
6745        // Need installer lock especially for dex file removal.
6746        abstract void cleanUpResourcesLI();
6747        abstract boolean doPostDeleteLI(boolean delete);
6748        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
6749
6750        /**
6751         * Called before the source arguments are copied. This is used mostly
6752         * for MoveParams when it needs to read the source file to put it in the
6753         * destination.
6754         */
6755        int doPreCopy() {
6756            return PackageManager.INSTALL_SUCCEEDED;
6757        }
6758
6759        /**
6760         * Called after the source arguments are copied. This is used mostly for
6761         * MoveParams when it needs to read the source file to put it in the
6762         * destination.
6763         *
6764         * @return
6765         */
6766        int doPostCopy(int uid) {
6767            return PackageManager.INSTALL_SUCCEEDED;
6768        }
6769
6770        protected boolean isFwdLocked() {
6771            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
6772        }
6773    }
6774
6775    class FileInstallArgs extends InstallArgs {
6776        File installDir;
6777        String codeFileName;
6778        String resourceFileName;
6779        String libraryPath;
6780        boolean created = false;
6781
6782        FileInstallArgs(InstallParams params) {
6783            super(params.getPackageUri(), params.observer, params.flags,
6784                    params.installerPackageName, params.getManifestDigest(),
6785                    params.getUser());
6786        }
6787
6788        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
6789            super(null, null, 0, null, null, null);
6790            File codeFile = new File(fullCodePath);
6791            installDir = codeFile.getParentFile();
6792            codeFileName = fullCodePath;
6793            resourceFileName = fullResourcePath;
6794            libraryPath = nativeLibraryPath;
6795        }
6796
6797        FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
6798            super(packageURI, null, 0, null, null, null);
6799            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6800            String apkName = getNextCodePath(null, pkgName, ".apk");
6801            codeFileName = new File(installDir, apkName + ".apk").getPath();
6802            resourceFileName = getResourcePathFromCodePath();
6803            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
6804        }
6805
6806        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
6807            final long lowThreshold;
6808
6809            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
6810                    .getService(DeviceStorageMonitorService.SERVICE);
6811            if (dsm == null) {
6812                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
6813                lowThreshold = 0L;
6814            } else {
6815                if (dsm.isMemoryLow()) {
6816                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
6817                    return false;
6818                }
6819
6820                lowThreshold = dsm.getMemoryLowThreshold();
6821            }
6822
6823            try {
6824                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6825                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6826                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
6827            } finally {
6828                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6829            }
6830        }
6831
6832        String getCodePath() {
6833            return codeFileName;
6834        }
6835
6836        void createCopyFile() {
6837            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
6838            codeFileName = createTempPackageFile(installDir).getPath();
6839            resourceFileName = getResourcePathFromCodePath();
6840            libraryPath = getLibraryPathFromCodePath();
6841            created = true;
6842        }
6843
6844        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
6845            if (temp) {
6846                // Generate temp file name
6847                createCopyFile();
6848            }
6849            // Get a ParcelFileDescriptor to write to the output file
6850            File codeFile = new File(codeFileName);
6851            if (!created) {
6852                try {
6853                    codeFile.createNewFile();
6854                    // Set permissions
6855                    if (!setPermissions()) {
6856                        // Failed setting permissions.
6857                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6858                    }
6859                } catch (IOException e) {
6860                   Slog.w(TAG, "Failed to create file " + codeFile);
6861                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6862                }
6863            }
6864            ParcelFileDescriptor out = null;
6865            try {
6866                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
6867            } catch (FileNotFoundException e) {
6868                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
6869                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6870            }
6871            // Copy the resource now
6872            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6873            try {
6874                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
6875                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
6876                ret = imcs.copyResource(packageURI, null, out);
6877            } finally {
6878                IoUtils.closeQuietly(out);
6879                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
6880            }
6881
6882            if (isFwdLocked()) {
6883                final File destResourceFile = new File(getResourcePath());
6884
6885                // Copy the public files
6886                try {
6887                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
6888                } catch (IOException e) {
6889                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
6890                            + " forward-locked app.");
6891                    destResourceFile.delete();
6892                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6893                }
6894            }
6895
6896            final File nativeLibraryFile = new File(getNativeLibraryPath());
6897            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
6898            if (nativeLibraryFile.exists()) {
6899                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
6900                nativeLibraryFile.delete();
6901            }
6902            try {
6903                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
6904                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6905                    return copyRet;
6906                }
6907            } catch (IOException e) {
6908                Slog.e(TAG, "Copying native libraries failed", e);
6909                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
6910            }
6911
6912            return ret;
6913        }
6914
6915        int doPreInstall(int status) {
6916            if (status != PackageManager.INSTALL_SUCCEEDED) {
6917                cleanUp();
6918            }
6919            return status;
6920        }
6921
6922        boolean doRename(int status, final String pkgName, String oldCodePath) {
6923            if (status != PackageManager.INSTALL_SUCCEEDED) {
6924                cleanUp();
6925                return false;
6926            } else {
6927                final File oldCodeFile = new File(getCodePath());
6928                final File oldResourceFile = new File(getResourcePath());
6929                final File oldLibraryFile = new File(getNativeLibraryPath());
6930
6931                // Rename APK file based on packageName
6932                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
6933                final File newCodeFile = new File(installDir, apkName + ".apk");
6934                if (!oldCodeFile.renameTo(newCodeFile)) {
6935                    return false;
6936                }
6937                codeFileName = newCodeFile.getPath();
6938
6939                // Rename public resource file if it's forward-locked.
6940                final File newResFile = new File(getResourcePathFromCodePath());
6941                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
6942                    return false;
6943                }
6944                resourceFileName = newResFile.getPath();
6945
6946                // Rename library path
6947                final File newLibraryFile = new File(getLibraryPathFromCodePath());
6948                if (newLibraryFile.exists()) {
6949                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
6950                    newLibraryFile.delete();
6951                }
6952                if (!oldLibraryFile.renameTo(newLibraryFile)) {
6953                    Slog.e(TAG, "Cannot rename native library directory "
6954                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
6955                    return false;
6956                }
6957                libraryPath = newLibraryFile.getPath();
6958
6959                // Attempt to set permissions
6960                if (!setPermissions()) {
6961                    return false;
6962                }
6963
6964                if (!SELinux.restorecon(newCodeFile)) {
6965                    return false;
6966                }
6967
6968                return true;
6969            }
6970        }
6971
6972        int doPostInstall(int status, int uid) {
6973            if (status != PackageManager.INSTALL_SUCCEEDED) {
6974                cleanUp();
6975            }
6976            return status;
6977        }
6978
6979        String getResourcePath() {
6980            return resourceFileName;
6981        }
6982
6983        private String getResourcePathFromCodePath() {
6984            final String codePath = getCodePath();
6985            if (isFwdLocked()) {
6986                final StringBuilder sb = new StringBuilder();
6987
6988                sb.append(mAppInstallDir.getPath());
6989                sb.append('/');
6990                sb.append(getApkName(codePath));
6991                sb.append(".zip");
6992
6993                /*
6994                 * If our APK is a temporary file, mark the resource as a
6995                 * temporary file as well so it can be cleaned up after
6996                 * catastrophic failure.
6997                 */
6998                if (codePath.endsWith(".tmp")) {
6999                    sb.append(".tmp");
7000                }
7001
7002                return sb.toString();
7003            } else {
7004                return codePath;
7005            }
7006        }
7007
7008        private String getLibraryPathFromCodePath() {
7009            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
7010        }
7011
7012        @Override
7013        String getNativeLibraryPath() {
7014            if (libraryPath == null) {
7015                libraryPath = getLibraryPathFromCodePath();
7016            }
7017            return libraryPath;
7018        }
7019
7020        private boolean cleanUp() {
7021            boolean ret = true;
7022            String sourceDir = getCodePath();
7023            String publicSourceDir = getResourcePath();
7024            if (sourceDir != null) {
7025                File sourceFile = new File(sourceDir);
7026                if (!sourceFile.exists()) {
7027                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
7028                    ret = false;
7029                }
7030                // Delete application's code and resources
7031                sourceFile.delete();
7032            }
7033            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
7034                final File publicSourceFile = new File(publicSourceDir);
7035                if (!publicSourceFile.exists()) {
7036                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
7037                }
7038                if (publicSourceFile.exists()) {
7039                    publicSourceFile.delete();
7040                }
7041            }
7042
7043            if (libraryPath != null) {
7044                File nativeLibraryFile = new File(libraryPath);
7045                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
7046                if (!nativeLibraryFile.delete()) {
7047                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
7048                }
7049            }
7050
7051            return ret;
7052        }
7053
7054        void cleanUpResourcesLI() {
7055            String sourceDir = getCodePath();
7056            if (cleanUp()) {
7057                int retCode = mInstaller.rmdex(sourceDir);
7058                if (retCode < 0) {
7059                    Slog.w(TAG, "Couldn't remove dex file for package: "
7060                            +  " at location "
7061                            + sourceDir + ", retcode=" + retCode);
7062                    // we don't consider this to be a failure of the core package deletion
7063                }
7064            }
7065        }
7066
7067        private boolean setPermissions() {
7068            // TODO Do this in a more elegant way later on. for now just a hack
7069            if (!isFwdLocked()) {
7070                final int filePermissions =
7071                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
7072                    |FileUtils.S_IROTH;
7073                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
7074                if (retCode != 0) {
7075                    Slog.e(TAG, "Couldn't set new package file permissions for " +
7076                            getCodePath()
7077                            + ". The return code was: " + retCode);
7078                    // TODO Define new internal error
7079                    return false;
7080                }
7081                return true;
7082            }
7083            return true;
7084        }
7085
7086        boolean doPostDeleteLI(boolean delete) {
7087            // XXX err, shouldn't we respect the delete flag?
7088            cleanUpResourcesLI();
7089            return true;
7090        }
7091    }
7092
7093    private boolean isAsecExternal(String cid) {
7094        final String asecPath = PackageHelper.getSdFilesystem(cid);
7095        return !asecPath.startsWith(mAsecInternalPath);
7096    }
7097
7098    /**
7099     * Extract the MountService "container ID" from the full code path of an
7100     * .apk.
7101     */
7102    static String cidFromCodePath(String fullCodePath) {
7103        int eidx = fullCodePath.lastIndexOf("/");
7104        String subStr1 = fullCodePath.substring(0, eidx);
7105        int sidx = subStr1.lastIndexOf("/");
7106        return subStr1.substring(sidx+1, eidx);
7107    }
7108
7109    class AsecInstallArgs extends InstallArgs {
7110        static final String RES_FILE_NAME = "pkg.apk";
7111        static final String PUBLIC_RES_FILE_NAME = "res.zip";
7112
7113        String cid;
7114        String packagePath;
7115        String resourcePath;
7116        String libraryPath;
7117
7118        AsecInstallArgs(InstallParams params) {
7119            super(params.getPackageUri(), params.observer, params.flags,
7120                    params.installerPackageName, params.getManifestDigest(),
7121                    params.getUser());
7122        }
7123
7124        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
7125                boolean isExternal, boolean isForwardLocked) {
7126            super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7127                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7128                    null, null, null);
7129            // Extract cid from fullCodePath
7130            int eidx = fullCodePath.lastIndexOf("/");
7131            String subStr1 = fullCodePath.substring(0, eidx);
7132            int sidx = subStr1.lastIndexOf("/");
7133            cid = subStr1.substring(sidx+1, eidx);
7134            setCachePath(subStr1);
7135        }
7136
7137        AsecInstallArgs(String cid, boolean isForwardLocked) {
7138            super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
7139                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7140                    null, null, null);
7141            this.cid = cid;
7142            setCachePath(PackageHelper.getSdDir(cid));
7143        }
7144
7145        AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
7146            super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
7147                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
7148                    null, null, null);
7149            this.cid = cid;
7150        }
7151
7152        void createCopyFile() {
7153            cid = getTempContainerId();
7154        }
7155
7156        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
7157            try {
7158                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7159                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7160                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
7161            } finally {
7162                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7163            }
7164        }
7165
7166        private final boolean isExternal() {
7167            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
7168        }
7169
7170        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
7171            if (temp) {
7172                createCopyFile();
7173            } else {
7174                /*
7175                 * Pre-emptively destroy the container since it's destroyed if
7176                 * copying fails due to it existing anyway.
7177                 */
7178                PackageHelper.destroySdDir(cid);
7179            }
7180
7181            final String newCachePath;
7182            try {
7183                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
7184                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
7185                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
7186                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
7187            } finally {
7188                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
7189            }
7190
7191            if (newCachePath != null) {
7192                setCachePath(newCachePath);
7193                return PackageManager.INSTALL_SUCCEEDED;
7194            } else {
7195                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7196            }
7197        }
7198
7199        @Override
7200        String getCodePath() {
7201            return packagePath;
7202        }
7203
7204        @Override
7205        String getResourcePath() {
7206            return resourcePath;
7207        }
7208
7209        @Override
7210        String getNativeLibraryPath() {
7211            return libraryPath;
7212        }
7213
7214        int doPreInstall(int status) {
7215            if (status != PackageManager.INSTALL_SUCCEEDED) {
7216                // Destroy container
7217                PackageHelper.destroySdDir(cid);
7218            } else {
7219                boolean mounted = PackageHelper.isContainerMounted(cid);
7220                if (!mounted) {
7221                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
7222                            Process.SYSTEM_UID);
7223                    if (newCachePath != null) {
7224                        setCachePath(newCachePath);
7225                    } else {
7226                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7227                    }
7228                }
7229            }
7230            return status;
7231        }
7232
7233        boolean doRename(int status, final String pkgName,
7234                String oldCodePath) {
7235            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
7236            String newCachePath = null;
7237            if (PackageHelper.isContainerMounted(cid)) {
7238                // Unmount the container
7239                if (!PackageHelper.unMountSdDir(cid)) {
7240                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
7241                    return false;
7242                }
7243            }
7244            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7245                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
7246                        " which might be stale. Will try to clean up.");
7247                // Clean up the stale container and proceed to recreate.
7248                if (!PackageHelper.destroySdDir(newCacheId)) {
7249                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
7250                    return false;
7251                }
7252                // Successfully cleaned up stale container. Try to rename again.
7253                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
7254                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
7255                            + " inspite of cleaning it up.");
7256                    return false;
7257                }
7258            }
7259            if (!PackageHelper.isContainerMounted(newCacheId)) {
7260                Slog.w(TAG, "Mounting container " + newCacheId);
7261                newCachePath = PackageHelper.mountSdDir(newCacheId,
7262                        getEncryptKey(), Process.SYSTEM_UID);
7263            } else {
7264                newCachePath = PackageHelper.getSdDir(newCacheId);
7265            }
7266            if (newCachePath == null) {
7267                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
7268                return false;
7269            }
7270            Log.i(TAG, "Succesfully renamed " + cid +
7271                    " to " + newCacheId +
7272                    " at new path: " + newCachePath);
7273            cid = newCacheId;
7274            setCachePath(newCachePath);
7275            return true;
7276        }
7277
7278        private void setCachePath(String newCachePath) {
7279            File cachePath = new File(newCachePath);
7280            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
7281            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
7282
7283            if (isFwdLocked()) {
7284                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
7285            } else {
7286                resourcePath = packagePath;
7287            }
7288        }
7289
7290        int doPostInstall(int status, int uid) {
7291            if (status != PackageManager.INSTALL_SUCCEEDED) {
7292                cleanUp();
7293            } else {
7294                final int groupOwner;
7295                final String protectedFile;
7296                if (isFwdLocked()) {
7297                    groupOwner = UserHandle.getSharedAppGid(uid);
7298                    protectedFile = RES_FILE_NAME;
7299                } else {
7300                    groupOwner = -1;
7301                    protectedFile = null;
7302                }
7303
7304                if (uid < Process.FIRST_APPLICATION_UID
7305                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
7306                    Slog.e(TAG, "Failed to finalize " + cid);
7307                    PackageHelper.destroySdDir(cid);
7308                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7309                }
7310
7311                boolean mounted = PackageHelper.isContainerMounted(cid);
7312                if (!mounted) {
7313                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
7314                }
7315            }
7316            return status;
7317        }
7318
7319        private void cleanUp() {
7320            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
7321
7322            // Destroy secure container
7323            PackageHelper.destroySdDir(cid);
7324        }
7325
7326        void cleanUpResourcesLI() {
7327            String sourceFile = getCodePath();
7328            // Remove dex file
7329            int retCode = mInstaller.rmdex(sourceFile);
7330            if (retCode < 0) {
7331                Slog.w(TAG, "Couldn't remove dex file for package: "
7332                        + " at location "
7333                        + sourceFile.toString() + ", retcode=" + retCode);
7334                // we don't consider this to be a failure of the core package deletion
7335            }
7336            cleanUp();
7337        }
7338
7339        boolean matchContainer(String app) {
7340            if (cid.startsWith(app)) {
7341                return true;
7342            }
7343            return false;
7344        }
7345
7346        String getPackageName() {
7347            return getAsecPackageName(cid);
7348        }
7349
7350        boolean doPostDeleteLI(boolean delete) {
7351            boolean ret = false;
7352            boolean mounted = PackageHelper.isContainerMounted(cid);
7353            if (mounted) {
7354                // Unmount first
7355                ret = PackageHelper.unMountSdDir(cid);
7356            }
7357            if (ret && delete) {
7358                cleanUpResourcesLI();
7359            }
7360            return ret;
7361        }
7362
7363        @Override
7364        int doPreCopy() {
7365            if (isFwdLocked()) {
7366                if (!PackageHelper.fixSdPermissions(cid,
7367                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
7368                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7369                }
7370            }
7371
7372            return PackageManager.INSTALL_SUCCEEDED;
7373        }
7374
7375        @Override
7376        int doPostCopy(int uid) {
7377            if (isFwdLocked()) {
7378                if (uid < Process.FIRST_APPLICATION_UID
7379                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
7380                                RES_FILE_NAME)) {
7381                    Slog.e(TAG, "Failed to finalize " + cid);
7382                    PackageHelper.destroySdDir(cid);
7383                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
7384                }
7385            }
7386
7387            return PackageManager.INSTALL_SUCCEEDED;
7388        }
7389    };
7390
7391    static String getAsecPackageName(String packageCid) {
7392        int idx = packageCid.lastIndexOf("-");
7393        if (idx == -1) {
7394            return packageCid;
7395        }
7396        return packageCid.substring(0, idx);
7397    }
7398
7399    // Utility method used to create code paths based on package name and available index.
7400    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
7401        String idxStr = "";
7402        int idx = 1;
7403        // Fall back to default value of idx=1 if prefix is not
7404        // part of oldCodePath
7405        if (oldCodePath != null) {
7406            String subStr = oldCodePath;
7407            // Drop the suffix right away
7408            if (subStr.endsWith(suffix)) {
7409                subStr = subStr.substring(0, subStr.length() - suffix.length());
7410            }
7411            // If oldCodePath already contains prefix find out the
7412            // ending index to either increment or decrement.
7413            int sidx = subStr.lastIndexOf(prefix);
7414            if (sidx != -1) {
7415                subStr = subStr.substring(sidx + prefix.length());
7416                if (subStr != null) {
7417                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
7418                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
7419                    }
7420                    try {
7421                        idx = Integer.parseInt(subStr);
7422                        if (idx <= 1) {
7423                            idx++;
7424                        } else {
7425                            idx--;
7426                        }
7427                    } catch(NumberFormatException e) {
7428                    }
7429                }
7430            }
7431        }
7432        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
7433        return prefix + idxStr;
7434    }
7435
7436    // Utility method used to ignore ADD/REMOVE events
7437    // by directory observer.
7438    private static boolean ignoreCodePath(String fullPathStr) {
7439        String apkName = getApkName(fullPathStr);
7440        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
7441        if (idx != -1 && ((idx+1) < apkName.length())) {
7442            // Make sure the package ends with a numeral
7443            String version = apkName.substring(idx+1);
7444            try {
7445                Integer.parseInt(version);
7446                return true;
7447            } catch (NumberFormatException e) {}
7448        }
7449        return false;
7450    }
7451
7452    // Utility method that returns the relative package path with respect
7453    // to the installation directory. Like say for /data/data/com.test-1.apk
7454    // string com.test-1 is returned.
7455    static String getApkName(String codePath) {
7456        if (codePath == null) {
7457            return null;
7458        }
7459        int sidx = codePath.lastIndexOf("/");
7460        int eidx = codePath.lastIndexOf(".");
7461        if (eidx == -1) {
7462            eidx = codePath.length();
7463        } else if (eidx == 0) {
7464            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
7465            return null;
7466        }
7467        return codePath.substring(sidx+1, eidx);
7468    }
7469
7470    class PackageInstalledInfo {
7471        String name;
7472        int uid;
7473        // The set of users that originally had this package installed.
7474        int[] origUsers;
7475        // The set of users that now have this package installed.
7476        int[] newUsers;
7477        PackageParser.Package pkg;
7478        int returnCode;
7479        PackageRemovedInfo removedInfo;
7480    }
7481
7482    /*
7483     * Install a non-existing package.
7484     */
7485    private void installNewPackageLI(PackageParser.Package pkg,
7486            int parseFlags, int scanMode, UserHandle user,
7487            String installerPackageName, PackageInstalledInfo res) {
7488        // Remember this for later, in case we need to rollback this install
7489        String pkgName = pkg.packageName;
7490
7491        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
7492        synchronized(mPackages) {
7493            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
7494                // A package with the same name is already installed, though
7495                // it has been renamed to an older name.  The package we
7496                // are trying to install should be installed as an update to
7497                // the existing one, but that has not been requested, so bail.
7498                Slog.w(TAG, "Attempt to re-install " + pkgName
7499                        + " without first uninstalling package running as "
7500                        + mSettings.mRenamedPackages.get(pkgName));
7501                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7502                return;
7503            }
7504            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
7505                // Don't allow installation over an existing package with the same name.
7506                Slog.w(TAG, "Attempt to re-install " + pkgName
7507                        + " without first uninstalling.");
7508                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
7509                return;
7510            }
7511        }
7512        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7513        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
7514                System.currentTimeMillis(), user);
7515        if (newPackage == null) {
7516            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7517            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7518                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7519            }
7520        } else {
7521            updateSettingsLI(newPackage,
7522                    installerPackageName,
7523                    res);
7524            // delete the partially installed application. the data directory will have to be
7525            // restored if it was already existing
7526            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7527                // remove package from internal structures.  Note that we want deletePackageX to
7528                // delete the package data and cache directories that it created in
7529                // scanPackageLocked, unless those directories existed before we even tried to
7530                // install.
7531                deletePackageLI(pkgName, UserHandle.ALL, false,
7532                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
7533                                res.removedInfo, true);
7534            }
7535        }
7536    }
7537
7538    private void replacePackageLI(PackageParser.Package pkg,
7539            int parseFlags, int scanMode, UserHandle user,
7540            String installerPackageName, PackageInstalledInfo res) {
7541
7542        PackageParser.Package oldPackage;
7543        String pkgName = pkg.packageName;
7544        // First find the old package info and check signatures
7545        synchronized(mPackages) {
7546            oldPackage = mPackages.get(pkgName);
7547            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
7548                    != PackageManager.SIGNATURE_MATCH) {
7549                Slog.w(TAG, "New package has a different signature: " + pkgName);
7550                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
7551                return;
7552            }
7553        }
7554        boolean sysPkg = (isSystemApp(oldPackage));
7555        if (sysPkg) {
7556            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7557                    user, installerPackageName, res);
7558        } else {
7559            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
7560                    user, installerPackageName, res);
7561        }
7562    }
7563
7564    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
7565            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7566            String installerPackageName, PackageInstalledInfo res) {
7567        PackageParser.Package newPackage = null;
7568        String pkgName = deletedPackage.packageName;
7569        boolean deletedPkg = true;
7570        boolean updatedSettings = false;
7571
7572        long origUpdateTime;
7573        if (pkg.mExtras != null) {
7574            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
7575        } else {
7576            origUpdateTime = 0;
7577        }
7578
7579        // First delete the existing package while retaining the data directory
7580        if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA,
7581                res.removedInfo, true)) {
7582            // If the existing package wasn't successfully deleted
7583            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7584            deletedPkg = false;
7585        } else {
7586            // Successfully deleted the old package. Now proceed with re-installation
7587            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7588            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
7589                    System.currentTimeMillis(), user);
7590            if (newPackage == null) {
7591                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7592                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7593                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7594                }
7595            } else {
7596                updateSettingsLI(newPackage,
7597                        installerPackageName,
7598                        res);
7599                updatedSettings = true;
7600            }
7601        }
7602
7603        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7604            // remove package from internal structures.  Note that we want deletePackageX to
7605            // delete the package data and cache directories that it created in
7606            // scanPackageLocked, unless those directories existed before we even tried to
7607            // install.
7608            if(updatedSettings) {
7609                deletePackageLI(
7610                        pkgName, null, true,
7611                        PackageManager.DELETE_KEEP_DATA,
7612                                res.removedInfo, true);
7613            }
7614            // Since we failed to install the new package we need to restore the old
7615            // package that we deleted.
7616            if(deletedPkg) {
7617                File restoreFile = new File(deletedPackage.mPath);
7618                // Parse old package
7619                boolean oldOnSd = isExternal(deletedPackage);
7620                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
7621                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
7622                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
7623                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
7624                        | SCAN_UPDATE_TIME;
7625                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
7626                        origUpdateTime, null) == null) {
7627                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
7628                    return;
7629                }
7630                // Restore of old package succeeded. Update permissions.
7631                // writer
7632                synchronized (mPackages) {
7633                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
7634                            UPDATE_PERMISSIONS_ALL);
7635                    // can downgrade to reader
7636                    mSettings.writeLPr();
7637                }
7638                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
7639            }
7640        }
7641    }
7642
7643    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
7644            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
7645            String installerPackageName, PackageInstalledInfo res) {
7646        PackageParser.Package newPackage = null;
7647        boolean updatedSettings = false;
7648        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
7649                PackageParser.PARSE_IS_SYSTEM;
7650        String packageName = deletedPackage.packageName;
7651        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
7652        if (packageName == null) {
7653            Slog.w(TAG, "Attempt to delete null packageName.");
7654            return;
7655        }
7656        PackageParser.Package oldPkg;
7657        PackageSetting oldPkgSetting;
7658        // reader
7659        synchronized (mPackages) {
7660            oldPkg = mPackages.get(packageName);
7661            oldPkgSetting = mSettings.mPackages.get(packageName);
7662            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
7663                    (oldPkgSetting == null)) {
7664                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
7665                return;
7666            }
7667        }
7668
7669        killApplication(packageName, oldPkg.applicationInfo.uid);
7670
7671        res.removedInfo.uid = oldPkg.applicationInfo.uid;
7672        res.removedInfo.removedPackage = packageName;
7673        // Remove existing system package
7674        removePackageLI(oldPkgSetting, true);
7675        // writer
7676        synchronized (mPackages) {
7677            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
7678                // We didn't need to disable the .apk as a current system package,
7679                // which means we are replacing another update that is already
7680                // installed.  We need to make sure to delete the older one's .apk.
7681                res.removedInfo.args = createInstallArgs(0,
7682                        deletedPackage.applicationInfo.sourceDir,
7683                        deletedPackage.applicationInfo.publicSourceDir,
7684                        deletedPackage.applicationInfo.nativeLibraryDir);
7685            } else {
7686                res.removedInfo.args = null;
7687            }
7688        }
7689
7690        // Successfully disabled the old package. Now proceed with re-installation
7691        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
7692        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7693        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
7694        if (newPackage == null) {
7695            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
7696            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
7697                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
7698            }
7699        } else {
7700            if (newPackage.mExtras != null) {
7701                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
7702                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
7703                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
7704            }
7705            updateSettingsLI(newPackage, installerPackageName, res);
7706            updatedSettings = true;
7707        }
7708
7709        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
7710            // Re installation failed. Restore old information
7711            // Remove new pkg information
7712            if (newPackage != null) {
7713                removeInstalledPackageLI(newPackage, true);
7714            }
7715            // Add back the old system package
7716            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
7717            // Restore the old system information in Settings
7718            synchronized(mPackages) {
7719                if (updatedSettings) {
7720                    mSettings.enableSystemPackageLPw(packageName);
7721                    mSettings.setInstallerPackageName(packageName,
7722                            oldPkgSetting.installerPackageName);
7723                }
7724                mSettings.writeLPr();
7725            }
7726        }
7727    }
7728
7729    // Utility method used to move dex files during install.
7730    private int moveDexFilesLI(PackageParser.Package newPackage) {
7731        int retCode;
7732        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
7733            retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
7734            if (retCode != 0) {
7735                if (mNoDexOpt) {
7736                    /*
7737                     * If we're in an engineering build, programs are lazily run
7738                     * through dexopt. If the .dex file doesn't exist yet, it
7739                     * will be created when the program is run next.
7740                     */
7741                    Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
7742                } else {
7743                    Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
7744                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7745                }
7746            }
7747        }
7748        return PackageManager.INSTALL_SUCCEEDED;
7749    }
7750
7751    private void updateSettingsLI(PackageParser.Package newPackage,
7752            String installerPackageName, PackageInstalledInfo res) {
7753        String pkgName = newPackage.packageName;
7754        synchronized (mPackages) {
7755            //write settings. the installStatus will be incomplete at this stage.
7756            //note that the new package setting would have already been
7757            //added to mPackages. It hasn't been persisted yet.
7758            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
7759            mSettings.writeLPr();
7760        }
7761
7762        if ((res.returnCode = moveDexFilesLI(newPackage))
7763                != PackageManager.INSTALL_SUCCEEDED) {
7764            // Discontinue if moving dex files failed.
7765            return;
7766        }
7767
7768        Log.d(TAG, "New package installed in " + newPackage.mPath);
7769
7770        synchronized (mPackages) {
7771            updatePermissionsLPw(newPackage.packageName, newPackage,
7772                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
7773                            ? UPDATE_PERMISSIONS_ALL : 0));
7774            res.name = pkgName;
7775            res.uid = newPackage.applicationInfo.uid;
7776            res.pkg = newPackage;
7777            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
7778            mSettings.setInstallerPackageName(pkgName, installerPackageName);
7779            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7780            //to update install status
7781            mSettings.writeLPr();
7782        }
7783    }
7784
7785    private void installPackageLI(InstallArgs args,
7786            boolean newInstall, PackageInstalledInfo res) {
7787        int pFlags = args.flags;
7788        String installerPackageName = args.installerPackageName;
7789        File tmpPackageFile = new File(args.getCodePath());
7790        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
7791        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
7792        boolean replace = false;
7793        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
7794                | (newInstall ? SCAN_NEW_INSTALL : 0);
7795        // Result object to be returned
7796        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
7797
7798        // Retrieve PackageSettings and parse package
7799        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
7800                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
7801                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
7802        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
7803        pp.setSeparateProcesses(mSeparateProcesses);
7804        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
7805                null, mMetrics, parseFlags);
7806        if (pkg == null) {
7807            res.returnCode = pp.getParseError();
7808            return;
7809        }
7810        String pkgName = res.name = pkg.packageName;
7811        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
7812            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
7813                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
7814                return;
7815            }
7816        }
7817        if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
7818            res.returnCode = pp.getParseError();
7819            return;
7820        }
7821
7822        /* If the installer passed in a manifest digest, compare it now. */
7823        if (args.manifestDigest != null) {
7824            if (DEBUG_INSTALL) {
7825                final String parsedManifest = pkg.manifestDigest == null ? "null"
7826                        : pkg.manifestDigest.toString();
7827                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
7828                        + parsedManifest);
7829            }
7830
7831            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
7832                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
7833                return;
7834            }
7835        } else if (DEBUG_INSTALL) {
7836            final String parsedManifest = pkg.manifestDigest == null
7837                    ? "null" : pkg.manifestDigest.toString();
7838            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
7839        }
7840
7841        // Get rid of all references to package scan path via parser.
7842        pp = null;
7843        String oldCodePath = null;
7844        boolean systemApp = false;
7845        synchronized (mPackages) {
7846            // Check if installing already existing package
7847            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
7848                String oldName = mSettings.mRenamedPackages.get(pkgName);
7849                if (pkg.mOriginalPackages != null
7850                        && pkg.mOriginalPackages.contains(oldName)
7851                        && mPackages.containsKey(oldName)) {
7852                    // This package is derived from an original package,
7853                    // and this device has been updating from that original
7854                    // name.  We must continue using the original name, so
7855                    // rename the new package here.
7856                    pkg.setPackageName(oldName);
7857                    pkgName = pkg.packageName;
7858                    replace = true;
7859                } else if (mPackages.containsKey(pkgName)) {
7860                    // This package, under its official name, already exists
7861                    // on the device; we should replace it.
7862                    replace = true;
7863                }
7864            }
7865            PackageSetting ps = mSettings.mPackages.get(pkgName);
7866            if (ps != null) {
7867                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
7868                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7869                    systemApp = (ps.pkg.applicationInfo.flags &
7870                            ApplicationInfo.FLAG_SYSTEM) != 0;
7871                }
7872                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7873            }
7874        }
7875
7876        if (systemApp && onSd) {
7877            // Disable updates to system apps on sdcard
7878            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
7879            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
7880            return;
7881        }
7882
7883        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
7884            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
7885            return;
7886        }
7887        // Set application objects path explicitly after the rename
7888        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
7889        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
7890        if (replace) {
7891            replacePackageLI(pkg, parseFlags, scanMode, args.user,
7892                    installerPackageName, res);
7893        } else {
7894            installNewPackageLI(pkg, parseFlags, scanMode, args.user,
7895                    installerPackageName, res);
7896        }
7897        synchronized (mPackages) {
7898            final PackageSetting ps = mSettings.mPackages.get(pkgName);
7899            if (ps != null) {
7900                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7901            }
7902        }
7903    }
7904
7905    private static boolean isForwardLocked(PackageParser.Package pkg) {
7906        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7907    }
7908
7909
7910    private boolean isForwardLocked(PackageSetting ps) {
7911        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
7912    }
7913
7914    private static boolean isExternal(PackageParser.Package pkg) {
7915        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7916    }
7917
7918    private static boolean isExternal(PackageSetting ps) {
7919        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
7920    }
7921
7922    private static boolean isSystemApp(PackageParser.Package pkg) {
7923        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7924    }
7925
7926    private static boolean isSystemApp(ApplicationInfo info) {
7927        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7928    }
7929
7930    private static boolean isSystemApp(PackageSetting ps) {
7931        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
7932    }
7933
7934    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
7935        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
7936    }
7937
7938    private int packageFlagsToInstallFlags(PackageSetting ps) {
7939        int installFlags = 0;
7940        if (isExternal(ps)) {
7941            installFlags |= PackageManager.INSTALL_EXTERNAL;
7942        }
7943        if (isForwardLocked(ps)) {
7944            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
7945        }
7946        return installFlags;
7947    }
7948
7949    private void deleteTempPackageFiles() {
7950        final FilenameFilter filter = new FilenameFilter() {
7951            public boolean accept(File dir, String name) {
7952                return name.startsWith("vmdl") && name.endsWith(".tmp");
7953            }
7954        };
7955        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
7956        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
7957    }
7958
7959    private static final void deleteTempPackageFilesInDirectory(File directory,
7960            FilenameFilter filter) {
7961        final String[] tmpFilesList = directory.list(filter);
7962        if (tmpFilesList == null) {
7963            return;
7964        }
7965        for (int i = 0; i < tmpFilesList.length; i++) {
7966            final File tmpFile = new File(directory, tmpFilesList[i]);
7967            tmpFile.delete();
7968        }
7969    }
7970
7971    private File createTempPackageFile(File installDir) {
7972        File tmpPackageFile;
7973        try {
7974            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
7975        } catch (IOException e) {
7976            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
7977            return null;
7978        }
7979        try {
7980            FileUtils.setPermissions(
7981                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
7982                    -1, -1);
7983            if (!SELinux.restorecon(tmpPackageFile)) {
7984                return null;
7985            }
7986        } catch (IOException e) {
7987            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
7988            return null;
7989        }
7990        return tmpPackageFile;
7991    }
7992
7993    public void deletePackage(final String packageName,
7994                              final IPackageDeleteObserver observer,
7995                              final int flags) {
7996        mContext.enforceCallingOrSelfPermission(
7997                android.Manifest.permission.DELETE_PACKAGES, null);
7998        // Queue up an async operation since the package deletion may take a little while.
7999        final int uid = Binder.getCallingUid();
8000        mHandler.post(new Runnable() {
8001            public void run() {
8002                mHandler.removeCallbacks(this);
8003                final int returnCode = deletePackageX(packageName, uid, flags);
8004                if (observer != null) {
8005                    try {
8006                        observer.packageDeleted(packageName, returnCode);
8007                    } catch (RemoteException e) {
8008                        Log.i(TAG, "Observer no longer exists.");
8009                    } //end catch
8010                } //end if
8011            } //end run
8012        });
8013    }
8014
8015    /**
8016     *  This method is an internal method that could be get invoked either
8017     *  to delete an installed package or to clean up a failed installation.
8018     *  After deleting an installed package, a broadcast is sent to notify any
8019     *  listeners that the package has been installed. For cleaning up a failed
8020     *  installation, the broadcast is not necessary since the package's
8021     *  installation wouldn't have sent the initial broadcast either
8022     *  The key steps in deleting a package are
8023     *  deleting the package information in internal structures like mPackages,
8024     *  deleting the packages base directories through installd
8025     *  updating mSettings to reflect current status
8026     *  persisting settings for later use
8027     *  sending a broadcast if necessary
8028     */
8029    private int deletePackageX(String packageName, int uid, int flags) {
8030        final PackageRemovedInfo info = new PackageRemovedInfo();
8031        final boolean res;
8032
8033        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
8034                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
8035        try {
8036            if (dpm != null && dpm.packageHasActiveAdmins(packageName, UserHandle.getUserId(uid))) {
8037                Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
8038                return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
8039            }
8040        } catch (RemoteException e) {
8041        }
8042
8043        boolean removedForAllUsers = false;
8044        boolean systemUpdate = false;
8045        synchronized (mInstallLock) {
8046            res = deletePackageLI(packageName,
8047                    (flags & PackageManager.DELETE_ALL_USERS) != 0
8048                            ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)),
8049                    true, flags | REMOVE_CHATTY, info, true);
8050            systemUpdate = info.isRemovedPackageSystemUpdate;
8051            if (res && !systemUpdate && mPackages.get(packageName) == null) {
8052                removedForAllUsers = true;
8053            }
8054        }
8055
8056        if (res) {
8057            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
8058
8059            // If the removed package was a system update, the old system package
8060            // was re-enabled; we need to broadcast this information
8061            if (systemUpdate) {
8062                Bundle extras = new Bundle(1);
8063                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
8064                        ? info.removedAppId : info.uid);
8065                extras.putBoolean(Intent.EXTRA_REPLACING, true);
8066
8067                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
8068                        extras, null, null, null);
8069                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
8070                        extras, null, null, null);
8071                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
8072                        null, packageName, null, null);
8073            }
8074        }
8075        // Force a gc here.
8076        Runtime.getRuntime().gc();
8077        // Delete the resources here after sending the broadcast to let
8078        // other processes clean up before deleting resources.
8079        if (info.args != null) {
8080            synchronized (mInstallLock) {
8081                info.args.doPostDeleteLI(true);
8082            }
8083        }
8084
8085        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
8086    }
8087
8088    static class PackageRemovedInfo {
8089        String removedPackage;
8090        int uid = -1;
8091        int removedAppId = -1;
8092        int[] removedUsers = null;
8093        boolean isRemovedPackageSystemUpdate = false;
8094        // Clean up resources deleted packages.
8095        InstallArgs args = null;
8096
8097        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
8098            Bundle extras = new Bundle(1);
8099            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
8100            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
8101            if (replacing) {
8102                extras.putBoolean(Intent.EXTRA_REPLACING, true);
8103            }
8104            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
8105            if (removedPackage != null) {
8106                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
8107                        extras, null, null, removedUsers);
8108                if (fullRemove && !replacing) {
8109                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
8110                            extras, null, null, removedUsers);
8111                }
8112            }
8113            if (removedAppId >= 0) {
8114                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
8115                        removedUsers);
8116            }
8117        }
8118    }
8119
8120    /*
8121     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
8122     * flag is not set, the data directory is removed as well.
8123     * make sure this flag is set for partially installed apps. If not its meaningless to
8124     * delete a partially installed application.
8125     */
8126    private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo,
8127            int flags, boolean writeSettings) {
8128        String packageName = ps.name;
8129        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
8130        // Retrieve object to delete permissions for shared user later on
8131        final PackageSetting deletedPs;
8132        // reader
8133        synchronized (mPackages) {
8134            deletedPs = mSettings.mPackages.get(packageName);
8135            if (outInfo != null) {
8136                outInfo.removedPackage = packageName;
8137                outInfo.removedUsers = deletedPs != null
8138                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
8139                        : null;
8140            }
8141        }
8142        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8143            removeDataDirsLI(packageName);
8144            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
8145        }
8146        // writer
8147        synchronized (mPackages) {
8148            if (deletedPs != null) {
8149                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
8150                    if (outInfo != null) {
8151                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
8152                    }
8153                    if (deletedPs != null) {
8154                        updatePermissionsLPw(deletedPs.name, null, 0);
8155                        if (deletedPs.sharedUser != null) {
8156                            // remove permissions associated with package
8157                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
8158                        }
8159                    }
8160                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
8161                }
8162            }
8163            // can downgrade to reader
8164            if (writeSettings) {
8165                // Save settings now
8166                mSettings.writeLPr();
8167            }
8168        }
8169    }
8170
8171    /*
8172     * Tries to delete system package.
8173     */
8174    private boolean deleteSystemPackageLI(PackageSetting newPs,
8175            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
8176        PackageSetting disabledPs = null;
8177        // Confirm if the system package has been updated
8178        // An updated system app can be deleted. This will also have to restore
8179        // the system pkg from system partition
8180        // reader
8181        synchronized (mPackages) {
8182            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
8183        }
8184        if (disabledPs == null) {
8185            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
8186            return false;
8187        } else {
8188            Log.i(TAG, "Deleting system pkg from data partition");
8189        }
8190        // Delete the updated package
8191        outInfo.isRemovedPackageSystemUpdate = true;
8192        if (disabledPs.versionCode < newPs.versionCode) {
8193            // Delete data for downgrades
8194            flags &= ~PackageManager.DELETE_KEEP_DATA;
8195        } else {
8196            // Preserve data by setting flag
8197            flags |= PackageManager.DELETE_KEEP_DATA;
8198        }
8199        boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo,
8200                writeSettings);
8201        if (!ret) {
8202            return false;
8203        }
8204        // writer
8205        synchronized (mPackages) {
8206            // Reinstate the old system package
8207            mSettings.enableSystemPackageLPw(newPs.name);
8208            // Remove any native libraries from the upgraded package.
8209            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
8210        }
8211        // Install the system package
8212        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
8213                PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
8214                SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
8215
8216        if (newPkg == null) {
8217            Slog.w(TAG, "Failed to restore system package:" + newPs.name
8218                    + " with error:" + mLastScanError);
8219            return false;
8220        }
8221        // writer
8222        synchronized (mPackages) {
8223            updatePermissionsLPw(newPkg.packageName, newPkg,
8224                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
8225            // can downgrade to reader here
8226            if (writeSettings) {
8227                mSettings.writeLPr();
8228            }
8229        }
8230        return true;
8231    }
8232
8233    private boolean deleteInstalledPackageLI(PackageSetting ps,
8234            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8235            boolean writeSettings) {
8236        if (outInfo != null) {
8237            outInfo.uid = ps.appId;
8238        }
8239
8240        // Delete package data from internal structures and also remove data if flag is set
8241        removePackageDataLI(ps, outInfo, flags, writeSettings);
8242
8243        // Delete application code and resources
8244        if (deleteCodeAndResources) {
8245            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
8246                    ps.resourcePathString, ps.nativeLibraryPathString);
8247        }
8248        return true;
8249    }
8250
8251    /*
8252     * This method handles package deletion in general
8253     */
8254    private boolean deletePackageLI(String packageName, UserHandle user,
8255            boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
8256            boolean writeSettings) {
8257        if (packageName == null) {
8258            Slog.w(TAG, "Attempt to delete null packageName.");
8259            return false;
8260        }
8261        PackageSetting ps;
8262        boolean dataOnly = false;
8263        int removeUser = -1;
8264        int appId = -1;
8265        synchronized (mPackages) {
8266            ps = mSettings.mPackages.get(packageName);
8267            if (ps == null) {
8268                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
8269                return false;
8270            }
8271            if (!isSystemApp(ps) && user != null
8272                    && user.getIdentifier() != UserHandle.USER_ALL) {
8273                // The caller is asking that the package only be deleted for a single
8274                // user.  To do this, we just mark its uninstalled state and delete
8275                // its data.
8276                ps.setUserState(user.getIdentifier(),
8277                        COMPONENT_ENABLED_STATE_DEFAULT,
8278                        false, //installed
8279                        true,  //stopped
8280                        true,  //notLaunched
8281                        null, null);
8282                if (ps.isAnyInstalled(sUserManager.getUserIds())) {
8283                    // Other user still have this package installed, so all
8284                    // we need to do is clear this user's data and save that
8285                    // it is uninstalled.
8286                    removeUser = user.getIdentifier();
8287                    appId = ps.appId;
8288                    mSettings.writePackageRestrictionsLPr(removeUser);
8289                } else {
8290                    // We need to set it back to 'installed' so the uninstall
8291                    // broadcasts will be sent correctly.
8292                    ps.setInstalled(true, user.getIdentifier());
8293                }
8294            }
8295        }
8296
8297        if (removeUser >= 0) {
8298            // From above, we determined that we are deleting this only
8299            // for a single user.  Continue the work here.
8300            if (outInfo != null) {
8301                outInfo.removedPackage = packageName;
8302                outInfo.removedAppId = appId;
8303                outInfo.removedUsers = new int[] {removeUser};
8304            }
8305            mInstaller.clearUserData(packageName, removeUser);
8306            schedulePackageCleaning(packageName, removeUser, false);
8307            return true;
8308        }
8309
8310        if (dataOnly) {
8311            // Delete application data first
8312            removePackageDataLI(ps, outInfo, flags, writeSettings);
8313            return true;
8314        }
8315        boolean ret = false;
8316        if (isSystemApp(ps)) {
8317            Log.i(TAG, "Removing system package:" + ps.name);
8318            // When an updated system application is deleted we delete the existing resources as well and
8319            // fall back to existing code in system partition
8320            ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings);
8321        } else {
8322            Log.i(TAG, "Removing non-system package:" + ps.name);
8323            // Kill application pre-emptively especially for apps on sd.
8324            killApplication(packageName, ps.appId);
8325            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo,
8326                    writeSettings);
8327        }
8328        return ret;
8329    }
8330
8331    private final class ClearStorageConnection implements ServiceConnection {
8332        IMediaContainerService mContainerService;
8333
8334        @Override
8335        public void onServiceConnected(ComponentName name, IBinder service) {
8336            synchronized (this) {
8337                mContainerService = IMediaContainerService.Stub.asInterface(service);
8338                notifyAll();
8339            }
8340        }
8341
8342        @Override
8343        public void onServiceDisconnected(ComponentName name) {
8344        }
8345    }
8346
8347    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
8348        final boolean mounted;
8349        if (Environment.isExternalStorageEmulated()) {
8350            mounted = true;
8351        } else {
8352            final String status = Environment.getExternalStorageState();
8353
8354            mounted = status.equals(Environment.MEDIA_MOUNTED)
8355                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
8356        }
8357
8358        if (!mounted) {
8359            return;
8360        }
8361
8362        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
8363        int[] users;
8364        if (userId == UserHandle.USER_ALL) {
8365            users = sUserManager.getUserIds();
8366        } else {
8367            users = new int[] { userId };
8368        }
8369        final ClearStorageConnection conn = new ClearStorageConnection();
8370        if (mContext.bindService(
8371                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_OWNER)) {
8372            try {
8373                for (int curUser : users) {
8374                    long timeout = SystemClock.uptimeMillis() + 5000;
8375                    synchronized (conn) {
8376                        long now = SystemClock.uptimeMillis();
8377                        while (conn.mContainerService == null && now < timeout) {
8378                            try {
8379                                conn.wait(timeout - now);
8380                            } catch (InterruptedException e) {
8381                            }
8382                        }
8383                    }
8384                    if (conn.mContainerService == null) {
8385                        return;
8386                    }
8387
8388                    final UserEnvironment userEnv = new UserEnvironment(curUser);
8389                    final File externalCacheDir = userEnv
8390                            .getExternalStorageAppCacheDirectory(packageName);
8391                    try {
8392                        conn.mContainerService.clearDirectory(externalCacheDir.toString());
8393                    } catch (RemoteException e) {
8394                    }
8395                    if (allData) {
8396                        final File externalDataDir = userEnv
8397                                .getExternalStorageAppDataDirectory(packageName);
8398                        try {
8399                            conn.mContainerService.clearDirectory(externalDataDir.toString());
8400                        } catch (RemoteException e) {
8401                        }
8402                        final File externalMediaDir = userEnv
8403                                .getExternalStorageAppMediaDirectory(packageName);
8404                        try {
8405                            conn.mContainerService.clearDirectory(externalMediaDir.toString());
8406                        } catch (RemoteException e) {
8407                        }
8408                    }
8409                }
8410            } finally {
8411                mContext.unbindService(conn);
8412            }
8413        }
8414    }
8415
8416    @Override
8417    public void clearApplicationUserData(final String packageName,
8418            final IPackageDataObserver observer, final int userId) {
8419        mContext.enforceCallingOrSelfPermission(
8420                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
8421        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
8422        // Queue up an async operation since the package deletion may take a little while.
8423        mHandler.post(new Runnable() {
8424            public void run() {
8425                mHandler.removeCallbacks(this);
8426                final boolean succeeded;
8427                synchronized (mInstallLock) {
8428                    succeeded = clearApplicationUserDataLI(packageName, userId);
8429                }
8430                clearExternalStorageDataSync(packageName, userId, true);
8431                if (succeeded) {
8432                    // invoke DeviceStorageMonitor's update method to clear any notifications
8433                    DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
8434                            ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
8435                    if (dsm != null) {
8436                        dsm.updateMemory();
8437                    }
8438                }
8439                if(observer != null) {
8440                    try {
8441                        observer.onRemoveCompleted(packageName, succeeded);
8442                    } catch (RemoteException e) {
8443                        Log.i(TAG, "Observer no longer exists.");
8444                    }
8445                } //end if observer
8446            } //end run
8447        });
8448    }
8449
8450    private boolean clearApplicationUserDataLI(String packageName, int userId) {
8451        if (packageName == null) {
8452            Slog.w(TAG, "Attempt to delete null packageName.");
8453            return false;
8454        }
8455        PackageParser.Package p;
8456        boolean dataOnly = false;
8457        synchronized (mPackages) {
8458            p = mPackages.get(packageName);
8459            if(p == null) {
8460                dataOnly = true;
8461                PackageSetting ps = mSettings.mPackages.get(packageName);
8462                if((ps == null) || (ps.pkg == null)) {
8463                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8464                    return false;
8465                }
8466                p = ps.pkg;
8467            }
8468        }
8469
8470        if (!dataOnly) {
8471            //need to check this only for fully installed applications
8472            if (p == null) {
8473                Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8474                return false;
8475            }
8476            final ApplicationInfo applicationInfo = p.applicationInfo;
8477            if (applicationInfo == null) {
8478                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8479                return false;
8480            }
8481        }
8482        int retCode = mInstaller.clearUserData(packageName, userId);
8483        if (retCode < 0) {
8484            Slog.w(TAG, "Couldn't remove cache files for package: "
8485                    + packageName);
8486            return false;
8487        }
8488        return true;
8489    }
8490
8491    public void deleteApplicationCacheFiles(final String packageName,
8492            final IPackageDataObserver observer) {
8493        mContext.enforceCallingOrSelfPermission(
8494                android.Manifest.permission.DELETE_CACHE_FILES, null);
8495        // Queue up an async operation since the package deletion may take a little while.
8496        final int userId = UserHandle.getCallingUserId();
8497        mHandler.post(new Runnable() {
8498            public void run() {
8499                mHandler.removeCallbacks(this);
8500                final boolean succeded;
8501                synchronized (mInstallLock) {
8502                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
8503                }
8504                clearExternalStorageDataSync(packageName, userId, false);
8505                if(observer != null) {
8506                    try {
8507                        observer.onRemoveCompleted(packageName, succeded);
8508                    } catch (RemoteException e) {
8509                        Log.i(TAG, "Observer no longer exists.");
8510                    }
8511                } //end if observer
8512            } //end run
8513        });
8514    }
8515
8516    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
8517        if (packageName == null) {
8518            Slog.w(TAG, "Attempt to delete null packageName.");
8519            return false;
8520        }
8521        PackageParser.Package p;
8522        synchronized (mPackages) {
8523            p = mPackages.get(packageName);
8524        }
8525        if (p == null) {
8526            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8527            return false;
8528        }
8529        final ApplicationInfo applicationInfo = p.applicationInfo;
8530        if (applicationInfo == null) {
8531            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8532            return false;
8533        }
8534        // TODO: Pass userId to deleteCacheFiles
8535        int retCode = mInstaller.deleteCacheFiles(packageName);
8536        if (retCode < 0) {
8537            Slog.w(TAG, "Couldn't remove cache files for package: "
8538                       + packageName);
8539            return false;
8540        }
8541        return true;
8542    }
8543
8544    public void getPackageSizeInfo(final String packageName, int userHandle,
8545            final IPackageStatsObserver observer) {
8546        mContext.enforceCallingOrSelfPermission(
8547                android.Manifest.permission.GET_PACKAGE_SIZE, null);
8548
8549        PackageStats stats = new PackageStats(packageName, userHandle);
8550
8551        /*
8552         * Queue up an async operation since the package measurement may take a
8553         * little while.
8554         */
8555        Message msg = mHandler.obtainMessage(INIT_COPY);
8556        msg.obj = new MeasureParams(stats, observer);
8557        mHandler.sendMessage(msg);
8558    }
8559
8560    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
8561            PackageStats pStats) {
8562        if (packageName == null) {
8563            Slog.w(TAG, "Attempt to get size of null packageName.");
8564            return false;
8565        }
8566        PackageParser.Package p;
8567        boolean dataOnly = false;
8568        String asecPath = null;
8569        synchronized (mPackages) {
8570            p = mPackages.get(packageName);
8571            if(p == null) {
8572                dataOnly = true;
8573                PackageSetting ps = mSettings.mPackages.get(packageName);
8574                if((ps == null) || (ps.pkg == null)) {
8575                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
8576                    return false;
8577                }
8578                p = ps.pkg;
8579            }
8580            if (p != null && (isExternal(p) || isForwardLocked(p))) {
8581                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
8582                if (secureContainerId != null) {
8583                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
8584                }
8585            }
8586        }
8587        String publicSrcDir = null;
8588        if(!dataOnly) {
8589            final ApplicationInfo applicationInfo = p.applicationInfo;
8590            if (applicationInfo == null) {
8591                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
8592                return false;
8593            }
8594            if (isForwardLocked(p)) {
8595                publicSrcDir = applicationInfo.publicSourceDir;
8596            }
8597        }
8598        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir,
8599                asecPath, pStats);
8600        if (res < 0) {
8601            return false;
8602        }
8603
8604        // Fix-up for forward-locked applications in ASEC containers.
8605        if (!isExternal(p)) {
8606            pStats.codeSize += pStats.externalCodeSize;
8607            pStats.externalCodeSize = 0L;
8608        }
8609
8610        return true;
8611    }
8612
8613
8614    public void addPackageToPreferred(String packageName) {
8615        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
8616    }
8617
8618    public void removePackageFromPreferred(String packageName) {
8619        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
8620    }
8621
8622    public List<PackageInfo> getPreferredPackages(int flags) {
8623        return new ArrayList<PackageInfo>();
8624    }
8625
8626    private int getUidTargetSdkVersionLockedLPr(int uid) {
8627        Object obj = mSettings.getUserIdLPr(uid);
8628        if (obj instanceof SharedUserSetting) {
8629            final SharedUserSetting sus = (SharedUserSetting) obj;
8630            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
8631            final Iterator<PackageSetting> it = sus.packages.iterator();
8632            while (it.hasNext()) {
8633                final PackageSetting ps = it.next();
8634                if (ps.pkg != null) {
8635                    int v = ps.pkg.applicationInfo.targetSdkVersion;
8636                    if (v < vers) vers = v;
8637                }
8638            }
8639            return vers;
8640        } else if (obj instanceof PackageSetting) {
8641            final PackageSetting ps = (PackageSetting) obj;
8642            if (ps.pkg != null) {
8643                return ps.pkg.applicationInfo.targetSdkVersion;
8644            }
8645        }
8646        return Build.VERSION_CODES.CUR_DEVELOPMENT;
8647    }
8648
8649    public void addPreferredActivity(IntentFilter filter, int match,
8650            ComponentName[] set, ComponentName activity, int userId) {
8651        // writer
8652        int callingUid = Binder.getCallingUid();
8653        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
8654        synchronized (mPackages) {
8655            if (mContext.checkCallingOrSelfPermission(
8656                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8657                    != PackageManager.PERMISSION_GRANTED) {
8658                if (getUidTargetSdkVersionLockedLPr(callingUid)
8659                        < Build.VERSION_CODES.FROYO) {
8660                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
8661                            + callingUid);
8662                    return;
8663                }
8664                mContext.enforceCallingOrSelfPermission(
8665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8666            }
8667
8668            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
8669            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8670            mSettings.mPreferredActivities.addFilter(
8671                    new PreferredActivity(filter, match, set, activity, userId));
8672            scheduleWriteSettingsLocked();
8673        }
8674    }
8675
8676    public void replacePreferredActivity(IntentFilter filter, int match,
8677            ComponentName[] set, ComponentName activity) {
8678        if (filter.countActions() != 1) {
8679            throw new IllegalArgumentException(
8680                    "replacePreferredActivity expects filter to have only 1 action.");
8681        }
8682        if (filter.countCategories() != 1) {
8683            throw new IllegalArgumentException(
8684                    "replacePreferredActivity expects filter to have only 1 category.");
8685        }
8686        if (filter.countDataAuthorities() != 0
8687                || filter.countDataPaths() != 0
8688                || filter.countDataSchemes() != 0
8689                || filter.countDataTypes() != 0) {
8690            throw new IllegalArgumentException(
8691                    "replacePreferredActivity expects filter to have no data authorities, " +
8692                    "paths, schemes or types.");
8693        }
8694        synchronized (mPackages) {
8695            if (mContext.checkCallingOrSelfPermission(
8696                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8697                    != PackageManager.PERMISSION_GRANTED) {
8698                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8699                        < Build.VERSION_CODES.FROYO) {
8700                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
8701                            + Binder.getCallingUid());
8702                    return;
8703                }
8704                mContext.enforceCallingOrSelfPermission(
8705                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8706            }
8707
8708            final int callingUserId = UserHandle.getCallingUserId();
8709            ArrayList<PreferredActivity> removed = null;
8710            Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8711            String action = filter.getAction(0);
8712            String category = filter.getCategory(0);
8713            while (it.hasNext()) {
8714                PreferredActivity pa = it.next();
8715                if (pa.mUserId != callingUserId) continue;
8716                if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
8717                    if (removed == null) {
8718                        removed = new ArrayList<PreferredActivity>();
8719                    }
8720                    removed.add(pa);
8721                    Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
8722                    filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
8723                }
8724            }
8725            if (removed != null) {
8726                for (int i=0; i<removed.size(); i++) {
8727                    PreferredActivity pa = removed.get(i);
8728                    mSettings.mPreferredActivities.removeFilter(pa);
8729                }
8730            }
8731            addPreferredActivity(filter, match, set, activity, callingUserId);
8732        }
8733    }
8734
8735    public void clearPackagePreferredActivities(String packageName) {
8736        final int uid = Binder.getCallingUid();
8737        // writer
8738        synchronized (mPackages) {
8739            PackageParser.Package pkg = mPackages.get(packageName);
8740            if (pkg == null || pkg.applicationInfo.uid != uid) {
8741                if (mContext.checkCallingOrSelfPermission(
8742                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
8743                        != PackageManager.PERMISSION_GRANTED) {
8744                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
8745                            < Build.VERSION_CODES.FROYO) {
8746                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
8747                                + Binder.getCallingUid());
8748                        return;
8749                    }
8750                    mContext.enforceCallingOrSelfPermission(
8751                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
8752                }
8753            }
8754
8755            if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) {
8756                scheduleWriteSettingsLocked();
8757            }
8758        }
8759    }
8760
8761    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
8762    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
8763        ArrayList<PreferredActivity> removed = null;
8764        Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8765        while (it.hasNext()) {
8766            PreferredActivity pa = it.next();
8767            if (userId != UserHandle.USER_ALL && pa.mUserId != userId) {
8768                continue;
8769            }
8770            if (pa.mPref.mComponent.getPackageName().equals(packageName)) {
8771                if (removed == null) {
8772                    removed = new ArrayList<PreferredActivity>();
8773                }
8774                removed.add(pa);
8775            }
8776        }
8777        if (removed != null) {
8778            for (int i=0; i<removed.size(); i++) {
8779                PreferredActivity pa = removed.get(i);
8780                mSettings.mPreferredActivities.removeFilter(pa);
8781            }
8782            return true;
8783        }
8784        return false;
8785    }
8786
8787    public int getPreferredActivities(List<IntentFilter> outFilters,
8788            List<ComponentName> outActivities, String packageName) {
8789
8790        int num = 0;
8791        final int userId = UserHandle.getCallingUserId();
8792        // reader
8793        synchronized (mPackages) {
8794            final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
8795            while (it.hasNext()) {
8796                final PreferredActivity pa = it.next();
8797                if (pa.mUserId != userId) {
8798                    continue;
8799                }
8800                if (packageName == null
8801                        || pa.mPref.mComponent.getPackageName().equals(packageName)) {
8802                    if (outFilters != null) {
8803                        outFilters.add(new IntentFilter(pa));
8804                    }
8805                    if (outActivities != null) {
8806                        outActivities.add(pa.mPref.mComponent);
8807                    }
8808                }
8809            }
8810        }
8811
8812        return num;
8813    }
8814
8815    @Override
8816    public void setApplicationEnabledSetting(String appPackageName,
8817            int newState, int flags, int userId) {
8818        if (!sUserManager.exists(userId)) return;
8819        setEnabledSetting(appPackageName, null, newState, flags, userId);
8820    }
8821
8822    @Override
8823    public void setComponentEnabledSetting(ComponentName componentName,
8824            int newState, int flags, int userId) {
8825        if (!sUserManager.exists(userId)) return;
8826        setEnabledSetting(componentName.getPackageName(),
8827                componentName.getClassName(), newState, flags, userId);
8828    }
8829
8830    private void setEnabledSetting(
8831            final String packageName, String className, int newState, final int flags, int userId) {
8832        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
8833              || newState == COMPONENT_ENABLED_STATE_ENABLED
8834              || newState == COMPONENT_ENABLED_STATE_DISABLED
8835              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) {
8836            throw new IllegalArgumentException("Invalid new component state: "
8837                    + newState);
8838        }
8839        PackageSetting pkgSetting;
8840        final int uid = Binder.getCallingUid();
8841        final int permission = mContext.checkCallingPermission(
8842                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8843        enforceCrossUserPermission(uid, userId, false, "set enabled");
8844        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8845        boolean sendNow = false;
8846        boolean isApp = (className == null);
8847        String componentName = isApp ? packageName : className;
8848        int packageUid = -1;
8849        ArrayList<String> components;
8850
8851        // writer
8852        synchronized (mPackages) {
8853            pkgSetting = mSettings.mPackages.get(packageName);
8854            if (pkgSetting == null) {
8855                if (className == null) {
8856                    throw new IllegalArgumentException(
8857                            "Unknown package: " + packageName);
8858                }
8859                throw new IllegalArgumentException(
8860                        "Unknown component: " + packageName
8861                        + "/" + className);
8862            }
8863            // Allow root and verify that userId is not being specified by a different user
8864            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
8865                throw new SecurityException(
8866                        "Permission Denial: attempt to change component state from pid="
8867                        + Binder.getCallingPid()
8868                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
8869            }
8870            if (className == null) {
8871                // We're dealing with an application/package level state change
8872                if (pkgSetting.getEnabled(userId) == newState) {
8873                    // Nothing to do
8874                    return;
8875                }
8876                pkgSetting.setEnabled(newState, userId);
8877                // pkgSetting.pkg.mSetEnabled = newState;
8878            } else {
8879                // We're dealing with a component level state change
8880                // First, verify that this is a valid class name.
8881                PackageParser.Package pkg = pkgSetting.pkg;
8882                if (pkg == null || !pkg.hasComponentClassName(className)) {
8883                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
8884                        throw new IllegalArgumentException("Component class " + className
8885                                + " does not exist in " + packageName);
8886                    } else {
8887                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
8888                                + className + " does not exist in " + packageName);
8889                    }
8890                }
8891                switch (newState) {
8892                case COMPONENT_ENABLED_STATE_ENABLED:
8893                    if (!pkgSetting.enableComponentLPw(className, userId)) {
8894                        return;
8895                    }
8896                    break;
8897                case COMPONENT_ENABLED_STATE_DISABLED:
8898                    if (!pkgSetting.disableComponentLPw(className, userId)) {
8899                        return;
8900                    }
8901                    break;
8902                case COMPONENT_ENABLED_STATE_DEFAULT:
8903                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
8904                        return;
8905                    }
8906                    break;
8907                default:
8908                    Slog.e(TAG, "Invalid new component state: " + newState);
8909                    return;
8910                }
8911            }
8912            mSettings.writePackageRestrictionsLPr(userId);
8913            packageUid = UserHandle.getUid(userId, pkgSetting.appId);
8914            components = mPendingBroadcasts.get(packageName);
8915            final boolean newPackage = components == null;
8916            if (newPackage) {
8917                components = new ArrayList<String>();
8918            }
8919            if (!components.contains(componentName)) {
8920                components.add(componentName);
8921            }
8922            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
8923                sendNow = true;
8924                // Purge entry from pending broadcast list if another one exists already
8925                // since we are sending one right away.
8926                mPendingBroadcasts.remove(packageName);
8927            } else {
8928                if (newPackage) {
8929                    mPendingBroadcasts.put(packageName, components);
8930                }
8931                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
8932                    // Schedule a message
8933                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
8934                }
8935            }
8936        }
8937
8938        long callingId = Binder.clearCallingIdentity();
8939        try {
8940            if (sendNow) {
8941                sendPackageChangedBroadcast(packageName,
8942                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
8943            }
8944        } finally {
8945            Binder.restoreCallingIdentity(callingId);
8946        }
8947    }
8948
8949    private void sendPackageChangedBroadcast(String packageName,
8950            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
8951        if (DEBUG_INSTALL)
8952            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
8953                    + componentNames);
8954        Bundle extras = new Bundle(4);
8955        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
8956        String nameList[] = new String[componentNames.size()];
8957        componentNames.toArray(nameList);
8958        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
8959        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
8960        extras.putInt(Intent.EXTRA_UID, packageUid);
8961        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
8962                new int[] {UserHandle.getUserId(packageUid)});
8963    }
8964
8965    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
8966        if (!sUserManager.exists(userId)) return;
8967        final int uid = Binder.getCallingUid();
8968        final int permission = mContext.checkCallingOrSelfPermission(
8969                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
8970        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
8971        enforceCrossUserPermission(uid, userId, true, "stop package");
8972        // writer
8973        synchronized (mPackages) {
8974            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
8975                    uid, userId)) {
8976                scheduleWritePackageRestrictionsLocked(userId);
8977            }
8978        }
8979    }
8980
8981    public String getInstallerPackageName(String packageName) {
8982        // reader
8983        synchronized (mPackages) {
8984            return mSettings.getInstallerPackageNameLPr(packageName);
8985        }
8986    }
8987
8988    @Override
8989    public int getApplicationEnabledSetting(String packageName, int userId) {
8990        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
8991        int uid = Binder.getCallingUid();
8992        enforceCrossUserPermission(uid, userId, false, "get enabled");
8993        // reader
8994        synchronized (mPackages) {
8995            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
8996        }
8997    }
8998
8999    @Override
9000    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
9001        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
9002        int uid = Binder.getCallingUid();
9003        enforceCrossUserPermission(uid, userId, false, "get component enabled");
9004        // reader
9005        synchronized (mPackages) {
9006            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
9007        }
9008    }
9009
9010    public void enterSafeMode() {
9011        enforceSystemOrRoot("Only the system can request entering safe mode");
9012
9013        if (!mSystemReady) {
9014            mSafeMode = true;
9015        }
9016    }
9017
9018    public void systemReady() {
9019        mSystemReady = true;
9020
9021        // Read the compatibilty setting when the system is ready.
9022        boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
9023                mContext.getContentResolver(),
9024                android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
9025        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
9026        if (DEBUG_SETTINGS) {
9027            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
9028        }
9029    }
9030
9031    public boolean isSafeMode() {
9032        return mSafeMode;
9033    }
9034
9035    public boolean hasSystemUidErrors() {
9036        return mHasSystemUidErrors;
9037    }
9038
9039    static String arrayToString(int[] array) {
9040        StringBuffer buf = new StringBuffer(128);
9041        buf.append('[');
9042        if (array != null) {
9043            for (int i=0; i<array.length; i++) {
9044                if (i > 0) buf.append(", ");
9045                buf.append(array[i]);
9046            }
9047        }
9048        buf.append(']');
9049        return buf.toString();
9050    }
9051
9052    static class DumpState {
9053        public static final int DUMP_LIBS = 1 << 0;
9054
9055        public static final int DUMP_FEATURES = 1 << 1;
9056
9057        public static final int DUMP_RESOLVERS = 1 << 2;
9058
9059        public static final int DUMP_PERMISSIONS = 1 << 3;
9060
9061        public static final int DUMP_PACKAGES = 1 << 4;
9062
9063        public static final int DUMP_SHARED_USERS = 1 << 5;
9064
9065        public static final int DUMP_MESSAGES = 1 << 6;
9066
9067        public static final int DUMP_PROVIDERS = 1 << 7;
9068
9069        public static final int DUMP_VERIFIERS = 1 << 8;
9070
9071        public static final int DUMP_PREFERRED = 1 << 9;
9072
9073        public static final int DUMP_PREFERRED_XML = 1 << 10;
9074
9075        public static final int OPTION_SHOW_FILTERS = 1 << 0;
9076
9077        private int mTypes;
9078
9079        private int mOptions;
9080
9081        private boolean mTitlePrinted;
9082
9083        private SharedUserSetting mSharedUser;
9084
9085        public boolean isDumping(int type) {
9086            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
9087                return true;
9088            }
9089
9090            return (mTypes & type) != 0;
9091        }
9092
9093        public void setDump(int type) {
9094            mTypes |= type;
9095        }
9096
9097        public boolean isOptionEnabled(int option) {
9098            return (mOptions & option) != 0;
9099        }
9100
9101        public void setOptionEnabled(int option) {
9102            mOptions |= option;
9103        }
9104
9105        public boolean onTitlePrinted() {
9106            final boolean printed = mTitlePrinted;
9107            mTitlePrinted = true;
9108            return printed;
9109        }
9110
9111        public boolean getTitlePrinted() {
9112            return mTitlePrinted;
9113        }
9114
9115        public void setTitlePrinted(boolean enabled) {
9116            mTitlePrinted = enabled;
9117        }
9118
9119        public SharedUserSetting getSharedUser() {
9120            return mSharedUser;
9121        }
9122
9123        public void setSharedUser(SharedUserSetting user) {
9124            mSharedUser = user;
9125        }
9126    }
9127
9128    @Override
9129    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9130        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
9131                != PackageManager.PERMISSION_GRANTED) {
9132            pw.println("Permission Denial: can't dump ActivityManager from from pid="
9133                    + Binder.getCallingPid()
9134                    + ", uid=" + Binder.getCallingUid()
9135                    + " without permission "
9136                    + android.Manifest.permission.DUMP);
9137            return;
9138        }
9139
9140        DumpState dumpState = new DumpState();
9141
9142        String packageName = null;
9143
9144        int opti = 0;
9145        while (opti < args.length) {
9146            String opt = args[opti];
9147            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9148                break;
9149            }
9150            opti++;
9151            if ("-a".equals(opt)) {
9152                // Right now we only know how to print all.
9153            } else if ("-h".equals(opt)) {
9154                pw.println("Package manager dump options:");
9155                pw.println("  [-h] [-f] [cmd] ...");
9156                pw.println("    -f: print details of intent filters");
9157                pw.println("    -h: print this help");
9158                pw.println("  cmd may be one of:");
9159                pw.println("    l[ibraries]: list known shared libraries");
9160                pw.println("    f[ibraries]: list device features");
9161                pw.println("    r[esolvers]: dump intent resolvers");
9162                pw.println("    perm[issions]: dump permissions");
9163                pw.println("    pref[erred]: print preferred package settings");
9164                pw.println("    preferred-xml: print preferred package settings as xml");
9165                pw.println("    prov[iders]: dump content providers");
9166                pw.println("    p[ackages]: dump installed packages");
9167                pw.println("    s[hared-users]: dump shared user IDs");
9168                pw.println("    m[essages]: print collected runtime messages");
9169                pw.println("    v[erifiers]: print package verifier info");
9170                pw.println("    <package.name>: info about given package");
9171                return;
9172            } else if ("-f".equals(opt)) {
9173                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
9174            } else {
9175                pw.println("Unknown argument: " + opt + "; use -h for help");
9176            }
9177        }
9178
9179        // Is the caller requesting to dump a particular piece of data?
9180        if (opti < args.length) {
9181            String cmd = args[opti];
9182            opti++;
9183            // Is this a package name?
9184            if ("android".equals(cmd) || cmd.contains(".")) {
9185                packageName = cmd;
9186            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
9187                dumpState.setDump(DumpState.DUMP_LIBS);
9188            } else if ("f".equals(cmd) || "features".equals(cmd)) {
9189                dumpState.setDump(DumpState.DUMP_FEATURES);
9190            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
9191                dumpState.setDump(DumpState.DUMP_RESOLVERS);
9192            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
9193                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
9194            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
9195                dumpState.setDump(DumpState.DUMP_PREFERRED);
9196            } else if ("preferred-xml".equals(cmd)) {
9197                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
9198            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
9199                dumpState.setDump(DumpState.DUMP_PACKAGES);
9200            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
9201                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
9202            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
9203                dumpState.setDump(DumpState.DUMP_PROVIDERS);
9204            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
9205                dumpState.setDump(DumpState.DUMP_MESSAGES);
9206            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
9207                dumpState.setDump(DumpState.DUMP_VERIFIERS);
9208            }
9209        }
9210
9211        // reader
9212        synchronized (mPackages) {
9213            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
9214                if (dumpState.onTitlePrinted())
9215                    pw.println(" ");
9216                pw.println("Verifiers:");
9217                pw.print("  Required: ");
9218                pw.print(mRequiredVerifierPackage);
9219                pw.print(" (uid=");
9220                pw.print(getPackageUid(mRequiredVerifierPackage, 0));
9221                pw.println(")");
9222            }
9223
9224            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
9225                if (dumpState.onTitlePrinted())
9226                    pw.println(" ");
9227                pw.println("Libraries:");
9228                final Iterator<String> it = mSharedLibraries.keySet().iterator();
9229                while (it.hasNext()) {
9230                    String name = it.next();
9231                    pw.print("  ");
9232                    pw.print(name);
9233                    pw.print(" -> ");
9234                    pw.println(mSharedLibraries.get(name));
9235                }
9236            }
9237
9238            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
9239                if (dumpState.onTitlePrinted())
9240                    pw.println(" ");
9241                pw.println("Features:");
9242                Iterator<String> it = mAvailableFeatures.keySet().iterator();
9243                while (it.hasNext()) {
9244                    String name = it.next();
9245                    pw.print("  ");
9246                    pw.println(name);
9247                }
9248            }
9249
9250            if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
9251                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
9252                        : "Activity Resolver Table:", "  ", packageName,
9253                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9254                    dumpState.setTitlePrinted(true);
9255                }
9256                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
9257                        : "Receiver Resolver Table:", "  ", packageName,
9258                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9259                    dumpState.setTitlePrinted(true);
9260                }
9261                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
9262                        : "Service Resolver Table:", "  ", packageName,
9263                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9264                    dumpState.setTitlePrinted(true);
9265                }
9266            }
9267
9268            if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
9269                if (mSettings.mPreferredActivities.dump(pw,
9270                        dumpState.getTitlePrinted() ? "\nPreferred Activities:"
9271                            : "Preferred Activities:", "  ",
9272                        packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
9273                    dumpState.setTitlePrinted(true);
9274                }
9275            }
9276
9277            if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
9278                pw.flush();
9279                FileOutputStream fout = new FileOutputStream(fd);
9280                BufferedOutputStream str = new BufferedOutputStream(fout);
9281                XmlSerializer serializer = new FastXmlSerializer();
9282                try {
9283                    serializer.setOutput(str, "utf-8");
9284                    serializer.startDocument(null, true);
9285                    serializer.setFeature(
9286                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
9287                    mSettings.writePreferredActivitiesLPr(serializer);
9288                    serializer.endDocument();
9289                    serializer.flush();
9290                } catch (IllegalArgumentException e) {
9291                    pw.println("Failed writing: " + e);
9292                } catch (IllegalStateException e) {
9293                    pw.println("Failed writing: " + e);
9294                } catch (IOException e) {
9295                    pw.println("Failed writing: " + e);
9296                }
9297            }
9298
9299            if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
9300                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
9301            }
9302
9303            if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
9304                boolean printedSomething = false;
9305                for (PackageParser.Provider p : mProvidersByComponent.values()) {
9306                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9307                        continue;
9308                    }
9309                    if (!printedSomething) {
9310                        if (dumpState.onTitlePrinted())
9311                            pw.println(" ");
9312                        pw.println("Registered ContentProviders:");
9313                        printedSomething = true;
9314                    }
9315                    pw.print("  "); pw.print(p.getComponentShortName()); pw.println(":");
9316                    pw.print("    "); pw.println(p.toString());
9317                }
9318                printedSomething = false;
9319                for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
9320                    PackageParser.Provider p = entry.getValue();
9321                    if (packageName != null && !packageName.equals(p.info.packageName)) {
9322                        continue;
9323                    }
9324                    if (!printedSomething) {
9325                        if (dumpState.onTitlePrinted())
9326                            pw.println(" ");
9327                        pw.println("ContentProvider Authorities:");
9328                        printedSomething = true;
9329                    }
9330                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
9331                    pw.print("    "); pw.println(p.toString());
9332                    if (p.info != null && p.info.applicationInfo != null) {
9333                        final String appInfo = p.info.applicationInfo.toString();
9334                        pw.print("      applicationInfo="); pw.println(appInfo);
9335                    }
9336                }
9337            }
9338
9339            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
9340                mSettings.dumpPackagesLPr(pw, packageName, dumpState);
9341            }
9342
9343            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
9344                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
9345            }
9346
9347            if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
9348                if (dumpState.onTitlePrinted())
9349                    pw.println(" ");
9350                mSettings.dumpReadMessagesLPr(pw, dumpState);
9351
9352                pw.println(" ");
9353                pw.println("Package warning messages:");
9354                final File fname = getSettingsProblemFile();
9355                FileInputStream in = null;
9356                try {
9357                    in = new FileInputStream(fname);
9358                    final int avail = in.available();
9359                    final byte[] data = new byte[avail];
9360                    in.read(data);
9361                    pw.print(new String(data));
9362                } catch (FileNotFoundException e) {
9363                } catch (IOException e) {
9364                } finally {
9365                    if (in != null) {
9366                        try {
9367                            in.close();
9368                        } catch (IOException e) {
9369                        }
9370                    }
9371                }
9372            }
9373        }
9374    }
9375
9376    // ------- apps on sdcard specific code -------
9377    static final boolean DEBUG_SD_INSTALL = false;
9378
9379    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9380
9381    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9382
9383    private boolean mMediaMounted = false;
9384
9385    private String getEncryptKey() {
9386        try {
9387            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9388                    SD_ENCRYPTION_KEYSTORE_NAME);
9389            if (sdEncKey == null) {
9390                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9391                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
9392                if (sdEncKey == null) {
9393                    Slog.e(TAG, "Failed to create encryption keys");
9394                    return null;
9395                }
9396            }
9397            return sdEncKey;
9398        } catch (NoSuchAlgorithmException nsae) {
9399            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
9400            return null;
9401        } catch (IOException ioe) {
9402            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
9403            return null;
9404        }
9405
9406    }
9407
9408    /* package */static String getTempContainerId() {
9409        int tmpIdx = 1;
9410        String list[] = PackageHelper.getSecureContainerList();
9411        if (list != null) {
9412            for (final String name : list) {
9413                // Ignore null and non-temporary container entries
9414                if (name == null || !name.startsWith(mTempContainerPrefix)) {
9415                    continue;
9416                }
9417
9418                String subStr = name.substring(mTempContainerPrefix.length());
9419                try {
9420                    int cid = Integer.parseInt(subStr);
9421                    if (cid >= tmpIdx) {
9422                        tmpIdx = cid + 1;
9423                    }
9424                } catch (NumberFormatException e) {
9425                }
9426            }
9427        }
9428        return mTempContainerPrefix + tmpIdx;
9429    }
9430
9431    /*
9432     * Update media status on PackageManager.
9433     */
9434    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9435        int callingUid = Binder.getCallingUid();
9436        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
9437            throw new SecurityException("Media status can only be updated by the system");
9438        }
9439        // reader; this apparently protects mMediaMounted, but should probably
9440        // be a different lock in that case.
9441        synchronized (mPackages) {
9442            Log.i(TAG, "Updating external media status from "
9443                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
9444                    + (mediaStatus ? "mounted" : "unmounted"));
9445            if (DEBUG_SD_INSTALL)
9446                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
9447                        + ", mMediaMounted=" + mMediaMounted);
9448            if (mediaStatus == mMediaMounted) {
9449                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
9450                        : 0, -1);
9451                mHandler.sendMessage(msg);
9452                return;
9453            }
9454            mMediaMounted = mediaStatus;
9455        }
9456        // Queue up an async operation since the package installation may take a
9457        // little while.
9458        mHandler.post(new Runnable() {
9459            public void run() {
9460                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
9461            }
9462        });
9463    }
9464
9465    /**
9466     * Called by MountService when the initial ASECs to scan are available.
9467     * Should block until all the ASEC containers are finished being scanned.
9468     */
9469    public void scanAvailableAsecs() {
9470        updateExternalMediaStatusInner(true, false, false);
9471    }
9472
9473    /*
9474     * Collect information of applications on external media, map them against
9475     * existing containers and update information based on current mount status.
9476     * Please note that we always have to report status if reportStatus has been
9477     * set to true especially when unloading packages.
9478     */
9479    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
9480            boolean externalStorage) {
9481        // Collection of uids
9482        int uidArr[] = null;
9483        // Collection of stale containers
9484        HashSet<String> removeCids = new HashSet<String>();
9485        // Collection of packages on external media with valid containers.
9486        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
9487        // Get list of secure containers.
9488        final String list[] = PackageHelper.getSecureContainerList();
9489        if (list == null || list.length == 0) {
9490            Log.i(TAG, "No secure containers on sdcard");
9491        } else {
9492            // Process list of secure containers and categorize them
9493            // as active or stale based on their package internal state.
9494            int uidList[] = new int[list.length];
9495            int num = 0;
9496            // reader
9497            synchronized (mPackages) {
9498                for (String cid : list) {
9499                    if (DEBUG_SD_INSTALL)
9500                        Log.i(TAG, "Processing container " + cid);
9501                    String pkgName = getAsecPackageName(cid);
9502                    if (pkgName == null) {
9503                        if (DEBUG_SD_INSTALL)
9504                            Log.i(TAG, "Container : " + cid + " stale");
9505                        removeCids.add(cid);
9506                        continue;
9507                    }
9508                    if (DEBUG_SD_INSTALL)
9509                        Log.i(TAG, "Looking for pkg : " + pkgName);
9510
9511                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
9512                    if (ps == null) {
9513                        Log.i(TAG, "Deleting container with no matching settings " + cid);
9514                        removeCids.add(cid);
9515                        continue;
9516                    }
9517
9518                    /*
9519                     * Skip packages that are not external if we're unmounting
9520                     * external storage.
9521                     */
9522                    if (externalStorage && !isMounted && !isExternal(ps)) {
9523                        continue;
9524                    }
9525
9526                    final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
9527                    // The package status is changed only if the code path
9528                    // matches between settings and the container id.
9529                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
9530                        if (DEBUG_SD_INSTALL) {
9531                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
9532                                    + " at code path: " + ps.codePathString);
9533                        }
9534
9535                        // We do have a valid package installed on sdcard
9536                        processCids.put(args, ps.codePathString);
9537                        final int uid = ps.appId;
9538                        if (uid != -1) {
9539                            uidList[num++] = uid;
9540                        }
9541                    } else {
9542                        Log.i(TAG, "Deleting stale container for " + cid);
9543                        removeCids.add(cid);
9544                    }
9545                }
9546            }
9547
9548            if (num > 0) {
9549                // Sort uid list
9550                Arrays.sort(uidList, 0, num);
9551                // Throw away duplicates
9552                uidArr = new int[num];
9553                uidArr[0] = uidList[0];
9554                int di = 0;
9555                for (int i = 1; i < num; i++) {
9556                    if (uidList[i - 1] != uidList[i]) {
9557                        uidArr[di++] = uidList[i];
9558                    }
9559                }
9560            }
9561        }
9562        // Process packages with valid entries.
9563        if (isMounted) {
9564            if (DEBUG_SD_INSTALL)
9565                Log.i(TAG, "Loading packages");
9566            loadMediaPackages(processCids, uidArr, removeCids);
9567            startCleaningPackages();
9568        } else {
9569            if (DEBUG_SD_INSTALL)
9570                Log.i(TAG, "Unloading packages");
9571            unloadMediaPackages(processCids, uidArr, reportStatus);
9572        }
9573    }
9574
9575   private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
9576            int uidArr[], IIntentReceiver finishedReceiver) {
9577        int size = pkgList.size();
9578        if (size > 0) {
9579            // Send broadcasts here
9580            Bundle extras = new Bundle();
9581            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
9582                    .toArray(new String[size]));
9583            if (uidArr != null) {
9584                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9585            }
9586            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9587                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
9588            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
9589        }
9590    }
9591
9592   /*
9593     * Look at potentially valid container ids from processCids If package
9594     * information doesn't match the one on record or package scanning fails,
9595     * the cid is added to list of removeCids. We currently don't delete stale
9596     * containers.
9597     */
9598   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9599            HashSet<String> removeCids) {
9600        ArrayList<String> pkgList = new ArrayList<String>();
9601        Set<AsecInstallArgs> keys = processCids.keySet();
9602        boolean doGc = false;
9603        for (AsecInstallArgs args : keys) {
9604            String codePath = processCids.get(args);
9605            if (DEBUG_SD_INSTALL)
9606                Log.i(TAG, "Loading container : " + args.cid);
9607            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9608            try {
9609                // Make sure there are no container errors first.
9610                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
9611                    Slog.e(TAG, "Failed to mount cid : " + args.cid
9612                            + " when installing from sdcard");
9613                    continue;
9614                }
9615                // Check code path here.
9616                if (codePath == null || !codePath.equals(args.getCodePath())) {
9617                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
9618                            + " does not match one in settings " + codePath);
9619                    continue;
9620                }
9621                // Parse package
9622                int parseFlags = mDefParseFlags;
9623                if (args.isExternal()) {
9624                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
9625                }
9626                if (args.isFwdLocked()) {
9627                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
9628                }
9629
9630                doGc = true;
9631                synchronized (mInstallLock) {
9632                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
9633                            0, 0, null);
9634                    // Scan the package
9635                    if (pkg != null) {
9636                        /*
9637                         * TODO why is the lock being held? doPostInstall is
9638                         * called in other places without the lock. This needs
9639                         * to be straightened out.
9640                         */
9641                        // writer
9642                        synchronized (mPackages) {
9643                            retCode = PackageManager.INSTALL_SUCCEEDED;
9644                            pkgList.add(pkg.packageName);
9645                            // Post process args
9646                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
9647                                    pkg.applicationInfo.uid);
9648                        }
9649                    } else {
9650                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
9651                    }
9652                }
9653
9654            } finally {
9655                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9656                    // Don't destroy container here. Wait till gc clears things
9657                    // up.
9658                    removeCids.add(args.cid);
9659                }
9660            }
9661        }
9662        // writer
9663        synchronized (mPackages) {
9664            // If the platform SDK has changed since the last time we booted,
9665            // we need to re-grant app permission to catch any new ones that
9666            // appear. This is really a hack, and means that apps can in some
9667            // cases get permissions that the user didn't initially explicitly
9668            // allow... it would be nice to have some better way to handle
9669            // this situation.
9670            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
9671            if (regrantPermissions)
9672                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
9673                        + mSdkVersion + "; regranting permissions for external storage");
9674            mSettings.mExternalSdkPlatform = mSdkVersion;
9675
9676            // Make sure group IDs have been assigned, and any permission
9677            // changes in other apps are accounted for
9678            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
9679                    | (regrantPermissions
9680                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
9681                            : 0));
9682            // can downgrade to reader
9683            // Persist settings
9684            mSettings.writeLPr();
9685        }
9686        // Send a broadcast to let everyone know we are done processing
9687        if (pkgList.size() > 0) {
9688            sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9689        }
9690        // Force gc to avoid any stale parser references that we might have.
9691        if (doGc) {
9692            Runtime.getRuntime().gc();
9693        }
9694        // List stale containers and destroy stale temporary containers.
9695        if (removeCids != null) {
9696            for (String cid : removeCids) {
9697                if (cid.startsWith(mTempContainerPrefix)) {
9698                    Log.i(TAG, "Destroying stale temporary container " + cid);
9699                    PackageHelper.destroySdDir(cid);
9700                } else {
9701                    Log.w(TAG, "Container " + cid + " is stale");
9702               }
9703           }
9704        }
9705    }
9706
9707   /*
9708     * Utility method to unload a list of specified containers
9709     */
9710    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
9711        // Just unmount all valid containers.
9712        for (AsecInstallArgs arg : cidArgs) {
9713            synchronized (mInstallLock) {
9714                arg.doPostDeleteLI(false);
9715           }
9716       }
9717   }
9718
9719    /*
9720     * Unload packages mounted on external media. This involves deleting package
9721     * data from internal structures, sending broadcasts about diabled packages,
9722     * gc'ing to free up references, unmounting all secure containers
9723     * corresponding to packages on external media, and posting a
9724     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
9725     * that we always have to post this message if status has been requested no
9726     * matter what.
9727     */
9728    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
9729            final boolean reportStatus) {
9730        if (DEBUG_SD_INSTALL)
9731            Log.i(TAG, "unloading media packages");
9732        ArrayList<String> pkgList = new ArrayList<String>();
9733        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
9734        final Set<AsecInstallArgs> keys = processCids.keySet();
9735        for (AsecInstallArgs args : keys) {
9736            String pkgName = args.getPackageName();
9737            if (DEBUG_SD_INSTALL)
9738                Log.i(TAG, "Trying to unload pkg : " + pkgName);
9739            // Delete package internally
9740            PackageRemovedInfo outInfo = new PackageRemovedInfo();
9741            synchronized (mInstallLock) {
9742                boolean res = deletePackageLI(pkgName, null, false,
9743                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
9744                if (res) {
9745                    pkgList.add(pkgName);
9746                } else {
9747                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
9748                    failedList.add(args);
9749                }
9750            }
9751        }
9752
9753        // reader
9754        synchronized (mPackages) {
9755            // We didn't update the settings after removing each package;
9756            // write them now for all packages.
9757            mSettings.writeLPr();
9758        }
9759
9760        // We have to absolutely send UPDATED_MEDIA_STATUS only
9761        // after confirming that all the receivers processed the ordered
9762        // broadcast when packages get disabled, force a gc to clean things up.
9763        // and unload all the containers.
9764        if (pkgList.size() > 0) {
9765            sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9766                public void performReceive(Intent intent, int resultCode, String data,
9767                        Bundle extras, boolean ordered, boolean sticky,
9768                        int sendingUser) throws RemoteException {
9769                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9770                            reportStatus ? 1 : 0, 1, keys);
9771                    mHandler.sendMessage(msg);
9772                }
9773            });
9774        } else {
9775            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
9776                    keys);
9777            mHandler.sendMessage(msg);
9778        }
9779    }
9780
9781    /** Binder call */
9782    @Override
9783    public void movePackage(final String packageName, final IPackageMoveObserver observer,
9784            final int flags) {
9785        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
9786        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
9787        int returnCode = PackageManager.MOVE_SUCCEEDED;
9788        int currFlags = 0;
9789        int newFlags = 0;
9790        // reader
9791        synchronized (mPackages) {
9792            PackageParser.Package pkg = mPackages.get(packageName);
9793            if (pkg == null) {
9794                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9795            } else {
9796                // Disable moving fwd locked apps and system packages
9797                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
9798                    Slog.w(TAG, "Cannot move system application");
9799                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9800                } else if (pkg.mOperationPending) {
9801                    Slog.w(TAG, "Attempt to move package which has pending operations");
9802                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
9803                } else {
9804                    // Find install location first
9805                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
9806                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
9807                        Slog.w(TAG, "Ambigous flags specified for move location.");
9808                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9809                    } else {
9810                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
9811                                : PackageManager.INSTALL_INTERNAL;
9812                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9813                                : PackageManager.INSTALL_INTERNAL;
9814
9815                        if (newFlags == currFlags) {
9816                            Slog.w(TAG, "No move required. Trying to move to same location");
9817                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9818                        } else {
9819                            if (isForwardLocked(pkg)) {
9820                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9821                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
9822                            }
9823                        }
9824                    }
9825                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9826                        pkg.mOperationPending = true;
9827                    }
9828                }
9829            }
9830
9831            /*
9832             * TODO this next block probably shouldn't be inside the lock. We
9833             * can't guarantee these won't change after this is fired off
9834             * anyway.
9835             */
9836            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9837                processPendingMove(new MoveParams(null, observer, 0, packageName,
9838                        null, -1, user),
9839                        returnCode);
9840            } else {
9841                Message msg = mHandler.obtainMessage(INIT_COPY);
9842                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9843                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9844                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9845                        pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
9846                msg.obj = mp;
9847                mHandler.sendMessage(msg);
9848            }
9849        }
9850    }
9851
9852    private void processPendingMove(final MoveParams mp, final int currentStatus) {
9853        // Queue up an async operation since the package deletion may take a
9854        // little while.
9855        mHandler.post(new Runnable() {
9856            public void run() {
9857                // TODO fix this; this does nothing.
9858                mHandler.removeCallbacks(this);
9859                int returnCode = currentStatus;
9860                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9861                    int uidArr[] = null;
9862                    ArrayList<String> pkgList = null;
9863                    synchronized (mPackages) {
9864                        PackageParser.Package pkg = mPackages.get(mp.packageName);
9865                        if (pkg == null) {
9866                            Slog.w(TAG, " Package " + mp.packageName
9867                                    + " doesn't exist. Aborting move");
9868                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9869                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9870                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
9871                                    + mp.srcArgs.getCodePath() + " to "
9872                                    + pkg.applicationInfo.sourceDir
9873                                    + " Aborting move and returning error");
9874                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9875                        } else {
9876                            uidArr = new int[] {
9877                                pkg.applicationInfo.uid
9878                            };
9879                            pkgList = new ArrayList<String>();
9880                            pkgList.add(mp.packageName);
9881                        }
9882                    }
9883                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9884                        // Send resources unavailable broadcast
9885                        sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
9886                        // Update package code and resource paths
9887                        synchronized (mInstallLock) {
9888                            synchronized (mPackages) {
9889                                PackageParser.Package pkg = mPackages.get(mp.packageName);
9890                                // Recheck for package again.
9891                                if (pkg == null) {
9892                                    Slog.w(TAG, " Package " + mp.packageName
9893                                            + " doesn't exist. Aborting move");
9894                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9895                                } else if (!mp.srcArgs.getCodePath().equals(
9896                                        pkg.applicationInfo.sourceDir)) {
9897                                    Slog.w(TAG, "Package " + mp.packageName
9898                                            + " code path changed from " + mp.srcArgs.getCodePath()
9899                                            + " to " + pkg.applicationInfo.sourceDir
9900                                            + " Aborting move and returning error");
9901                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9902                                } else {
9903                                    final String oldCodePath = pkg.mPath;
9904                                    final String newCodePath = mp.targetArgs.getCodePath();
9905                                    final String newResPath = mp.targetArgs.getResourcePath();
9906                                    final String newNativePath = mp.targetArgs
9907                                            .getNativeLibraryPath();
9908
9909                                    final File newNativeDir = new File(newNativePath);
9910
9911                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
9912                                        synchronized (mInstallLock) {
9913                                            if (mInstaller.linkNativeLibraryDirectory(
9914                                                    pkg.applicationInfo.dataDir, newNativePath) < 0) {
9915                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9916                                            }
9917                                        }
9918                                        NativeLibraryHelper.copyNativeBinariesIfNeededLI(new File(
9919                                                newCodePath), newNativeDir);
9920                                    } else {
9921                                        synchronized (mInstallLock) {
9922                                            if (mInstaller.linkNativeLibraryDirectory(
9923                                                    pkg.applicationInfo.dataDir, newNativePath) < 0) {
9924                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9925                                            }
9926                                        }
9927                                    }
9928
9929                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9930                                        pkg.mPath = newCodePath;
9931                                        // Move dex files around
9932                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
9933                                            // Moving of dex files failed. Set
9934                                            // error code and abort move.
9935                                            pkg.mPath = pkg.mScanPath;
9936                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9937                                        }
9938                                    }
9939
9940                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9941                                        pkg.mScanPath = newCodePath;
9942                                        pkg.applicationInfo.sourceDir = newCodePath;
9943                                        pkg.applicationInfo.publicSourceDir = newResPath;
9944                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
9945                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
9946                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
9947                                        ps.codePathString = ps.codePath.getPath();
9948                                        ps.resourcePath = new File(
9949                                                pkg.applicationInfo.publicSourceDir);
9950                                        ps.resourcePathString = ps.resourcePath.getPath();
9951                                        ps.nativeLibraryPathString = newNativePath;
9952                                        // Set the application info flag
9953                                        // correctly.
9954                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9955                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9956                                        } else {
9957                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9958                                        }
9959                                        ps.setFlags(pkg.applicationInfo.flags);
9960                                        mAppDirs.remove(oldCodePath);
9961                                        mAppDirs.put(newCodePath, pkg);
9962                                        // Persist settings
9963                                        mSettings.writeLPr();
9964                                    }
9965                                }
9966                            }
9967                        }
9968                        // Send resources available broadcast
9969                        sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
9970                    }
9971                }
9972                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9973                    // Clean up failed installation
9974                    if (mp.targetArgs != null) {
9975                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
9976                                -1);
9977                    }
9978                } else {
9979                    // Force a gc to clear things up.
9980                    Runtime.getRuntime().gc();
9981                    // Delete older code
9982                    synchronized (mInstallLock) {
9983                        mp.srcArgs.doPostDeleteLI(true);
9984                    }
9985                }
9986
9987                // Allow more operations on this file if we didn't fail because
9988                // an operation was already pending for this package.
9989                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9990                    synchronized (mPackages) {
9991                        PackageParser.Package pkg = mPackages.get(mp.packageName);
9992                        if (pkg != null) {
9993                            pkg.mOperationPending = false;
9994                       }
9995                   }
9996                }
9997
9998                IPackageMoveObserver observer = mp.observer;
9999                if (observer != null) {
10000                    try {
10001                        observer.packageMoved(mp.packageName, returnCode);
10002                    } catch (RemoteException e) {
10003                        Log.i(TAG, "Observer no longer exists.");
10004                    }
10005                }
10006            }
10007        });
10008    }
10009
10010    public boolean setInstallLocation(int loc) {
10011        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
10012                null);
10013        if (getInstallLocation() == loc) {
10014            return true;
10015        }
10016        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
10017                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10018            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
10019                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
10020            return true;
10021        }
10022        return false;
10023   }
10024
10025    public int getInstallLocation() {
10026        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10027                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
10028                PackageHelper.APP_INSTALL_AUTO);
10029    }
10030
10031    /** Called by UserManagerService */
10032    void cleanUpUserLILPw(int userHandle) {
10033        // Disable all the packages for the user first
10034        Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet();
10035        for (Entry<String, PackageSetting> entry : entries) {
10036            entry.getValue().removeUser(userHandle);
10037        }
10038        if (mDirtyUsers.remove(userHandle));
10039        mSettings.removeUserLPr(userHandle);
10040        if (mInstaller != null) {
10041            // Technically, we shouldn't be doing this with the package lock
10042            // held.  However, this is very rare, and there is already so much
10043            // other disk I/O going on, that we'll let it slide for now.
10044            mInstaller.removeUserDataDirs(userHandle);
10045        }
10046    }
10047
10048    /** Called by UserManagerService */
10049    void createNewUserLILPw(int userHandle, File path) {
10050        if (mInstaller != null) {
10051            path.mkdir();
10052            FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
10053                    | FileUtils.S_IXOTH, -1, -1);
10054            for (PackageSetting ps : mSettings.mPackages.values()) {
10055                // Only system apps are initially installed.
10056                ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
10057                // Need to create a data directory for all apps under this user.
10058                mInstaller.createUserData(ps.name,
10059                        UserHandle.getUid(userHandle, ps.appId), userHandle);
10060            }
10061            mSettings.writePackageRestrictionsLPr(userHandle);
10062        }
10063    }
10064
10065    @Override
10066    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
10067        mContext.enforceCallingOrSelfPermission(
10068                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10069                "Only package verification agents can read the verifier device identity");
10070
10071        synchronized (mPackages) {
10072            return mSettings.getVerifierDeviceIdentityLPw();
10073        }
10074    }
10075
10076    @Override
10077    public void setPermissionEnforced(String permission, boolean enforced) {
10078        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
10079        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10080            synchronized (mPackages) {
10081                if (mSettings.mReadExternalStorageEnforced == null
10082                        || mSettings.mReadExternalStorageEnforced != enforced) {
10083                    mSettings.mReadExternalStorageEnforced = enforced;
10084                    mSettings.writeLPr();
10085
10086                    // kill any non-foreground processes so we restart them and
10087                    // grant/revoke the GID.
10088                    final IActivityManager am = ActivityManagerNative.getDefault();
10089                    if (am != null) {
10090                        final long token = Binder.clearCallingIdentity();
10091                        try {
10092                            am.killProcessesBelowForeground("setPermissionEnforcement");
10093                        } catch (RemoteException e) {
10094                        } finally {
10095                            Binder.restoreCallingIdentity(token);
10096                        }
10097                    }
10098                }
10099            }
10100        } else {
10101            throw new IllegalArgumentException("No selective enforcement for " + permission);
10102        }
10103    }
10104
10105    @Override
10106    public boolean isPermissionEnforced(String permission) {
10107        final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
10108        synchronized (mPackages) {
10109            return isPermissionEnforcedLocked(permission, enforcedDefault);
10110        }
10111    }
10112
10113    /**
10114     * Check if given permission should be enforced by default. Should always be
10115     * called outside of {@link #mPackages} lock.
10116     */
10117    private boolean isPermissionEnforcedDefault(String permission) {
10118        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10119            return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10120                    android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
10121                    != 0;
10122        } else {
10123            return true;
10124        }
10125    }
10126
10127    /**
10128     * Check if user has requested that given permission be enforced, using
10129     * given default if undefined.
10130     */
10131    private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
10132        if (READ_EXTERNAL_STORAGE.equals(permission)) {
10133            if (mSettings.mReadExternalStorageEnforced != null) {
10134                return mSettings.mReadExternalStorageEnforced;
10135            } else {
10136                // User hasn't defined; fall back to secure default
10137                return enforcedDefault;
10138            }
10139        } else {
10140            return true;
10141        }
10142    }
10143
10144    public boolean isStorageLow() {
10145        final long token = Binder.clearCallingIdentity();
10146        try {
10147            final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
10148                    .getService(DeviceStorageMonitorService.SERVICE);
10149            return dsm.isMemoryLow();
10150        } finally {
10151            Binder.restoreCallingIdentity(token);
10152        }
10153    }
10154}
10155