OSDN Git Service

am 288ecf98: Merge "Prioritize most-recently-enabled link-handling app" into mnc-dev
[android-x86/frameworks-base.git] / services / core / java / com / android / server / pm / PackageManagerService.java
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
17 package com.android.server.pm;
18
19 import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60 import static android.content.pm.PackageManager.MATCH_ALL;
61 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66 import static android.content.pm.PackageParser.isApkFile;
67 import static android.os.Process.PACKAGE_INFO_GID;
68 import static android.os.Process.SYSTEM_UID;
69 import static android.system.OsConstants.O_CREAT;
70 import static android.system.OsConstants.O_RDWR;
71 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75 import static com.android.internal.util.ArrayUtils.appendInt;
76 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85 import android.Manifest;
86 import android.app.ActivityManager;
87 import android.app.ActivityManagerNative;
88 import android.app.AppGlobals;
89 import android.app.IActivityManager;
90 import android.app.admin.IDevicePolicyManager;
91 import android.app.backup.IBackupManager;
92 import android.app.usage.UsageStats;
93 import android.app.usage.UsageStatsManager;
94 import android.content.BroadcastReceiver;
95 import android.content.ComponentName;
96 import android.content.Context;
97 import android.content.IIntentReceiver;
98 import android.content.Intent;
99 import android.content.IntentFilter;
100 import android.content.IntentSender;
101 import android.content.IntentSender.SendIntentException;
102 import android.content.ServiceConnection;
103 import android.content.pm.ActivityInfo;
104 import android.content.pm.ApplicationInfo;
105 import android.content.pm.FeatureInfo;
106 import android.content.pm.IOnPermissionsChangeListener;
107 import android.content.pm.IPackageDataObserver;
108 import android.content.pm.IPackageDeleteObserver;
109 import android.content.pm.IPackageDeleteObserver2;
110 import android.content.pm.IPackageInstallObserver2;
111 import android.content.pm.IPackageInstaller;
112 import android.content.pm.IPackageManager;
113 import android.content.pm.IPackageMoveObserver;
114 import android.content.pm.IPackageStatsObserver;
115 import android.content.pm.InstrumentationInfo;
116 import android.content.pm.IntentFilterVerificationInfo;
117 import android.content.pm.KeySet;
118 import android.content.pm.ManifestDigest;
119 import android.content.pm.PackageCleanItem;
120 import android.content.pm.PackageInfo;
121 import android.content.pm.PackageInfoLite;
122 import android.content.pm.PackageInstaller;
123 import android.content.pm.PackageManager;
124 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125 import android.content.pm.PackageManagerInternal;
126 import android.content.pm.PackageParser;
127 import android.content.pm.PackageParser.ActivityIntentInfo;
128 import android.content.pm.PackageParser.PackageLite;
129 import android.content.pm.PackageParser.PackageParserException;
130 import android.content.pm.PackageStats;
131 import android.content.pm.PackageUserState;
132 import android.content.pm.ParceledListSlice;
133 import android.content.pm.PermissionGroupInfo;
134 import android.content.pm.PermissionInfo;
135 import android.content.pm.ProviderInfo;
136 import android.content.pm.ResolveInfo;
137 import android.content.pm.ServiceInfo;
138 import android.content.pm.Signature;
139 import android.content.pm.UserInfo;
140 import android.content.pm.VerificationParams;
141 import android.content.pm.VerifierDeviceIdentity;
142 import android.content.pm.VerifierInfo;
143 import android.content.res.Resources;
144 import android.hardware.display.DisplayManager;
145 import android.net.Uri;
146 import android.os.Binder;
147 import android.os.Build;
148 import android.os.Bundle;
149 import android.os.Environment;
150 import android.os.Environment.UserEnvironment;
151 import android.os.FileUtils;
152 import android.os.Handler;
153 import android.os.IBinder;
154 import android.os.Looper;
155 import android.os.Message;
156 import android.os.Parcel;
157 import android.os.ParcelFileDescriptor;
158 import android.os.Process;
159 import android.os.RemoteCallbackList;
160 import android.os.RemoteException;
161 import android.os.SELinux;
162 import android.os.ServiceManager;
163 import android.os.SystemClock;
164 import android.os.SystemProperties;
165 import android.os.UserHandle;
166 import android.os.UserManager;
167 import android.os.storage.IMountService;
168 import android.os.storage.StorageEventListener;
169 import android.os.storage.StorageManager;
170 import android.os.storage.VolumeInfo;
171 import android.os.storage.VolumeRecord;
172 import android.security.KeyStore;
173 import android.security.SystemKeyStore;
174 import android.system.ErrnoException;
175 import android.system.Os;
176 import android.system.StructStat;
177 import android.text.TextUtils;
178 import android.text.format.DateUtils;
179 import android.util.ArrayMap;
180 import android.util.ArraySet;
181 import android.util.AtomicFile;
182 import android.util.DisplayMetrics;
183 import android.util.EventLog;
184 import android.util.ExceptionUtils;
185 import android.util.Log;
186 import android.util.LogPrinter;
187 import android.util.MathUtils;
188 import android.util.PrintStreamPrinter;
189 import android.util.Slog;
190 import android.util.SparseArray;
191 import android.util.SparseBooleanArray;
192 import android.util.SparseIntArray;
193 import android.util.Xml;
194 import android.view.Display;
195
196 import dalvik.system.DexFile;
197 import dalvik.system.VMRuntime;
198
199 import libcore.io.IoUtils;
200 import libcore.util.EmptyArray;
201
202 import com.android.internal.R;
203 import com.android.internal.annotations.GuardedBy;
204 import com.android.internal.app.IMediaContainerService;
205 import com.android.internal.app.ResolverActivity;
206 import com.android.internal.content.NativeLibraryHelper;
207 import com.android.internal.content.PackageHelper;
208 import com.android.internal.os.IParcelFileDescriptorFactory;
209 import com.android.internal.os.SomeArgs;
210 import com.android.internal.os.Zygote;
211 import com.android.internal.util.ArrayUtils;
212 import com.android.internal.util.FastPrintWriter;
213 import com.android.internal.util.FastXmlSerializer;
214 import com.android.internal.util.IndentingPrintWriter;
215 import com.android.internal.util.Preconditions;
216 import com.android.server.EventLogTags;
217 import com.android.server.FgThread;
218 import com.android.server.IntentResolver;
219 import com.android.server.LocalServices;
220 import com.android.server.ServiceThread;
221 import com.android.server.SystemConfig;
222 import com.android.server.Watchdog;
223 import com.android.server.pm.PermissionsState.PermissionState;
224 import com.android.server.pm.Settings.DatabaseVersion;
225 import com.android.server.storage.DeviceStorageMonitorInternal;
226
227 import org.xmlpull.v1.XmlPullParser;
228 import org.xmlpull.v1.XmlPullParserException;
229 import org.xmlpull.v1.XmlSerializer;
230
231 import java.io.BufferedInputStream;
232 import java.io.BufferedOutputStream;
233 import java.io.BufferedReader;
234 import java.io.ByteArrayInputStream;
235 import java.io.ByteArrayOutputStream;
236 import java.io.File;
237 import java.io.FileDescriptor;
238 import java.io.FileNotFoundException;
239 import java.io.FileOutputStream;
240 import java.io.FileReader;
241 import java.io.FilenameFilter;
242 import java.io.IOException;
243 import java.io.InputStream;
244 import java.io.PrintWriter;
245 import java.nio.charset.StandardCharsets;
246 import java.security.NoSuchAlgorithmException;
247 import java.security.PublicKey;
248 import java.security.cert.CertificateEncodingException;
249 import java.security.cert.CertificateException;
250 import java.text.SimpleDateFormat;
251 import java.util.ArrayList;
252 import java.util.Arrays;
253 import java.util.Collection;
254 import java.util.Collections;
255 import java.util.Comparator;
256 import java.util.Date;
257 import java.util.Iterator;
258 import java.util.List;
259 import java.util.Map;
260 import java.util.Objects;
261 import java.util.Set;
262 import java.util.concurrent.CountDownLatch;
263 import java.util.concurrent.TimeUnit;
264 import java.util.concurrent.atomic.AtomicBoolean;
265 import java.util.concurrent.atomic.AtomicInteger;
266 import java.util.concurrent.atomic.AtomicLong;
267
268 /**
269  * Keep track of all those .apks everywhere.
270  *
271  * This is very central to the platform's security; please run the unit
272  * tests whenever making modifications here:
273  *
274 mmm frameworks/base/tests/AndroidTests
275 adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
276 adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
277  *
278  * {@hide}
279  */
280 public class PackageManagerService extends IPackageManager.Stub {
281     static final String TAG = "PackageManager";
282     static final boolean DEBUG_SETTINGS = false;
283     static final boolean DEBUG_PREFERRED = false;
284     static final boolean DEBUG_UPGRADE = false;
285     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
286     private static final boolean DEBUG_BACKUP = false;
287     private static final boolean DEBUG_INSTALL = false;
288     private static final boolean DEBUG_REMOVE = false;
289     private static final boolean DEBUG_BROADCASTS = false;
290     private static final boolean DEBUG_SHOW_INFO = false;
291     private static final boolean DEBUG_PACKAGE_INFO = false;
292     private static final boolean DEBUG_INTENT_MATCHING = false;
293     private static final boolean DEBUG_PACKAGE_SCANNING = false;
294     private static final boolean DEBUG_VERIFY = false;
295     private static final boolean DEBUG_DEXOPT = false;
296     private static final boolean DEBUG_ABI_SELECTION = false;
297
298     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
299
300     private static final int RADIO_UID = Process.PHONE_UID;
301     private static final int LOG_UID = Process.LOG_UID;
302     private static final int NFC_UID = Process.NFC_UID;
303     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
304     private static final int SHELL_UID = Process.SHELL_UID;
305
306     // Cap the size of permission trees that 3rd party apps can define
307     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
308
309     // Suffix used during package installation when copying/moving
310     // package apks to install directory.
311     private static final String INSTALL_PACKAGE_SUFFIX = "-";
312
313     static final int SCAN_NO_DEX = 1<<1;
314     static final int SCAN_FORCE_DEX = 1<<2;
315     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
316     static final int SCAN_NEW_INSTALL = 1<<4;
317     static final int SCAN_NO_PATHS = 1<<5;
318     static final int SCAN_UPDATE_TIME = 1<<6;
319     static final int SCAN_DEFER_DEX = 1<<7;
320     static final int SCAN_BOOTING = 1<<8;
321     static final int SCAN_TRUSTED_OVERLAY = 1<<9;
322     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
323     static final int SCAN_REQUIRE_KNOWN = 1<<12;
324     static final int SCAN_MOVE = 1<<13;
325     static final int SCAN_INITIAL = 1<<14;
326
327     static final int REMOVE_CHATTY = 1<<16;
328
329     private static final int[] EMPTY_INT_ARRAY = new int[0];
330
331     /**
332      * Timeout (in milliseconds) after which the watchdog should declare that
333      * our handler thread is wedged.  The usual default for such things is one
334      * minute but we sometimes do very lengthy I/O operations on this thread,
335      * such as installing multi-gigabyte applications, so ours needs to be longer.
336      */
337     private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
338
339     /**
340      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
341      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
342      * settings entry if available, otherwise we use the hardcoded default.  If it's been
343      * more than this long since the last fstrim, we force one during the boot sequence.
344      *
345      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
346      * one gets run at the next available charging+idle time.  This final mandatory
347      * no-fstrim check kicks in only of the other scheduling criteria is never met.
348      */
349     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
350
351     /**
352      * Whether verification is enabled by default.
353      */
354     private static final boolean DEFAULT_VERIFY_ENABLE = true;
355
356     /**
357      * The default maximum time to wait for the verification agent to return in
358      * milliseconds.
359      */
360     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
361
362     /**
363      * The default response for package verification timeout.
364      *
365      * This can be either PackageManager.VERIFICATION_ALLOW or
366      * PackageManager.VERIFICATION_REJECT.
367      */
368     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
369
370     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
371
372     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
373             DEFAULT_CONTAINER_PACKAGE,
374             "com.android.defcontainer.DefaultContainerService");
375
376     private static final String KILL_APP_REASON_GIDS_CHANGED =
377             "permission grant or revoke changed gids";
378
379     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
380             "permissions revoked";
381
382     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
383
384     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
385
386     /** Permission grant: not grant the permission. */
387     private static final int GRANT_DENIED = 1;
388
389     /** Permission grant: grant the permission as an install permission. */
390     private static final int GRANT_INSTALL = 2;
391
392     /** Permission grant: grant the permission as an install permission for a legacy app. */
393     private static final int GRANT_INSTALL_LEGACY = 3;
394
395     /** Permission grant: grant the permission as a runtime one. */
396     private static final int GRANT_RUNTIME = 4;
397
398     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
399     private static final int GRANT_UPGRADE = 5;
400
401     /** Canonical intent used to identify what counts as a "web browser" app */
402     private static final Intent sBrowserIntent;
403     static {
404         sBrowserIntent = new Intent();
405         sBrowserIntent.setAction(Intent.ACTION_VIEW);
406         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
407         sBrowserIntent.setData(Uri.parse("http:"));
408     }
409
410     final ServiceThread mHandlerThread;
411
412     final PackageHandler mHandler;
413
414     /**
415      * Messages for {@link #mHandler} that need to wait for system ready before
416      * being dispatched.
417      */
418     private ArrayList<Message> mPostSystemReadyMessages;
419
420     final int mSdkVersion = Build.VERSION.SDK_INT;
421
422     final Context mContext;
423     final boolean mFactoryTest;
424     final boolean mOnlyCore;
425     final boolean mLazyDexOpt;
426     final long mDexOptLRUThresholdInMills;
427     final DisplayMetrics mMetrics;
428     final int mDefParseFlags;
429     final String[] mSeparateProcesses;
430     final boolean mIsUpgrade;
431
432     // This is where all application persistent data goes.
433     final File mAppDataDir;
434
435     // This is where all application persistent data goes for secondary users.
436     final File mUserAppDataDir;
437
438     /** The location for ASEC container files on internal storage. */
439     final String mAsecInternalPath;
440
441     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
442     // LOCK HELD.  Can be called with mInstallLock held.
443     @GuardedBy("mInstallLock")
444     final Installer mInstaller;
445
446     /** Directory where installed third-party apps stored */
447     final File mAppInstallDir;
448
449     /**
450      * Directory to which applications installed internally have their
451      * 32 bit native libraries copied.
452      */
453     private File mAppLib32InstallDir;
454
455     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
456     // apps.
457     final File mDrmAppPrivateInstallDir;
458
459     // ----------------------------------------------------------------
460
461     // Lock for state used when installing and doing other long running
462     // operations.  Methods that must be called with this lock held have
463     // the suffix "LI".
464     final Object mInstallLock = new Object();
465
466     // ----------------------------------------------------------------
467
468     // Keys are String (package name), values are Package.  This also serves
469     // as the lock for the global state.  Methods that must be called with
470     // this lock held have the prefix "LP".
471     @GuardedBy("mPackages")
472     final ArrayMap<String, PackageParser.Package> mPackages =
473             new ArrayMap<String, PackageParser.Package>();
474
475     // Tracks available target package names -> overlay package paths.
476     final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
477         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
478
479     /**
480      * Tracks new system packages [receiving in an OTA] that we expect to
481      * find updated user-installed versions. Keys are package name, values
482      * are package location.
483      */
484     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
485
486     final Settings mSettings;
487     boolean mRestoredSettings;
488
489     // System configuration read by SystemConfig.
490     final int[] mGlobalGids;
491     final SparseArray<ArraySet<String>> mSystemPermissions;
492     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
493
494     // If mac_permissions.xml was found for seinfo labeling.
495     boolean mFoundPolicyFile;
496
497     // If a recursive restorecon of /data/data/<pkg> is needed.
498     private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
499
500     public static final class SharedLibraryEntry {
501         public final String path;
502         public final String apk;
503
504         SharedLibraryEntry(String _path, String _apk) {
505             path = _path;
506             apk = _apk;
507         }
508     }
509
510     // Currently known shared libraries.
511     final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
512             new ArrayMap<String, SharedLibraryEntry>();
513
514     // All available activities, for your resolving pleasure.
515     final ActivityIntentResolver mActivities =
516             new ActivityIntentResolver();
517
518     // All available receivers, for your resolving pleasure.
519     final ActivityIntentResolver mReceivers =
520             new ActivityIntentResolver();
521
522     // All available services, for your resolving pleasure.
523     final ServiceIntentResolver mServices = new ServiceIntentResolver();
524
525     // All available providers, for your resolving pleasure.
526     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
527
528     // Mapping from provider base names (first directory in content URI codePath)
529     // to the provider information.
530     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
531             new ArrayMap<String, PackageParser.Provider>();
532
533     // Mapping from instrumentation class names to info about them.
534     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
535             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
536
537     // Mapping from permission names to info about them.
538     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
539             new ArrayMap<String, PackageParser.PermissionGroup>();
540
541     // Packages whose data we have transfered into another package, thus
542     // should no longer exist.
543     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
544
545     // Broadcast actions that are only available to the system.
546     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
547
548     /** List of packages waiting for verification. */
549     final SparseArray<PackageVerificationState> mPendingVerification
550             = new SparseArray<PackageVerificationState>();
551
552     /** Set of packages associated with each app op permission. */
553     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
554
555     final PackageInstallerService mInstallerService;
556
557     private final PackageDexOptimizer mPackageDexOptimizer;
558
559     private AtomicInteger mNextMoveId = new AtomicInteger();
560     private final MoveCallbacks mMoveCallbacks;
561
562     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
563
564     // Cache of users who need badging.
565     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
566
567     /** Token for keys in mPendingVerification. */
568     private int mPendingVerificationToken = 0;
569
570     volatile boolean mSystemReady;
571     volatile boolean mSafeMode;
572     volatile boolean mHasSystemUidErrors;
573
574     ApplicationInfo mAndroidApplication;
575     final ActivityInfo mResolveActivity = new ActivityInfo();
576     final ResolveInfo mResolveInfo = new ResolveInfo();
577     ComponentName mResolveComponentName;
578     PackageParser.Package mPlatformPackage;
579     ComponentName mCustomResolverComponentName;
580
581     boolean mResolverReplaced = false;
582
583     private final ComponentName mIntentFilterVerifierComponent;
584     private int mIntentFilterVerificationToken = 0;
585
586     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
587             = new SparseArray<IntentFilterVerificationState>();
588
589     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
590             new DefaultPermissionGrantPolicy(this);
591
592     private static class IFVerificationParams {
593         PackageParser.Package pkg;
594         boolean replacing;
595         int userId;
596         int verifierUid;
597
598         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
599                 int _userId, int _verifierUid) {
600             pkg = _pkg;
601             replacing = _replacing;
602             userId = _userId;
603             replacing = _replacing;
604             verifierUid = _verifierUid;
605         }
606     }
607
608     private interface IntentFilterVerifier<T extends IntentFilter> {
609         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
610                                                T filter, String packageName);
611         void startVerifications(int userId);
612         void receiveVerificationResponse(int verificationId);
613     }
614
615     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
616         private Context mContext;
617         private ComponentName mIntentFilterVerifierComponent;
618         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
619
620         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
621             mContext = context;
622             mIntentFilterVerifierComponent = verifierComponent;
623         }
624
625         private String getDefaultScheme() {
626             return IntentFilter.SCHEME_HTTPS;
627         }
628
629         @Override
630         public void startVerifications(int userId) {
631             // Launch verifications requests
632             int count = mCurrentIntentFilterVerifications.size();
633             for (int n=0; n<count; n++) {
634                 int verificationId = mCurrentIntentFilterVerifications.get(n);
635                 final IntentFilterVerificationState ivs =
636                         mIntentFilterVerificationStates.get(verificationId);
637
638                 String packageName = ivs.getPackageName();
639
640                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
641                 final int filterCount = filters.size();
642                 ArraySet<String> domainsSet = new ArraySet<>();
643                 for (int m=0; m<filterCount; m++) {
644                     PackageParser.ActivityIntentInfo filter = filters.get(m);
645                     domainsSet.addAll(filter.getHostsList());
646                 }
647                 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
648                 synchronized (mPackages) {
649                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
650                             packageName, domainsList) != null) {
651                         scheduleWriteSettingsLocked();
652                     }
653                 }
654                 sendVerificationRequest(userId, verificationId, ivs);
655             }
656             mCurrentIntentFilterVerifications.clear();
657         }
658
659         private void sendVerificationRequest(int userId, int verificationId,
660                 IntentFilterVerificationState ivs) {
661
662             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
663             verificationIntent.putExtra(
664                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
665                     verificationId);
666             verificationIntent.putExtra(
667                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
668                     getDefaultScheme());
669             verificationIntent.putExtra(
670                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
671                     ivs.getHostsString());
672             verificationIntent.putExtra(
673                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
674                     ivs.getPackageName());
675             verificationIntent.setComponent(mIntentFilterVerifierComponent);
676             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
677
678             UserHandle user = new UserHandle(userId);
679             mContext.sendBroadcastAsUser(verificationIntent, user);
680             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
681                     "Sending IntentFilter verification broadcast");
682         }
683
684         public void receiveVerificationResponse(int verificationId) {
685             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
686
687             final boolean verified = ivs.isVerified();
688
689             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
690             final int count = filters.size();
691             if (DEBUG_DOMAIN_VERIFICATION) {
692                 Slog.i(TAG, "Received verification response " + verificationId
693                         + " for " + count + " filters, verified=" + verified);
694             }
695             for (int n=0; n<count; n++) {
696                 PackageParser.ActivityIntentInfo filter = filters.get(n);
697                 filter.setVerified(verified);
698
699                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
700                         + " verified with result:" + verified + " and hosts:"
701                         + ivs.getHostsString());
702             }
703
704             mIntentFilterVerificationStates.remove(verificationId);
705
706             final String packageName = ivs.getPackageName();
707             IntentFilterVerificationInfo ivi = null;
708
709             synchronized (mPackages) {
710                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
711             }
712             if (ivi == null) {
713                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
714                         + verificationId + " packageName:" + packageName);
715                 return;
716             }
717             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
718                     "Updating IntentFilterVerificationInfo for package " + packageName
719                             +" verificationId:" + verificationId);
720
721             synchronized (mPackages) {
722                 if (verified) {
723                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
724                 } else {
725                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
726                 }
727                 scheduleWriteSettingsLocked();
728
729                 final int userId = ivs.getUserId();
730                 if (userId != UserHandle.USER_ALL) {
731                     final int userStatus =
732                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
733
734                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
735                     boolean needUpdate = false;
736
737                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
738                     // already been set by the User thru the Disambiguation dialog
739                     switch (userStatus) {
740                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
741                             if (verified) {
742                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
743                             } else {
744                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
745                             }
746                             needUpdate = true;
747                             break;
748
749                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
750                             if (verified) {
751                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
752                                 needUpdate = true;
753                             }
754                             break;
755
756                         default:
757                             // Nothing to do
758                     }
759
760                     if (needUpdate) {
761                         mSettings.updateIntentFilterVerificationStatusLPw(
762                                 packageName, updatedStatus, userId);
763                         scheduleWritePackageRestrictionsLocked(userId);
764                     }
765                 }
766             }
767         }
768
769         @Override
770         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
771                     ActivityIntentInfo filter, String packageName) {
772             if (!hasValidDomains(filter)) {
773                 return false;
774             }
775             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
776             if (ivs == null) {
777                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
778                         packageName);
779             }
780             if (DEBUG_DOMAIN_VERIFICATION) {
781                 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
782             }
783             ivs.addFilter(filter);
784             return true;
785         }
786
787         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
788                 int userId, int verificationId, String packageName) {
789             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
790                     verifierUid, userId, packageName);
791             ivs.setPendingState();
792             synchronized (mPackages) {
793                 mIntentFilterVerificationStates.append(verificationId, ivs);
794                 mCurrentIntentFilterVerifications.add(verificationId);
795             }
796             return ivs;
797         }
798     }
799
800     private static boolean hasValidDomains(ActivityIntentInfo filter) {
801         boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
802                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
803         if (!hasHTTPorHTTPS) {
804             return false;
805         }
806         return true;
807     }
808
809     private IntentFilterVerifier mIntentFilterVerifier;
810
811     // Set of pending broadcasts for aggregating enable/disable of components.
812     static class PendingPackageBroadcasts {
813         // for each user id, a map of <package name -> components within that package>
814         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
815
816         public PendingPackageBroadcasts() {
817             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
818         }
819
820         public ArrayList<String> get(int userId, String packageName) {
821             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822             return packages.get(packageName);
823         }
824
825         public void put(int userId, String packageName, ArrayList<String> components) {
826             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
827             packages.put(packageName, components);
828         }
829
830         public void remove(int userId, String packageName) {
831             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
832             if (packages != null) {
833                 packages.remove(packageName);
834             }
835         }
836
837         public void remove(int userId) {
838             mUidMap.remove(userId);
839         }
840
841         public int userIdCount() {
842             return mUidMap.size();
843         }
844
845         public int userIdAt(int n) {
846             return mUidMap.keyAt(n);
847         }
848
849         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
850             return mUidMap.get(userId);
851         }
852
853         public int size() {
854             // total number of pending broadcast entries across all userIds
855             int num = 0;
856             for (int i = 0; i< mUidMap.size(); i++) {
857                 num += mUidMap.valueAt(i).size();
858             }
859             return num;
860         }
861
862         public void clear() {
863             mUidMap.clear();
864         }
865
866         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
867             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
868             if (map == null) {
869                 map = new ArrayMap<String, ArrayList<String>>();
870                 mUidMap.put(userId, map);
871             }
872             return map;
873         }
874     }
875     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
876
877     // Service Connection to remote media container service to copy
878     // package uri's from external media onto secure containers
879     // or internal storage.
880     private IMediaContainerService mContainerService = null;
881
882     static final int SEND_PENDING_BROADCAST = 1;
883     static final int MCS_BOUND = 3;
884     static final int END_COPY = 4;
885     static final int INIT_COPY = 5;
886     static final int MCS_UNBIND = 6;
887     static final int START_CLEANING_PACKAGE = 7;
888     static final int FIND_INSTALL_LOC = 8;
889     static final int POST_INSTALL = 9;
890     static final int MCS_RECONNECT = 10;
891     static final int MCS_GIVE_UP = 11;
892     static final int UPDATED_MEDIA_STATUS = 12;
893     static final int WRITE_SETTINGS = 13;
894     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
895     static final int PACKAGE_VERIFIED = 15;
896     static final int CHECK_PENDING_VERIFICATION = 16;
897     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
898     static final int INTENT_FILTER_VERIFIED = 18;
899
900     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
901
902     // Delay time in millisecs
903     static final int BROADCAST_DELAY = 10 * 1000;
904
905     static UserManagerService sUserManager;
906
907     // Stores a list of users whose package restrictions file needs to be updated
908     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
909
910     final private DefaultContainerConnection mDefContainerConn =
911             new DefaultContainerConnection();
912     class DefaultContainerConnection implements ServiceConnection {
913         public void onServiceConnected(ComponentName name, IBinder service) {
914             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
915             IMediaContainerService imcs =
916                 IMediaContainerService.Stub.asInterface(service);
917             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
918         }
919
920         public void onServiceDisconnected(ComponentName name) {
921             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
922         }
923     }
924
925     // Recordkeeping of restore-after-install operations that are currently in flight
926     // between the Package Manager and the Backup Manager
927     class PostInstallData {
928         public InstallArgs args;
929         public PackageInstalledInfo res;
930
931         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
932             args = _a;
933             res = _r;
934         }
935     }
936
937     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
938     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
939
940     // XML tags for backup/restore of various bits of state
941     private static final String TAG_PREFERRED_BACKUP = "pa";
942     private static final String TAG_DEFAULT_APPS = "da";
943     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
944
945     final String mRequiredVerifierPackage;
946     final String mRequiredInstallerPackage;
947
948     private final PackageUsage mPackageUsage = new PackageUsage();
949
950     private class PackageUsage {
951         private static final int WRITE_INTERVAL
952             = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
953
954         private final Object mFileLock = new Object();
955         private final AtomicLong mLastWritten = new AtomicLong(0);
956         private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
957
958         private boolean mIsHistoricalPackageUsageAvailable = true;
959
960         boolean isHistoricalPackageUsageAvailable() {
961             return mIsHistoricalPackageUsageAvailable;
962         }
963
964         void write(boolean force) {
965             if (force) {
966                 writeInternal();
967                 return;
968             }
969             if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
970                 && !DEBUG_DEXOPT) {
971                 return;
972             }
973             if (mBackgroundWriteRunning.compareAndSet(false, true)) {
974                 new Thread("PackageUsage_DiskWriter") {
975                     @Override
976                     public void run() {
977                         try {
978                             writeInternal();
979                         } finally {
980                             mBackgroundWriteRunning.set(false);
981                         }
982                     }
983                 }.start();
984             }
985         }
986
987         private void writeInternal() {
988             synchronized (mPackages) {
989                 synchronized (mFileLock) {
990                     AtomicFile file = getFile();
991                     FileOutputStream f = null;
992                     try {
993                         f = file.startWrite();
994                         BufferedOutputStream out = new BufferedOutputStream(f);
995                         FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
996                         StringBuilder sb = new StringBuilder();
997                         for (PackageParser.Package pkg : mPackages.values()) {
998                             if (pkg.mLastPackageUsageTimeInMills == 0) {
999                                 continue;
1000                             }
1001                             sb.setLength(0);
1002                             sb.append(pkg.packageName);
1003                             sb.append(' ');
1004                             sb.append((long)pkg.mLastPackageUsageTimeInMills);
1005                             sb.append('\n');
1006                             out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1007                         }
1008                         out.flush();
1009                         file.finishWrite(f);
1010                     } catch (IOException e) {
1011                         if (f != null) {
1012                             file.failWrite(f);
1013                         }
1014                         Log.e(TAG, "Failed to write package usage times", e);
1015                     }
1016                 }
1017             }
1018             mLastWritten.set(SystemClock.elapsedRealtime());
1019         }
1020
1021         void readLP() {
1022             synchronized (mFileLock) {
1023                 AtomicFile file = getFile();
1024                 BufferedInputStream in = null;
1025                 try {
1026                     in = new BufferedInputStream(file.openRead());
1027                     StringBuffer sb = new StringBuffer();
1028                     while (true) {
1029                         String packageName = readToken(in, sb, ' ');
1030                         if (packageName == null) {
1031                             break;
1032                         }
1033                         String timeInMillisString = readToken(in, sb, '\n');
1034                         if (timeInMillisString == null) {
1035                             throw new IOException("Failed to find last usage time for package "
1036                                                   + packageName);
1037                         }
1038                         PackageParser.Package pkg = mPackages.get(packageName);
1039                         if (pkg == null) {
1040                             continue;
1041                         }
1042                         long timeInMillis;
1043                         try {
1044                             timeInMillis = Long.parseLong(timeInMillisString.toString());
1045                         } catch (NumberFormatException e) {
1046                             throw new IOException("Failed to parse " + timeInMillisString
1047                                                   + " as a long.", e);
1048                         }
1049                         pkg.mLastPackageUsageTimeInMills = timeInMillis;
1050                     }
1051                 } catch (FileNotFoundException expected) {
1052                     mIsHistoricalPackageUsageAvailable = false;
1053                 } catch (IOException e) {
1054                     Log.w(TAG, "Failed to read package usage times", e);
1055                 } finally {
1056                     IoUtils.closeQuietly(in);
1057                 }
1058             }
1059             mLastWritten.set(SystemClock.elapsedRealtime());
1060         }
1061
1062         private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1063                 throws IOException {
1064             sb.setLength(0);
1065             while (true) {
1066                 int ch = in.read();
1067                 if (ch == -1) {
1068                     if (sb.length() == 0) {
1069                         return null;
1070                     }
1071                     throw new IOException("Unexpected EOF");
1072                 }
1073                 if (ch == endOfToken) {
1074                     return sb.toString();
1075                 }
1076                 sb.append((char)ch);
1077             }
1078         }
1079
1080         private AtomicFile getFile() {
1081             File dataDir = Environment.getDataDirectory();
1082             File systemDir = new File(dataDir, "system");
1083             File fname = new File(systemDir, "package-usage.list");
1084             return new AtomicFile(fname);
1085         }
1086     }
1087
1088     class PackageHandler extends Handler {
1089         private boolean mBound = false;
1090         final ArrayList<HandlerParams> mPendingInstalls =
1091             new ArrayList<HandlerParams>();
1092
1093         private boolean connectToService() {
1094             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1095                     " DefaultContainerService");
1096             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1097             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1099                     Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1100                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1101                 mBound = true;
1102                 return true;
1103             }
1104             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105             return false;
1106         }
1107
1108         private void disconnectService() {
1109             mContainerService = null;
1110             mBound = false;
1111             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112             mContext.unbindService(mDefContainerConn);
1113             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114         }
1115
1116         PackageHandler(Looper looper) {
1117             super(looper);
1118         }
1119
1120         public void handleMessage(Message msg) {
1121             try {
1122                 doHandleMessage(msg);
1123             } finally {
1124                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125             }
1126         }
1127
1128         void doHandleMessage(Message msg) {
1129             switch (msg.what) {
1130                 case INIT_COPY: {
1131                     HandlerParams params = (HandlerParams) msg.obj;
1132                     int idx = mPendingInstalls.size();
1133                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1134                     // If a bind was already initiated we dont really
1135                     // need to do anything. The pending install
1136                     // will be processed later on.
1137                     if (!mBound) {
1138                         // If this is the only one pending we might
1139                         // have to bind to the service again.
1140                         if (!connectToService()) {
1141                             Slog.e(TAG, "Failed to bind to media container service");
1142                             params.serviceError();
1143                             return;
1144                         } else {
1145                             // Once we bind to the service, the first
1146                             // pending request will be processed.
1147                             mPendingInstalls.add(idx, params);
1148                         }
1149                     } else {
1150                         mPendingInstalls.add(idx, params);
1151                         // Already bound to the service. Just make
1152                         // sure we trigger off processing the first request.
1153                         if (idx == 0) {
1154                             mHandler.sendEmptyMessage(MCS_BOUND);
1155                         }
1156                     }
1157                     break;
1158                 }
1159                 case MCS_BOUND: {
1160                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1161                     if (msg.obj != null) {
1162                         mContainerService = (IMediaContainerService) msg.obj;
1163                     }
1164                     if (mContainerService == null) {
1165                         if (!mBound) {
1166                             // Something seriously wrong since we are not bound and we are not
1167                             // waiting for connection. Bail out.
1168                             Slog.e(TAG, "Cannot bind to media container service");
1169                             for (HandlerParams params : mPendingInstalls) {
1170                                 // Indicate service bind error
1171                                 params.serviceError();
1172                             }
1173                             mPendingInstalls.clear();
1174                         } else {
1175                             Slog.w(TAG, "Waiting to connect to media container service");
1176                         }
1177                     } else if (mPendingInstalls.size() > 0) {
1178                         HandlerParams params = mPendingInstalls.get(0);
1179                         if (params != null) {
1180                             if (params.startCopy()) {
1181                                 // We are done...  look for more work or to
1182                                 // go idle.
1183                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1184                                         "Checking for more work or unbind...");
1185                                 // Delete pending install
1186                                 if (mPendingInstalls.size() > 0) {
1187                                     mPendingInstalls.remove(0);
1188                                 }
1189                                 if (mPendingInstalls.size() == 0) {
1190                                     if (mBound) {
1191                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1192                                                 "Posting delayed MCS_UNBIND");
1193                                         removeMessages(MCS_UNBIND);
1194                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1195                                         // Unbind after a little delay, to avoid
1196                                         // continual thrashing.
1197                                         sendMessageDelayed(ubmsg, 10000);
1198                                     }
1199                                 } else {
1200                                     // There are more pending requests in queue.
1201                                     // Just post MCS_BOUND message to trigger processing
1202                                     // of next pending install.
1203                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                             "Posting MCS_BOUND for next work");
1205                                     mHandler.sendEmptyMessage(MCS_BOUND);
1206                                 }
1207                             }
1208                         }
1209                     } else {
1210                         // Should never happen ideally.
1211                         Slog.w(TAG, "Empty queue");
1212                     }
1213                     break;
1214                 }
1215                 case MCS_RECONNECT: {
1216                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1217                     if (mPendingInstalls.size() > 0) {
1218                         if (mBound) {
1219                             disconnectService();
1220                         }
1221                         if (!connectToService()) {
1222                             Slog.e(TAG, "Failed to bind to media container service");
1223                             for (HandlerParams params : mPendingInstalls) {
1224                                 // Indicate service bind error
1225                                 params.serviceError();
1226                             }
1227                             mPendingInstalls.clear();
1228                         }
1229                     }
1230                     break;
1231                 }
1232                 case MCS_UNBIND: {
1233                     // If there is no actual work left, then time to unbind.
1234                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1235
1236                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1237                         if (mBound) {
1238                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1239
1240                             disconnectService();
1241                         }
1242                     } else if (mPendingInstalls.size() > 0) {
1243                         // There are more pending requests in queue.
1244                         // Just post MCS_BOUND message to trigger processing
1245                         // of next pending install.
1246                         mHandler.sendEmptyMessage(MCS_BOUND);
1247                     }
1248
1249                     break;
1250                 }
1251                 case MCS_GIVE_UP: {
1252                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1253                     mPendingInstalls.remove(0);
1254                     break;
1255                 }
1256                 case SEND_PENDING_BROADCAST: {
1257                     String packages[];
1258                     ArrayList<String> components[];
1259                     int size = 0;
1260                     int uids[];
1261                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262                     synchronized (mPackages) {
1263                         if (mPendingBroadcasts == null) {
1264                             return;
1265                         }
1266                         size = mPendingBroadcasts.size();
1267                         if (size <= 0) {
1268                             // Nothing to be done. Just return
1269                             return;
1270                         }
1271                         packages = new String[size];
1272                         components = new ArrayList[size];
1273                         uids = new int[size];
1274                         int i = 0;  // filling out the above arrays
1275
1276                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1277                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1278                             Iterator<Map.Entry<String, ArrayList<String>>> it
1279                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1280                                             .entrySet().iterator();
1281                             while (it.hasNext() && i < size) {
1282                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1283                                 packages[i] = ent.getKey();
1284                                 components[i] = ent.getValue();
1285                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1286                                 uids[i] = (ps != null)
1287                                         ? UserHandle.getUid(packageUserId, ps.appId)
1288                                         : -1;
1289                                 i++;
1290                             }
1291                         }
1292                         size = i;
1293                         mPendingBroadcasts.clear();
1294                     }
1295                     // Send broadcasts
1296                     for (int i = 0; i < size; i++) {
1297                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1298                     }
1299                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300                     break;
1301                 }
1302                 case START_CLEANING_PACKAGE: {
1303                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1304                     final String packageName = (String)msg.obj;
1305                     final int userId = msg.arg1;
1306                     final boolean andCode = msg.arg2 != 0;
1307                     synchronized (mPackages) {
1308                         if (userId == UserHandle.USER_ALL) {
1309                             int[] users = sUserManager.getUserIds();
1310                             for (int user : users) {
1311                                 mSettings.addPackageToCleanLPw(
1312                                         new PackageCleanItem(user, packageName, andCode));
1313                             }
1314                         } else {
1315                             mSettings.addPackageToCleanLPw(
1316                                     new PackageCleanItem(userId, packageName, andCode));
1317                         }
1318                     }
1319                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                     startCleaningPackages();
1321                 } break;
1322                 case POST_INSTALL: {
1323                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1324                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1325                     mRunningInstalls.delete(msg.arg1);
1326                     boolean deleteOld = false;
1327
1328                     if (data != null) {
1329                         InstallArgs args = data.args;
1330                         PackageInstalledInfo res = data.res;
1331
1332                         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1333                             final String packageName = res.pkg.applicationInfo.packageName;
1334                             res.removedInfo.sendBroadcast(false, true, false);
1335                             Bundle extras = new Bundle(1);
1336                             extras.putInt(Intent.EXTRA_UID, res.uid);
1337
1338                             // Now that we successfully installed the package, grant runtime
1339                             // permissions if requested before broadcasting the install.
1340                             if ((args.installFlags
1341                                     & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1342                                 grantRequestedRuntimePermissions(res.pkg,
1343                                         args.user.getIdentifier());
1344                             }
1345
1346                             // Determine the set of users who are adding this
1347                             // package for the first time vs. those who are seeing
1348                             // an update.
1349                             int[] firstUsers;
1350                             int[] updateUsers = new int[0];
1351                             if (res.origUsers == null || res.origUsers.length == 0) {
1352                                 firstUsers = res.newUsers;
1353                             } else {
1354                                 firstUsers = new int[0];
1355                                 for (int i=0; i<res.newUsers.length; i++) {
1356                                     int user = res.newUsers[i];
1357                                     boolean isNew = true;
1358                                     for (int j=0; j<res.origUsers.length; j++) {
1359                                         if (res.origUsers[j] == user) {
1360                                             isNew = false;
1361                                             break;
1362                                         }
1363                                     }
1364                                     if (isNew) {
1365                                         int[] newFirst = new int[firstUsers.length+1];
1366                                         System.arraycopy(firstUsers, 0, newFirst, 0,
1367                                                 firstUsers.length);
1368                                         newFirst[firstUsers.length] = user;
1369                                         firstUsers = newFirst;
1370                                     } else {
1371                                         int[] newUpdate = new int[updateUsers.length+1];
1372                                         System.arraycopy(updateUsers, 0, newUpdate, 0,
1373                                                 updateUsers.length);
1374                                         newUpdate[updateUsers.length] = user;
1375                                         updateUsers = newUpdate;
1376                                     }
1377                                 }
1378                             }
1379                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                     packageName, extras, null, null, firstUsers);
1381                             final boolean update = res.removedInfo.removedPackage != null;
1382                             if (update) {
1383                                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1384                             }
1385                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1386                                     packageName, extras, null, null, updateUsers);
1387                             if (update) {
1388                                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1389                                         packageName, extras, null, null, updateUsers);
1390                                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1391                                         null, null, packageName, null, updateUsers);
1392
1393                                 // treat asec-hosted packages like removable media on upgrade
1394                                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1395                                     if (DEBUG_INSTALL) {
1396                                         Slog.i(TAG, "upgrading pkg " + res.pkg
1397                                                 + " is ASEC-hosted -> AVAILABLE");
1398                                     }
1399                                     int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1400                                     ArrayList<String> pkgList = new ArrayList<String>(1);
1401                                     pkgList.add(packageName);
1402                                     sendResourcesChangedBroadcast(true, true,
1403                                             pkgList,uidArray, null);
1404                                 }
1405                             }
1406                             if (res.removedInfo.args != null) {
1407                                 // Remove the replaced package's older resources safely now
1408                                 deleteOld = true;
1409                             }
1410
1411                             // If this app is a browser and it's newly-installed for some
1412                             // users, clear any default-browser state in those users
1413                             if (firstUsers.length > 0) {
1414                                 // the app's nature doesn't depend on the user, so we can just
1415                                 // check its browser nature in any user and generalize.
1416                                 if (packageIsBrowser(packageName, firstUsers[0])) {
1417                                     synchronized (mPackages) {
1418                                         for (int userId : firstUsers) {
1419                                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1420                                         }
1421                                     }
1422                                 }
1423                             }
1424                             // Log current value of "unknown sources" setting
1425                             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1426                                 getUnknownSourcesSettings());
1427                         }
1428                         // Force a gc to clear up things
1429                         Runtime.getRuntime().gc();
1430                         // We delete after a gc for applications  on sdcard.
1431                         if (deleteOld) {
1432                             synchronized (mInstallLock) {
1433                                 res.removedInfo.args.doPostDeleteLI(true);
1434                             }
1435                         }
1436                         if (args.observer != null) {
1437                             try {
1438                                 Bundle extras = extrasForInstallResult(res);
1439                                 args.observer.onPackageInstalled(res.name, res.returnCode,
1440                                         res.returnMsg, extras);
1441                             } catch (RemoteException e) {
1442                                 Slog.i(TAG, "Observer no longer exists.");
1443                             }
1444                         }
1445                     } else {
1446                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                     }
1448                 } break;
1449                 case UPDATED_MEDIA_STATUS: {
1450                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1451                     boolean reportStatus = msg.arg1 == 1;
1452                     boolean doGc = msg.arg2 == 1;
1453                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1454                     if (doGc) {
1455                         // Force a gc to clear up stale containers.
1456                         Runtime.getRuntime().gc();
1457                     }
1458                     if (msg.obj != null) {
1459                         @SuppressWarnings("unchecked")
1460                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1461                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1462                         // Unload containers
1463                         unloadAllContainers(args);
1464                     }
1465                     if (reportStatus) {
1466                         try {
1467                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1468                             PackageHelper.getMountService().finishMediaUpdate();
1469                         } catch (RemoteException e) {
1470                             Log.e(TAG, "MountService not running?");
1471                         }
1472                     }
1473                 } break;
1474                 case WRITE_SETTINGS: {
1475                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476                     synchronized (mPackages) {
1477                         removeMessages(WRITE_SETTINGS);
1478                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                         mSettings.writeLPr();
1480                         mDirtyUsers.clear();
1481                     }
1482                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                 } break;
1484                 case WRITE_PACKAGE_RESTRICTIONS: {
1485                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                     synchronized (mPackages) {
1487                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                         for (int userId : mDirtyUsers) {
1489                             mSettings.writePackageRestrictionsLPr(userId);
1490                         }
1491                         mDirtyUsers.clear();
1492                     }
1493                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                 } break;
1495                 case CHECK_PENDING_VERIFICATION: {
1496                     final int verificationId = msg.arg1;
1497                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                     if ((state != null) && !state.timeoutExtended()) {
1500                         final InstallArgs args = state.getInstallArgs();
1501                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                         Slog.i(TAG, "Verification timed out for " + originUri);
1504                         mPendingVerification.remove(verificationId);
1505
1506                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                             Slog.i(TAG, "Continuing with installation of " + originUri);
1510                             state.setVerifierResponse(Binder.getCallingUid(),
1511                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                             broadcastPackageVerified(verificationId, originUri,
1513                                     PackageManager.VERIFICATION_ALLOW,
1514                                     state.getInstallArgs().getUser());
1515                             try {
1516                                 ret = args.copyApk(mContainerService, true);
1517                             } catch (RemoteException e) {
1518                                 Slog.e(TAG, "Could not contact the ContainerService");
1519                             }
1520                         } else {
1521                             broadcastPackageVerified(verificationId, originUri,
1522                                     PackageManager.VERIFICATION_REJECT,
1523                                     state.getInstallArgs().getUser());
1524                         }
1525
1526                         processPendingInstall(args, ret);
1527                         mHandler.sendEmptyMessage(MCS_UNBIND);
1528                     }
1529                     break;
1530                 }
1531                 case PACKAGE_VERIFIED: {
1532                     final int verificationId = msg.arg1;
1533
1534                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1535                     if (state == null) {
1536                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1537                         break;
1538                     }
1539
1540                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1541
1542                     state.setVerifierResponse(response.callerUid, response.code);
1543
1544                     if (state.isVerificationComplete()) {
1545                         mPendingVerification.remove(verificationId);
1546
1547                         final InstallArgs args = state.getInstallArgs();
1548                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                         int ret;
1551                         if (state.isInstallAllowed()) {
1552                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1553                             broadcastPackageVerified(verificationId, originUri,
1554                                     response.code, state.getInstallArgs().getUser());
1555                             try {
1556                                 ret = args.copyApk(mContainerService, true);
1557                             } catch (RemoteException e) {
1558                                 Slog.e(TAG, "Could not contact the ContainerService");
1559                             }
1560                         } else {
1561                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1562                         }
1563
1564                         processPendingInstall(args, ret);
1565
1566                         mHandler.sendEmptyMessage(MCS_UNBIND);
1567                     }
1568
1569                     break;
1570                 }
1571                 case START_INTENT_FILTER_VERIFICATIONS: {
1572                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                             params.replacing, params.pkg);
1575                     break;
1576                 }
1577                 case INTENT_FILTER_VERIFIED: {
1578                     final int verificationId = msg.arg1;
1579
1580                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                             verificationId);
1582                     if (state == null) {
1583                         Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                 + verificationId + " received");
1585                         break;
1586                     }
1587
1588                     final int userId = state.getUserId();
1589
1590                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                             "Processing IntentFilter verification with token:"
1592                             + verificationId + " and userId:" + userId);
1593
1594                     final IntentFilterVerificationResponse response =
1595                             (IntentFilterVerificationResponse) msg.obj;
1596
1597                     state.setVerifierResponse(response.callerUid, response.code);
1598
1599                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                             "IntentFilter verification with token:" + verificationId
1601                             + " and userId:" + userId
1602                             + " is settings verifier response with response code:"
1603                             + response.code);
1604
1605                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                 + response.getFailedDomainsString());
1608                     }
1609
1610                     if (state.isVerificationComplete()) {
1611                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                     } else {
1613                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                 "IntentFilter verification with token:" + verificationId
1615                                 + " was not said to be complete");
1616                     }
1617
1618                     break;
1619                 }
1620             }
1621         }
1622     }
1623
1624     private StorageEventListener mStorageListener = new StorageEventListener() {
1625         @Override
1626         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1627             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1628                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1629                     final String volumeUuid = vol.getFsUuid();
1630
1631                     // Clean up any users or apps that were removed or recreated
1632                     // while this volume was missing
1633                     reconcileUsers(volumeUuid);
1634                     reconcileApps(volumeUuid);
1635
1636                     // Clean up any install sessions that expired or were
1637                     // cancelled while this volume was missing
1638                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
1639
1640                     loadPrivatePackages(vol);
1641
1642                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1643                     unloadPrivatePackages(vol);
1644                 }
1645             }
1646
1647             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1648                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1649                     updateExternalMediaStatus(true, false);
1650                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1651                     updateExternalMediaStatus(false, false);
1652                 }
1653             }
1654         }
1655
1656         @Override
1657         public void onVolumeForgotten(String fsUuid) {
1658             // Remove any apps installed on the forgotten volume
1659             synchronized (mPackages) {
1660                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1661                 for (PackageSetting ps : packages) {
1662                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1663                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1664                             UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1665                 }
1666
1667                 mSettings.writeLPr();
1668             }
1669         }
1670     };
1671
1672     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1673         if (userId >= UserHandle.USER_OWNER) {
1674             grantRequestedRuntimePermissionsForUser(pkg, userId);
1675         } else if (userId == UserHandle.USER_ALL) {
1676             for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1677                 grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1678             }
1679         }
1680
1681         // We could have touched GID membership, so flush out packages.list
1682         synchronized (mPackages) {
1683             mSettings.writePackageListLPr();
1684         }
1685     }
1686
1687     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1688         SettingBase sb = (SettingBase) pkg.mExtras;
1689         if (sb == null) {
1690             return;
1691         }
1692
1693         PermissionsState permissionsState = sb.getPermissionsState();
1694
1695         for (String permission : pkg.requestedPermissions) {
1696             BasePermission bp = mSettings.mPermissions.get(permission);
1697             if (bp != null && bp.isRuntime()) {
1698                 permissionsState.grantRuntimePermission(bp, userId);
1699             }
1700         }
1701     }
1702
1703     Bundle extrasForInstallResult(PackageInstalledInfo res) {
1704         Bundle extras = null;
1705         switch (res.returnCode) {
1706             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1707                 extras = new Bundle();
1708                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1709                         res.origPermission);
1710                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1711                         res.origPackage);
1712                 break;
1713             }
1714             case PackageManager.INSTALL_SUCCEEDED: {
1715                 extras = new Bundle();
1716                 extras.putBoolean(Intent.EXTRA_REPLACING,
1717                         res.removedInfo != null && res.removedInfo.removedPackage != null);
1718                 break;
1719             }
1720         }
1721         return extras;
1722     }
1723
1724     void scheduleWriteSettingsLocked() {
1725         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1726             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1727         }
1728     }
1729
1730     void scheduleWritePackageRestrictionsLocked(int userId) {
1731         if (!sUserManager.exists(userId)) return;
1732         mDirtyUsers.add(userId);
1733         if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1734             mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1735         }
1736     }
1737
1738     public static PackageManagerService main(Context context, Installer installer,
1739             boolean factoryTest, boolean onlyCore) {
1740         PackageManagerService m = new PackageManagerService(context, installer,
1741                 factoryTest, onlyCore);
1742         ServiceManager.addService("package", m);
1743         return m;
1744     }
1745
1746     static String[] splitString(String str, char sep) {
1747         int count = 1;
1748         int i = 0;
1749         while ((i=str.indexOf(sep, i)) >= 0) {
1750             count++;
1751             i++;
1752         }
1753
1754         String[] res = new String[count];
1755         i=0;
1756         count = 0;
1757         int lastI=0;
1758         while ((i=str.indexOf(sep, i)) >= 0) {
1759             res[count] = str.substring(lastI, i);
1760             count++;
1761             i++;
1762             lastI = i;
1763         }
1764         res[count] = str.substring(lastI, str.length());
1765         return res;
1766     }
1767
1768     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1769         DisplayManager displayManager = (DisplayManager) context.getSystemService(
1770                 Context.DISPLAY_SERVICE);
1771         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1772     }
1773
1774     public PackageManagerService(Context context, Installer installer,
1775             boolean factoryTest, boolean onlyCore) {
1776         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1777                 SystemClock.uptimeMillis());
1778
1779         if (mSdkVersion <= 0) {
1780             Slog.w(TAG, "**** ro.build.version.sdk not set!");
1781         }
1782
1783         mContext = context;
1784         mFactoryTest = factoryTest;
1785         mOnlyCore = onlyCore;
1786         mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1787         mMetrics = new DisplayMetrics();
1788         mSettings = new Settings(mPackages);
1789         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1790                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1791         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1792                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1793         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1794                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1796                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1797         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1798                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1799         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1800                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1801
1802         // TODO: add a property to control this?
1803         long dexOptLRUThresholdInMinutes;
1804         if (mLazyDexOpt) {
1805             dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1806         } else {
1807             dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1808         }
1809         mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1810
1811         String separateProcesses = SystemProperties.get("debug.separate_processes");
1812         if (separateProcesses != null && separateProcesses.length() > 0) {
1813             if ("*".equals(separateProcesses)) {
1814                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1815                 mSeparateProcesses = null;
1816                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1817             } else {
1818                 mDefParseFlags = 0;
1819                 mSeparateProcesses = separateProcesses.split(",");
1820                 Slog.w(TAG, "Running with debug.separate_processes: "
1821                         + separateProcesses);
1822             }
1823         } else {
1824             mDefParseFlags = 0;
1825             mSeparateProcesses = null;
1826         }
1827
1828         mInstaller = installer;
1829         mPackageDexOptimizer = new PackageDexOptimizer(this);
1830         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1831
1832         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1833                 FgThread.get().getLooper());
1834
1835         getDefaultDisplayMetrics(context, mMetrics);
1836
1837         SystemConfig systemConfig = SystemConfig.getInstance();
1838         mGlobalGids = systemConfig.getGlobalGids();
1839         mSystemPermissions = systemConfig.getSystemPermissions();
1840         mAvailableFeatures = systemConfig.getAvailableFeatures();
1841
1842         synchronized (mInstallLock) {
1843         // writer
1844         synchronized (mPackages) {
1845             mHandlerThread = new ServiceThread(TAG,
1846                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1847             mHandlerThread.start();
1848             mHandler = new PackageHandler(mHandlerThread.getLooper());
1849             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1850
1851             File dataDir = Environment.getDataDirectory();
1852             mAppDataDir = new File(dataDir, "data");
1853             mAppInstallDir = new File(dataDir, "app");
1854             mAppLib32InstallDir = new File(dataDir, "app-lib");
1855             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1856             mUserAppDataDir = new File(dataDir, "user");
1857             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1858
1859             sUserManager = new UserManagerService(context, this,
1860                     mInstallLock, mPackages);
1861
1862             // Propagate permission configuration in to package manager.
1863             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1864                     = systemConfig.getPermissions();
1865             for (int i=0; i<permConfig.size(); i++) {
1866                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1867                 BasePermission bp = mSettings.mPermissions.get(perm.name);
1868                 if (bp == null) {
1869                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1870                     mSettings.mPermissions.put(perm.name, bp);
1871                 }
1872                 if (perm.gids != null) {
1873                     bp.setGids(perm.gids, perm.perUser);
1874                 }
1875             }
1876
1877             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1878             for (int i=0; i<libConfig.size(); i++) {
1879                 mSharedLibraries.put(libConfig.keyAt(i),
1880                         new SharedLibraryEntry(libConfig.valueAt(i), null));
1881             }
1882
1883             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1884
1885             mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1886                     mSdkVersion, mOnlyCore);
1887
1888             String customResolverActivity = Resources.getSystem().getString(
1889                     R.string.config_customResolverActivity);
1890             if (TextUtils.isEmpty(customResolverActivity)) {
1891                 customResolverActivity = null;
1892             } else {
1893                 mCustomResolverComponentName = ComponentName.unflattenFromString(
1894                         customResolverActivity);
1895             }
1896
1897             long startTime = SystemClock.uptimeMillis();
1898
1899             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1900                     startTime);
1901
1902             // Set flag to monitor and not change apk file paths when
1903             // scanning install directories.
1904             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1905
1906             final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1907
1908             /**
1909              * Add everything in the in the boot class path to the
1910              * list of process files because dexopt will have been run
1911              * if necessary during zygote startup.
1912              */
1913             final String bootClassPath = System.getenv("BOOTCLASSPATH");
1914             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1915
1916             if (bootClassPath != null) {
1917                 String[] bootClassPathElements = splitString(bootClassPath, ':');
1918                 for (String element : bootClassPathElements) {
1919                     alreadyDexOpted.add(element);
1920                 }
1921             } else {
1922                 Slog.w(TAG, "No BOOTCLASSPATH found!");
1923             }
1924
1925             if (systemServerClassPath != null) {
1926                 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1927                 for (String element : systemServerClassPathElements) {
1928                     alreadyDexOpted.add(element);
1929                 }
1930             } else {
1931                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1932             }
1933
1934             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1935             final String[] dexCodeInstructionSets =
1936                     getDexCodeInstructionSets(
1937                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
1938
1939             /**
1940              * Ensure all external libraries have had dexopt run on them.
1941              */
1942             if (mSharedLibraries.size() > 0) {
1943                 // NOTE: For now, we're compiling these system "shared libraries"
1944                 // (and framework jars) into all available architectures. It's possible
1945                 // to compile them only when we come across an app that uses them (there's
1946                 // already logic for that in scanPackageLI) but that adds some complexity.
1947                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1948                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1949                         final String lib = libEntry.path;
1950                         if (lib == null) {
1951                             continue;
1952                         }
1953
1954                         try {
1955                             int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1956                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1957                                 alreadyDexOpted.add(lib);
1958                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1959                             }
1960                         } catch (FileNotFoundException e) {
1961                             Slog.w(TAG, "Library not found: " + lib);
1962                         } catch (IOException e) {
1963                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1964                                     + e.getMessage());
1965                         }
1966                     }
1967                 }
1968             }
1969
1970             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1971
1972             // Gross hack for now: we know this file doesn't contain any
1973             // code, so don't dexopt it to avoid the resulting log spew.
1974             alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1975
1976             // Gross hack for now: we know this file is only part of
1977             // the boot class path for art, so don't dexopt it to
1978             // avoid the resulting log spew.
1979             alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1980
1981             /**
1982              * There are a number of commands implemented in Java, which
1983              * we currently need to do the dexopt on so that they can be
1984              * run from a non-root shell.
1985              */
1986             String[] frameworkFiles = frameworkDir.list();
1987             if (frameworkFiles != null) {
1988                 // TODO: We could compile these only for the most preferred ABI. We should
1989                 // first double check that the dex files for these commands are not referenced
1990                 // by other system apps.
1991                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1992                     for (int i=0; i<frameworkFiles.length; i++) {
1993                         File libPath = new File(frameworkDir, frameworkFiles[i]);
1994                         String path = libPath.getPath();
1995                         // Skip the file if we already did it.
1996                         if (alreadyDexOpted.contains(path)) {
1997                             continue;
1998                         }
1999                         // Skip the file if it is not a type we want to dexopt.
2000                         if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2001                             continue;
2002                         }
2003                         try {
2004                             int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2005                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2006                                 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2007                             }
2008                         } catch (FileNotFoundException e) {
2009                             Slog.w(TAG, "Jar not found: " + path);
2010                         } catch (IOException e) {
2011                             Slog.w(TAG, "Exception reading jar: " + path, e);
2012                         }
2013                     }
2014                 }
2015             }
2016
2017             // Collect vendor overlay packages.
2018             // (Do this before scanning any apps.)
2019             // For security and version matching reason, only consider
2020             // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2021             File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2022             scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2023                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2024
2025             // Find base frameworks (resource packages without code).
2026             scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2027                     | PackageParser.PARSE_IS_SYSTEM_DIR
2028                     | PackageParser.PARSE_IS_PRIVILEGED,
2029                     scanFlags | SCAN_NO_DEX, 0);
2030
2031             // Collected privileged system packages.
2032             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2033             scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2034                     | PackageParser.PARSE_IS_SYSTEM_DIR
2035                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2036
2037             // Collect ordinary system packages.
2038             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2039             scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2040                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2041
2042             // Collect all vendor packages.
2043             File vendorAppDir = new File("/vendor/app");
2044             try {
2045                 vendorAppDir = vendorAppDir.getCanonicalFile();
2046             } catch (IOException e) {
2047                 // failed to look up canonical path, continue with original one
2048             }
2049             scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2050                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2051
2052             // Collect all OEM packages.
2053             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2054             scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2055                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2056
2057             if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2058             mInstaller.moveFiles();
2059
2060             // Prune any system packages that no longer exist.
2061             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2062             if (!mOnlyCore) {
2063                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2064                 while (psit.hasNext()) {
2065                     PackageSetting ps = psit.next();
2066
2067                     /*
2068                      * If this is not a system app, it can't be a
2069                      * disable system app.
2070                      */
2071                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2072                         continue;
2073                     }
2074
2075                     /*
2076                      * If the package is scanned, it's not erased.
2077                      */
2078                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2079                     if (scannedPkg != null) {
2080                         /*
2081                          * If the system app is both scanned and in the
2082                          * disabled packages list, then it must have been
2083                          * added via OTA. Remove it from the currently
2084                          * scanned package so the previously user-installed
2085                          * application can be scanned.
2086                          */
2087                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2088                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2089                                     + ps.name + "; removing system app.  Last known codePath="
2090                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2091                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2092                                     + scannedPkg.mVersionCode);
2093                             removePackageLI(ps, true);
2094                             mExpectingBetter.put(ps.name, ps.codePath);
2095                         }
2096
2097                         continue;
2098                     }
2099
2100                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                         psit.remove();
2102                         logCriticalInfo(Log.WARN, "System package " + ps.name
2103                                 + " no longer exists; wiping its data");
2104                         removeDataDirsLI(null, ps.name);
2105                     } else {
2106                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2107                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2108                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2109                         }
2110                     }
2111                 }
2112             }
2113
2114             //look for any incomplete package installations
2115             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2116             //clean up list
2117             for(int i = 0; i < deletePkgsList.size(); i++) {
2118                 //clean up here
2119                 cleanupInstallFailedPackage(deletePkgsList.get(i));
2120             }
2121             //delete tmp files
2122             deleteTempPackageFiles();
2123
2124             // Remove any shared userIDs that have no associated packages
2125             mSettings.pruneSharedUsersLPw();
2126
2127             if (!mOnlyCore) {
2128                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2129                         SystemClock.uptimeMillis());
2130                 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2131
2132                 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2133                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2134
2135                 /**
2136                  * Remove disable package settings for any updated system
2137                  * apps that were removed via an OTA. If they're not a
2138                  * previously-updated app, remove them completely.
2139                  * Otherwise, just revoke their system-level permissions.
2140                  */
2141                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2142                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2143                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2144
2145                     String msg;
2146                     if (deletedPkg == null) {
2147                         msg = "Updated system package " + deletedAppName
2148                                 + " no longer exists; wiping its data";
2149                         removeDataDirsLI(null, deletedAppName);
2150                     } else {
2151                         msg = "Updated system app + " + deletedAppName
2152                                 + " no longer present; removing system privileges for "
2153                                 + deletedAppName;
2154
2155                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2156
2157                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2158                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2159                     }
2160                     logCriticalInfo(Log.WARN, msg);
2161                 }
2162
2163                 /**
2164                  * Make sure all system apps that we expected to appear on
2165                  * the userdata partition actually showed up. If they never
2166                  * appeared, crawl back and revive the system version.
2167                  */
2168                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2169                     final String packageName = mExpectingBetter.keyAt(i);
2170                     if (!mPackages.containsKey(packageName)) {
2171                         final File scanFile = mExpectingBetter.valueAt(i);
2172
2173                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2174                                 + " but never showed up; reverting to system");
2175
2176                         final int reparseFlags;
2177                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2178                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2179                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2180                                     | PackageParser.PARSE_IS_PRIVILEGED;
2181                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2182                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2183                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2184                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2185                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2186                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2187                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2188                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2189                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2190                         } else {
2191                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2192                             continue;
2193                         }
2194
2195                         mSettings.enableSystemPackageLPw(packageName);
2196
2197                         try {
2198                             scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2199                         } catch (PackageManagerException e) {
2200                             Slog.e(TAG, "Failed to parse original system package: "
2201                                     + e.getMessage());
2202                         }
2203                     }
2204                 }
2205             }
2206             mExpectingBetter.clear();
2207
2208             // Now that we know all of the shared libraries, update all clients to have
2209             // the correct library paths.
2210             updateAllSharedLibrariesLPw();
2211
2212             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2213                 // NOTE: We ignore potential failures here during a system scan (like
2214                 // the rest of the commands above) because there's precious little we
2215                 // can do about it. A settings error is reported, though.
2216                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2217                         false /* force dexopt */, false /* defer dexopt */);
2218             }
2219
2220             // Now that we know all the packages we are keeping,
2221             // read and update their last usage times.
2222             mPackageUsage.readLP();
2223
2224             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2225                     SystemClock.uptimeMillis());
2226             Slog.i(TAG, "Time to scan packages: "
2227                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2228                     + " seconds");
2229
2230             // If the platform SDK has changed since the last time we booted,
2231             // we need to re-grant app permission to catch any new ones that
2232             // appear.  This is really a hack, and means that apps can in some
2233             // cases get permissions that the user didn't initially explicitly
2234             // allow...  it would be nice to have some better way to handle
2235             // this situation.
2236             final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2237                     != mSdkVersion;
2238             if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2239                     + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2240                     + "; regranting permissions for internal storage");
2241             mSettings.mInternalSdkPlatform = mSdkVersion;
2242
2243             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2244                     | (regrantPermissions
2245                             ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2246                             : 0));
2247
2248             // If this is the first boot, and it is a normal boot, then
2249             // we need to initialize the default preferred apps.
2250             if (!mRestoredSettings && !onlyCore) {
2251                 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2252                 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2253                 primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2254             }
2255
2256             // If this is first boot after an OTA, and a normal boot, then
2257             // we need to clear code cache directories.
2258             mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2259             if (mIsUpgrade && !onlyCore) {
2260                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2261                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2262                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2263                     deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2264                 }
2265                 mSettings.mFingerprint = Build.FINGERPRINT;
2266             }
2267
2268             checkDefaultBrowser();
2269
2270             // All the changes are done during package scanning.
2271             mSettings.updateInternalDatabaseVersion();
2272
2273             // can downgrade to reader
2274             mSettings.writeLPr();
2275
2276             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2277                     SystemClock.uptimeMillis());
2278
2279             mRequiredVerifierPackage = getRequiredVerifierLPr();
2280             mRequiredInstallerPackage = getRequiredInstallerLPr();
2281
2282             mInstallerService = new PackageInstallerService(context, this);
2283
2284             mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2285             mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2286                     mIntentFilterVerifierComponent);
2287
2288         } // synchronized (mPackages)
2289         } // synchronized (mInstallLock)
2290
2291         // Now after opening every single application zip, make sure they
2292         // are all flushed.  Not really needed, but keeps things nice and
2293         // tidy.
2294         Runtime.getRuntime().gc();
2295
2296         // Expose private service for system components to use.
2297         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2298     }
2299
2300     @Override
2301     public boolean isFirstBoot() {
2302         return !mRestoredSettings;
2303     }
2304
2305     @Override
2306     public boolean isOnlyCoreApps() {
2307         return mOnlyCore;
2308     }
2309
2310     @Override
2311     public boolean isUpgrade() {
2312         return mIsUpgrade;
2313     }
2314
2315     private String getRequiredVerifierLPr() {
2316         final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2317         final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2318                 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2319
2320         String requiredVerifier = null;
2321
2322         final int N = receivers.size();
2323         for (int i = 0; i < N; i++) {
2324             final ResolveInfo info = receivers.get(i);
2325
2326             if (info.activityInfo == null) {
2327                 continue;
2328             }
2329
2330             final String packageName = info.activityInfo.packageName;
2331
2332             if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2333                     packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2334                 continue;
2335             }
2336
2337             if (requiredVerifier != null) {
2338                 throw new RuntimeException("There can be only one required verifier");
2339             }
2340
2341             requiredVerifier = packageName;
2342         }
2343
2344         return requiredVerifier;
2345     }
2346
2347     private String getRequiredInstallerLPr() {
2348         Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2349         installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2350         installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2351
2352         final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2353                 PACKAGE_MIME_TYPE, 0, 0);
2354
2355         String requiredInstaller = null;
2356
2357         final int N = installers.size();
2358         for (int i = 0; i < N; i++) {
2359             final ResolveInfo info = installers.get(i);
2360             final String packageName = info.activityInfo.packageName;
2361
2362             if (!info.activityInfo.applicationInfo.isSystemApp()) {
2363                 continue;
2364             }
2365
2366             if (requiredInstaller != null) {
2367                 throw new RuntimeException("There must be one required installer");
2368             }
2369
2370             requiredInstaller = packageName;
2371         }
2372
2373         if (requiredInstaller == null) {
2374             throw new RuntimeException("There must be one required installer");
2375         }
2376
2377         return requiredInstaller;
2378     }
2379
2380     private ComponentName getIntentFilterVerifierComponentNameLPr() {
2381         final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2382         final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2383                 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2384
2385         ComponentName verifierComponentName = null;
2386
2387         int priority = -1000;
2388         final int N = receivers.size();
2389         for (int i = 0; i < N; i++) {
2390             final ResolveInfo info = receivers.get(i);
2391
2392             if (info.activityInfo == null) {
2393                 continue;
2394             }
2395
2396             final String packageName = info.activityInfo.packageName;
2397
2398             final PackageSetting ps = mSettings.mPackages.get(packageName);
2399             if (ps == null) {
2400                 continue;
2401             }
2402
2403             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2404                     packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2405                 continue;
2406             }
2407
2408             // Select the IntentFilterVerifier with the highest priority
2409             if (priority < info.priority) {
2410                 priority = info.priority;
2411                 verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2412                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2413                         + verifierComponentName + " with priority: " + info.priority);
2414             }
2415         }
2416
2417         return verifierComponentName;
2418     }
2419
2420     private void primeDomainVerificationsLPw(int userId) {
2421         if (DEBUG_DOMAIN_VERIFICATION) {
2422             Slog.d(TAG, "Priming domain verifications in user " + userId);
2423         }
2424
2425         SystemConfig systemConfig = SystemConfig.getInstance();
2426         ArraySet<String> packages = systemConfig.getLinkedApps();
2427         ArraySet<String> domains = new ArraySet<String>();
2428
2429         for (String packageName : packages) {
2430             PackageParser.Package pkg = mPackages.get(packageName);
2431             if (pkg != null) {
2432                 if (!pkg.isSystemApp()) {
2433                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2434                     continue;
2435                 }
2436
2437                 domains.clear();
2438                 for (PackageParser.Activity a : pkg.activities) {
2439                     for (ActivityIntentInfo filter : a.intents) {
2440                         if (hasValidDomains(filter)) {
2441                             domains.addAll(filter.getHostsList());
2442                         }
2443                     }
2444                 }
2445
2446                 if (domains.size() > 0) {
2447                     if (DEBUG_DOMAIN_VERIFICATION) {
2448                         Slog.v(TAG, "      + " + packageName);
2449                     }
2450                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2451                     // state w.r.t. the formal app-linkage "no verification attempted" state;
2452                     // and then 'always' in the per-user state actually used for intent resolution.
2453                     final IntentFilterVerificationInfo ivi;
2454                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2455                             new ArrayList<String>(domains));
2456                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2457                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2458                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2459                 } else {
2460                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2461                             + "' does not handle web links");
2462                 }
2463             } else {
2464                 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2465             }
2466         }
2467
2468         scheduleWritePackageRestrictionsLocked(userId);
2469         scheduleWriteSettingsLocked();
2470     }
2471
2472     private void applyFactoryDefaultBrowserLPw(int userId) {
2473         // The default browser app's package name is stored in a string resource,
2474         // with a product-specific overlay used for vendor customization.
2475         String browserPkg = mContext.getResources().getString(
2476                 com.android.internal.R.string.default_browser);
2477         if (!TextUtils.isEmpty(browserPkg)) {
2478             // non-empty string => required to be a known package
2479             PackageSetting ps = mSettings.mPackages.get(browserPkg);
2480             if (ps == null) {
2481                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2482                 browserPkg = null;
2483             } else {
2484                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2485             }
2486         }
2487
2488         // Nothing valid explicitly set? Make the factory-installed browser the explicit
2489         // default.  If there's more than one, just leave everything alone.
2490         if (browserPkg == null) {
2491             calculateDefaultBrowserLPw(userId);
2492         }
2493     }
2494
2495     private void calculateDefaultBrowserLPw(int userId) {
2496         List<String> allBrowsers = resolveAllBrowserApps(userId);
2497         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2498         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499     }
2500
2501     private List<String> resolveAllBrowserApps(int userId) {
2502         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2503         List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2504                 PackageManager.MATCH_ALL, userId);
2505
2506         final int count = list.size();
2507         List<String> result = new ArrayList<String>(count);
2508         for (int i=0; i<count; i++) {
2509             ResolveInfo info = list.get(i);
2510             if (info.activityInfo == null
2511                     || !info.handleAllWebDataURI
2512                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2513                     || result.contains(info.activityInfo.packageName)) {
2514                 continue;
2515             }
2516             result.add(info.activityInfo.packageName);
2517         }
2518
2519         return result;
2520     }
2521
2522     private boolean packageIsBrowser(String packageName, int userId) {
2523         List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2524                 PackageManager.MATCH_ALL, userId);
2525         final int N = list.size();
2526         for (int i = 0; i < N; i++) {
2527             ResolveInfo info = list.get(i);
2528             if (packageName.equals(info.activityInfo.packageName)) {
2529                 return true;
2530             }
2531         }
2532         return false;
2533     }
2534
2535     private void checkDefaultBrowser() {
2536         final int myUserId = UserHandle.myUserId();
2537         final String packageName = getDefaultBrowserPackageName(myUserId);
2538         if (packageName != null) {
2539             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2540             if (info == null) {
2541                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
2542                 synchronized (mPackages) {
2543                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2544                 }
2545             }
2546         }
2547     }
2548
2549     @Override
2550     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2551             throws RemoteException {
2552         try {
2553             return super.onTransact(code, data, reply, flags);
2554         } catch (RuntimeException e) {
2555             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2556                 Slog.wtf(TAG, "Package Manager Crash", e);
2557             }
2558             throw e;
2559         }
2560     }
2561
2562     void cleanupInstallFailedPackage(PackageSetting ps) {
2563         logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2564
2565         removeDataDirsLI(ps.volumeUuid, ps.name);
2566         if (ps.codePath != null) {
2567             if (ps.codePath.isDirectory()) {
2568                 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2569             } else {
2570                 ps.codePath.delete();
2571             }
2572         }
2573         if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2574             if (ps.resourcePath.isDirectory()) {
2575                 FileUtils.deleteContents(ps.resourcePath);
2576             }
2577             ps.resourcePath.delete();
2578         }
2579         mSettings.removePackageLPw(ps.name);
2580     }
2581
2582     static int[] appendInts(int[] cur, int[] add) {
2583         if (add == null) return cur;
2584         if (cur == null) return add;
2585         final int N = add.length;
2586         for (int i=0; i<N; i++) {
2587             cur = appendInt(cur, add[i]);
2588         }
2589         return cur;
2590     }
2591
2592     PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2593         if (!sUserManager.exists(userId)) return null;
2594         final PackageSetting ps = (PackageSetting) p.mExtras;
2595         if (ps == null) {
2596             return null;
2597         }
2598
2599         final PermissionsState permissionsState = ps.getPermissionsState();
2600
2601         final int[] gids = permissionsState.computeGids(userId);
2602         final Set<String> permissions = permissionsState.getPermissions(userId);
2603         final PackageUserState state = ps.readUserState(userId);
2604
2605         return PackageParser.generatePackageInfo(p, gids, flags,
2606                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2607     }
2608
2609     @Override
2610     public boolean isPackageFrozen(String packageName) {
2611         synchronized (mPackages) {
2612             final PackageSetting ps = mSettings.mPackages.get(packageName);
2613             if (ps != null) {
2614                 return ps.frozen;
2615             }
2616         }
2617         Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2618         return true;
2619     }
2620
2621     @Override
2622     public boolean isPackageAvailable(String packageName, int userId) {
2623         if (!sUserManager.exists(userId)) return false;
2624         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2625         synchronized (mPackages) {
2626             PackageParser.Package p = mPackages.get(packageName);
2627             if (p != null) {
2628                 final PackageSetting ps = (PackageSetting) p.mExtras;
2629                 if (ps != null) {
2630                     final PackageUserState state = ps.readUserState(userId);
2631                     if (state != null) {
2632                         return PackageParser.isAvailable(state);
2633                     }
2634                 }
2635             }
2636         }
2637         return false;
2638     }
2639
2640     @Override
2641     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2642         if (!sUserManager.exists(userId)) return null;
2643         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2644         // reader
2645         synchronized (mPackages) {
2646             PackageParser.Package p = mPackages.get(packageName);
2647             if (DEBUG_PACKAGE_INFO)
2648                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2649             if (p != null) {
2650                 return generatePackageInfo(p, flags, userId);
2651             }
2652             if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2653                 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2654             }
2655         }
2656         return null;
2657     }
2658
2659     @Override
2660     public String[] currentToCanonicalPackageNames(String[] names) {
2661         String[] out = new String[names.length];
2662         // reader
2663         synchronized (mPackages) {
2664             for (int i=names.length-1; i>=0; i--) {
2665                 PackageSetting ps = mSettings.mPackages.get(names[i]);
2666                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2667             }
2668         }
2669         return out;
2670     }
2671
2672     @Override
2673     public String[] canonicalToCurrentPackageNames(String[] names) {
2674         String[] out = new String[names.length];
2675         // reader
2676         synchronized (mPackages) {
2677             for (int i=names.length-1; i>=0; i--) {
2678                 String cur = mSettings.mRenamedPackages.get(names[i]);
2679                 out[i] = cur != null ? cur : names[i];
2680             }
2681         }
2682         return out;
2683     }
2684
2685     @Override
2686     public int getPackageUid(String packageName, int userId) {
2687         if (!sUserManager.exists(userId)) return -1;
2688         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2689
2690         // reader
2691         synchronized (mPackages) {
2692             PackageParser.Package p = mPackages.get(packageName);
2693             if(p != null) {
2694                 return UserHandle.getUid(userId, p.applicationInfo.uid);
2695             }
2696             PackageSetting ps = mSettings.mPackages.get(packageName);
2697             if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2698                 return -1;
2699             }
2700             p = ps.pkg;
2701             return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2702         }
2703     }
2704
2705     @Override
2706     public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2707         if (!sUserManager.exists(userId)) {
2708             return null;
2709         }
2710
2711         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2712                 "getPackageGids");
2713
2714         // reader
2715         synchronized (mPackages) {
2716             PackageParser.Package p = mPackages.get(packageName);
2717             if (DEBUG_PACKAGE_INFO) {
2718                 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2719             }
2720             if (p != null) {
2721                 PackageSetting ps = (PackageSetting) p.mExtras;
2722                 return ps.getPermissionsState().computeGids(userId);
2723             }
2724         }
2725
2726         return null;
2727     }
2728
2729     @Override
2730     public int getMountExternalMode(int uid) {
2731         if (Process.isIsolated(uid)) {
2732             return Zygote.MOUNT_EXTERNAL_NONE;
2733         } else {
2734             if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2735                 return Zygote.MOUNT_EXTERNAL_DEFAULT;
2736             } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2737                 return Zygote.MOUNT_EXTERNAL_WRITE;
2738             } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2739                 return Zygote.MOUNT_EXTERNAL_READ;
2740             } else {
2741                 return Zygote.MOUNT_EXTERNAL_DEFAULT;
2742             }
2743         }
2744     }
2745
2746     static PermissionInfo generatePermissionInfo(
2747             BasePermission bp, int flags) {
2748         if (bp.perm != null) {
2749             return PackageParser.generatePermissionInfo(bp.perm, flags);
2750         }
2751         PermissionInfo pi = new PermissionInfo();
2752         pi.name = bp.name;
2753         pi.packageName = bp.sourcePackage;
2754         pi.nonLocalizedLabel = bp.name;
2755         pi.protectionLevel = bp.protectionLevel;
2756         return pi;
2757     }
2758
2759     @Override
2760     public PermissionInfo getPermissionInfo(String name, int flags) {
2761         // reader
2762         synchronized (mPackages) {
2763             final BasePermission p = mSettings.mPermissions.get(name);
2764             if (p != null) {
2765                 return generatePermissionInfo(p, flags);
2766             }
2767             return null;
2768         }
2769     }
2770
2771     @Override
2772     public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2773         // reader
2774         synchronized (mPackages) {
2775             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2776             for (BasePermission p : mSettings.mPermissions.values()) {
2777                 if (group == null) {
2778                     if (p.perm == null || p.perm.info.group == null) {
2779                         out.add(generatePermissionInfo(p, flags));
2780                     }
2781                 } else {
2782                     if (p.perm != null && group.equals(p.perm.info.group)) {
2783                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2784                     }
2785                 }
2786             }
2787
2788             if (out.size() > 0) {
2789                 return out;
2790             }
2791             return mPermissionGroups.containsKey(group) ? out : null;
2792         }
2793     }
2794
2795     @Override
2796     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2797         // reader
2798         synchronized (mPackages) {
2799             return PackageParser.generatePermissionGroupInfo(
2800                     mPermissionGroups.get(name), flags);
2801         }
2802     }
2803
2804     @Override
2805     public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2806         // reader
2807         synchronized (mPackages) {
2808             final int N = mPermissionGroups.size();
2809             ArrayList<PermissionGroupInfo> out
2810                     = new ArrayList<PermissionGroupInfo>(N);
2811             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2812                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2813             }
2814             return out;
2815         }
2816     }
2817
2818     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2819             int userId) {
2820         if (!sUserManager.exists(userId)) return null;
2821         PackageSetting ps = mSettings.mPackages.get(packageName);
2822         if (ps != null) {
2823             if (ps.pkg == null) {
2824                 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2825                         flags, userId);
2826                 if (pInfo != null) {
2827                     return pInfo.applicationInfo;
2828                 }
2829                 return null;
2830             }
2831             return PackageParser.generateApplicationInfo(ps.pkg, flags,
2832                     ps.readUserState(userId), userId);
2833         }
2834         return null;
2835     }
2836
2837     private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2838             int userId) {
2839         if (!sUserManager.exists(userId)) return null;
2840         PackageSetting ps = mSettings.mPackages.get(packageName);
2841         if (ps != null) {
2842             PackageParser.Package pkg = ps.pkg;
2843             if (pkg == null) {
2844                 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2845                     return null;
2846                 }
2847                 // Only data remains, so we aren't worried about code paths
2848                 pkg = new PackageParser.Package(packageName);
2849                 pkg.applicationInfo.packageName = packageName;
2850                 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2851                 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2852                 pkg.applicationInfo.dataDir = Environment
2853                         .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2854                         .getAbsolutePath();
2855                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2856                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2857             }
2858             return generatePackageInfo(pkg, flags, userId);
2859         }
2860         return null;
2861     }
2862
2863     @Override
2864     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2865         if (!sUserManager.exists(userId)) return null;
2866         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2867         // writer
2868         synchronized (mPackages) {
2869             PackageParser.Package p = mPackages.get(packageName);
2870             if (DEBUG_PACKAGE_INFO) Log.v(
2871                     TAG, "getApplicationInfo " + packageName
2872                     + ": " + p);
2873             if (p != null) {
2874                 PackageSetting ps = mSettings.mPackages.get(packageName);
2875                 if (ps == null) return null;
2876                 // Note: isEnabledLP() does not apply here - always return info
2877                 return PackageParser.generateApplicationInfo(
2878                         p, flags, ps.readUserState(userId), userId);
2879             }
2880             if ("android".equals(packageName)||"system".equals(packageName)) {
2881                 return mAndroidApplication;
2882             }
2883             if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2884                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2885             }
2886         }
2887         return null;
2888     }
2889
2890     @Override
2891     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2892             final IPackageDataObserver observer) {
2893         mContext.enforceCallingOrSelfPermission(
2894                 android.Manifest.permission.CLEAR_APP_CACHE, null);
2895         // Queue up an async operation since clearing cache may take a little while.
2896         mHandler.post(new Runnable() {
2897             public void run() {
2898                 mHandler.removeCallbacks(this);
2899                 int retCode = -1;
2900                 synchronized (mInstallLock) {
2901                     retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2902                     if (retCode < 0) {
2903                         Slog.w(TAG, "Couldn't clear application caches");
2904                     }
2905                 }
2906                 if (observer != null) {
2907                     try {
2908                         observer.onRemoveCompleted(null, (retCode >= 0));
2909                     } catch (RemoteException e) {
2910                         Slog.w(TAG, "RemoveException when invoking call back");
2911                     }
2912                 }
2913             }
2914         });
2915     }
2916
2917     @Override
2918     public void freeStorage(final String volumeUuid, final long freeStorageSize,
2919             final IntentSender pi) {
2920         mContext.enforceCallingOrSelfPermission(
2921                 android.Manifest.permission.CLEAR_APP_CACHE, null);
2922         // Queue up an async operation since clearing cache may take a little while.
2923         mHandler.post(new Runnable() {
2924             public void run() {
2925                 mHandler.removeCallbacks(this);
2926                 int retCode = -1;
2927                 synchronized (mInstallLock) {
2928                     retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2929                     if (retCode < 0) {
2930                         Slog.w(TAG, "Couldn't clear application caches");
2931                     }
2932                 }
2933                 if(pi != null) {
2934                     try {
2935                         // Callback via pending intent
2936                         int code = (retCode >= 0) ? 1 : 0;
2937                         pi.sendIntent(null, code, null,
2938                                 null, null);
2939                     } catch (SendIntentException e1) {
2940                         Slog.i(TAG, "Failed to send pending intent");
2941                     }
2942                 }
2943             }
2944         });
2945     }
2946
2947     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2948         synchronized (mInstallLock) {
2949             if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2950                 throw new IOException("Failed to free enough space");
2951             }
2952         }
2953     }
2954
2955     @Override
2956     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2957         if (!sUserManager.exists(userId)) return null;
2958         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2959         synchronized (mPackages) {
2960             PackageParser.Activity a = mActivities.mActivities.get(component);
2961
2962             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2963             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2964                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2965                 if (ps == null) return null;
2966                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2967                         userId);
2968             }
2969             if (mResolveComponentName.equals(component)) {
2970                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
2971                         new PackageUserState(), userId);
2972             }
2973         }
2974         return null;
2975     }
2976
2977     @Override
2978     public boolean activitySupportsIntent(ComponentName component, Intent intent,
2979             String resolvedType) {
2980         synchronized (mPackages) {
2981             PackageParser.Activity a = mActivities.mActivities.get(component);
2982             if (a == null) {
2983                 return false;
2984             }
2985             for (int i=0; i<a.intents.size(); i++) {
2986                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2987                         intent.getData(), intent.getCategories(), TAG) >= 0) {
2988                     return true;
2989                 }
2990             }
2991             return false;
2992         }
2993     }
2994
2995     @Override
2996     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2997         if (!sUserManager.exists(userId)) return null;
2998         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2999         synchronized (mPackages) {
3000             PackageParser.Activity a = mReceivers.mActivities.get(component);
3001             if (DEBUG_PACKAGE_INFO) Log.v(
3002                 TAG, "getReceiverInfo " + component + ": " + a);
3003             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3004                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3005                 if (ps == null) return null;
3006                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3007                         userId);
3008             }
3009         }
3010         return null;
3011     }
3012
3013     @Override
3014     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3015         if (!sUserManager.exists(userId)) return null;
3016         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3017         synchronized (mPackages) {
3018             PackageParser.Service s = mServices.mServices.get(component);
3019             if (DEBUG_PACKAGE_INFO) Log.v(
3020                 TAG, "getServiceInfo " + component + ": " + s);
3021             if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3022                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3023                 if (ps == null) return null;
3024                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3025                         userId);
3026             }
3027         }
3028         return null;
3029     }
3030
3031     @Override
3032     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3033         if (!sUserManager.exists(userId)) return null;
3034         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3035         synchronized (mPackages) {
3036             PackageParser.Provider p = mProviders.mProviders.get(component);
3037             if (DEBUG_PACKAGE_INFO) Log.v(
3038                 TAG, "getProviderInfo " + component + ": " + p);
3039             if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3040                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3041                 if (ps == null) return null;
3042                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3043                         userId);
3044             }
3045         }
3046         return null;
3047     }
3048
3049     @Override
3050     public String[] getSystemSharedLibraryNames() {
3051         Set<String> libSet;
3052         synchronized (mPackages) {
3053             libSet = mSharedLibraries.keySet();
3054             int size = libSet.size();
3055             if (size > 0) {
3056                 String[] libs = new String[size];
3057                 libSet.toArray(libs);
3058                 return libs;
3059             }
3060         }
3061         return null;
3062     }
3063
3064     /**
3065      * @hide
3066      */
3067     PackageParser.Package findSharedNonSystemLibrary(String libName) {
3068         synchronized (mPackages) {
3069             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3070             if (lib != null && lib.apk != null) {
3071                 return mPackages.get(lib.apk);
3072             }
3073         }
3074         return null;
3075     }
3076
3077     @Override
3078     public FeatureInfo[] getSystemAvailableFeatures() {
3079         Collection<FeatureInfo> featSet;
3080         synchronized (mPackages) {
3081             featSet = mAvailableFeatures.values();
3082             int size = featSet.size();
3083             if (size > 0) {
3084                 FeatureInfo[] features = new FeatureInfo[size+1];
3085                 featSet.toArray(features);
3086                 FeatureInfo fi = new FeatureInfo();
3087                 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3088                         FeatureInfo.GL_ES_VERSION_UNDEFINED);
3089                 features[size] = fi;
3090                 return features;
3091             }
3092         }
3093         return null;
3094     }
3095
3096     @Override
3097     public boolean hasSystemFeature(String name) {
3098         synchronized (mPackages) {
3099             return mAvailableFeatures.containsKey(name);
3100         }
3101     }
3102
3103     private void checkValidCaller(int uid, int userId) {
3104         if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3105             return;
3106
3107         throw new SecurityException("Caller uid=" + uid
3108                 + " is not privileged to communicate with user=" + userId);
3109     }
3110
3111     @Override
3112     public int checkPermission(String permName, String pkgName, int userId) {
3113         if (!sUserManager.exists(userId)) {
3114             return PackageManager.PERMISSION_DENIED;
3115         }
3116
3117         synchronized (mPackages) {
3118             final PackageParser.Package p = mPackages.get(pkgName);
3119             if (p != null && p.mExtras != null) {
3120                 final PackageSetting ps = (PackageSetting) p.mExtras;
3121                 if (ps.getPermissionsState().hasPermission(permName, userId)) {
3122                     return PackageManager.PERMISSION_GRANTED;
3123                 }
3124             }
3125         }
3126
3127         return PackageManager.PERMISSION_DENIED;
3128     }
3129
3130     @Override
3131     public int checkUidPermission(String permName, int uid) {
3132         final int userId = UserHandle.getUserId(uid);
3133
3134         if (!sUserManager.exists(userId)) {
3135             return PackageManager.PERMISSION_DENIED;
3136         }
3137
3138         synchronized (mPackages) {
3139             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3140             if (obj != null) {
3141                 final SettingBase ps = (SettingBase) obj;
3142                 if (ps.getPermissionsState().hasPermission(permName, userId)) {
3143                     return PackageManager.PERMISSION_GRANTED;
3144                 }
3145             } else {
3146                 ArraySet<String> perms = mSystemPermissions.get(uid);
3147                 if (perms != null && perms.contains(permName)) {
3148                     return PackageManager.PERMISSION_GRANTED;
3149                 }
3150             }
3151         }
3152
3153         return PackageManager.PERMISSION_DENIED;
3154     }
3155
3156     @Override
3157     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3158         if (UserHandle.getCallingUserId() != userId) {
3159             mContext.enforceCallingPermission(
3160                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3161                     "isPermissionRevokedByPolicy for user " + userId);
3162         }
3163
3164         if (checkPermission(permission, packageName, userId)
3165                 == PackageManager.PERMISSION_GRANTED) {
3166             return false;
3167         }
3168
3169         final long identity = Binder.clearCallingIdentity();
3170         try {
3171             final int flags = getPermissionFlags(permission, packageName, userId);
3172             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3173         } finally {
3174             Binder.restoreCallingIdentity(identity);
3175         }
3176     }
3177
3178     /**
3179      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3180      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3181      * @param checkShell TODO(yamasani):
3182      * @param message the message to log on security exception
3183      */
3184     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3185             boolean checkShell, String message) {
3186         if (userId < 0) {
3187             throw new IllegalArgumentException("Invalid userId " + userId);
3188         }
3189         if (checkShell) {
3190             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3191         }
3192         if (userId == UserHandle.getUserId(callingUid)) return;
3193         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3194             if (requireFullPermission) {
3195                 mContext.enforceCallingOrSelfPermission(
3196                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3197             } else {
3198                 try {
3199                     mContext.enforceCallingOrSelfPermission(
3200                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3201                 } catch (SecurityException se) {
3202                     mContext.enforceCallingOrSelfPermission(
3203                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3204                 }
3205             }
3206         }
3207     }
3208
3209     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3210         if (callingUid == Process.SHELL_UID) {
3211             if (userHandle >= 0
3212                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3213                 throw new SecurityException("Shell does not have permission to access user "
3214                         + userHandle);
3215             } else if (userHandle < 0) {
3216                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3217                         + Debug.getCallers(3));
3218             }
3219         }
3220     }
3221
3222     private BasePermission findPermissionTreeLP(String permName) {
3223         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3224             if (permName.startsWith(bp.name) &&
3225                     permName.length() > bp.name.length() &&
3226                     permName.charAt(bp.name.length()) == '.') {
3227                 return bp;
3228             }
3229         }
3230         return null;
3231     }
3232
3233     private BasePermission checkPermissionTreeLP(String permName) {
3234         if (permName != null) {
3235             BasePermission bp = findPermissionTreeLP(permName);
3236             if (bp != null) {
3237                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3238                     return bp;
3239                 }
3240                 throw new SecurityException("Calling uid "
3241                         + Binder.getCallingUid()
3242                         + " is not allowed to add to permission tree "
3243                         + bp.name + " owned by uid " + bp.uid);
3244             }
3245         }
3246         throw new SecurityException("No permission tree found for " + permName);
3247     }
3248
3249     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3250         if (s1 == null) {
3251             return s2 == null;
3252         }
3253         if (s2 == null) {
3254             return false;
3255         }
3256         if (s1.getClass() != s2.getClass()) {
3257             return false;
3258         }
3259         return s1.equals(s2);
3260     }
3261
3262     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3263         if (pi1.icon != pi2.icon) return false;
3264         if (pi1.logo != pi2.logo) return false;
3265         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3266         if (!compareStrings(pi1.name, pi2.name)) return false;
3267         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3268         // We'll take care of setting this one.
3269         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3270         // These are not currently stored in settings.
3271         //if (!compareStrings(pi1.group, pi2.group)) return false;
3272         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3273         //if (pi1.labelRes != pi2.labelRes) return false;
3274         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3275         return true;
3276     }
3277
3278     int permissionInfoFootprint(PermissionInfo info) {
3279         int size = info.name.length();
3280         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3281         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3282         return size;
3283     }
3284
3285     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3286         int size = 0;
3287         for (BasePermission perm : mSettings.mPermissions.values()) {
3288             if (perm.uid == tree.uid) {
3289                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3290             }
3291         }
3292         return size;
3293     }
3294
3295     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3296         // We calculate the max size of permissions defined by this uid and throw
3297         // if that plus the size of 'info' would exceed our stated maximum.
3298         if (tree.uid != Process.SYSTEM_UID) {
3299             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3300             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3301                 throw new SecurityException("Permission tree size cap exceeded");
3302             }
3303         }
3304     }
3305
3306     boolean addPermissionLocked(PermissionInfo info, boolean async) {
3307         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3308             throw new SecurityException("Label must be specified in permission");
3309         }
3310         BasePermission tree = checkPermissionTreeLP(info.name);
3311         BasePermission bp = mSettings.mPermissions.get(info.name);
3312         boolean added = bp == null;
3313         boolean changed = true;
3314         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3315         if (added) {
3316             enforcePermissionCapLocked(info, tree);
3317             bp = new BasePermission(info.name, tree.sourcePackage,
3318                     BasePermission.TYPE_DYNAMIC);
3319         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3320             throw new SecurityException(
3321                     "Not allowed to modify non-dynamic permission "
3322                     + info.name);
3323         } else {
3324             if (bp.protectionLevel == fixedLevel
3325                     && bp.perm.owner.equals(tree.perm.owner)
3326                     && bp.uid == tree.uid
3327                     && comparePermissionInfos(bp.perm.info, info)) {
3328                 changed = false;
3329             }
3330         }
3331         bp.protectionLevel = fixedLevel;
3332         info = new PermissionInfo(info);
3333         info.protectionLevel = fixedLevel;
3334         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3335         bp.perm.info.packageName = tree.perm.info.packageName;
3336         bp.uid = tree.uid;
3337         if (added) {
3338             mSettings.mPermissions.put(info.name, bp);
3339         }
3340         if (changed) {
3341             if (!async) {
3342                 mSettings.writeLPr();
3343             } else {
3344                 scheduleWriteSettingsLocked();
3345             }
3346         }
3347         return added;
3348     }
3349
3350     @Override
3351     public boolean addPermission(PermissionInfo info) {
3352         synchronized (mPackages) {
3353             return addPermissionLocked(info, false);
3354         }
3355     }
3356
3357     @Override
3358     public boolean addPermissionAsync(PermissionInfo info) {
3359         synchronized (mPackages) {
3360             return addPermissionLocked(info, true);
3361         }
3362     }
3363
3364     @Override
3365     public void removePermission(String name) {
3366         synchronized (mPackages) {
3367             checkPermissionTreeLP(name);
3368             BasePermission bp = mSettings.mPermissions.get(name);
3369             if (bp != null) {
3370                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
3371                     throw new SecurityException(
3372                             "Not allowed to modify non-dynamic permission "
3373                             + name);
3374                 }
3375                 mSettings.mPermissions.remove(name);
3376                 mSettings.writeLPr();
3377             }
3378         }
3379     }
3380
3381     private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3382             BasePermission bp) {
3383         int index = pkg.requestedPermissions.indexOf(bp.name);
3384         if (index == -1) {
3385             throw new SecurityException("Package " + pkg.packageName
3386                     + " has not requested permission " + bp.name);
3387         }
3388         if (!bp.isRuntime()) {
3389             throw new SecurityException("Permission " + bp.name
3390                     + " is not a changeable permission type");
3391         }
3392     }
3393
3394     @Override
3395     public void grantRuntimePermission(String packageName, String name, final int userId) {
3396         if (!sUserManager.exists(userId)) {
3397             Log.e(TAG, "No such user:" + userId);
3398             return;
3399         }
3400
3401         mContext.enforceCallingOrSelfPermission(
3402                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3403                 "grantRuntimePermission");
3404
3405         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3406                 "grantRuntimePermission");
3407
3408         final int uid;
3409         final SettingBase sb;
3410
3411         synchronized (mPackages) {
3412             final PackageParser.Package pkg = mPackages.get(packageName);
3413             if (pkg == null) {
3414                 throw new IllegalArgumentException("Unknown package: " + packageName);
3415             }
3416
3417             final BasePermission bp = mSettings.mPermissions.get(name);
3418             if (bp == null) {
3419                 throw new IllegalArgumentException("Unknown permission: " + name);
3420             }
3421
3422             enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3423
3424             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3425             sb = (SettingBase) pkg.mExtras;
3426             if (sb == null) {
3427                 throw new IllegalArgumentException("Unknown package: " + packageName);
3428             }
3429
3430             final PermissionsState permissionsState = sb.getPermissionsState();
3431
3432             final int flags = permissionsState.getPermissionFlags(name, userId);
3433             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3434                 throw new SecurityException("Cannot grant system fixed permission: "
3435                         + name + " for package: " + packageName);
3436             }
3437
3438             final int result = permissionsState.grantRuntimePermission(bp, userId);
3439             switch (result) {
3440                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3441                     return;
3442                 }
3443
3444                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3445                     mHandler.post(new Runnable() {
3446                         @Override
3447                         public void run() {
3448                             killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3449                         }
3450                     });
3451                 } break;
3452             }
3453
3454             mOnPermissionChangeListeners.onPermissionsChanged(uid);
3455
3456             // Not critical if that is lost - app has to request again.
3457             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3458         }
3459
3460         // Only need to do this if user is initialized. Otherwise it's a new user
3461         // and there are no processes running as the user yet and there's no need
3462         // to make an expensive call to remount processes for the changed permissions.
3463         if (READ_EXTERNAL_STORAGE.equals(name)
3464                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
3465             final long token = Binder.clearCallingIdentity();
3466             try {
3467                 if (sUserManager.isInitialized(userId)) {
3468                     final StorageManager storage = mContext.getSystemService(StorageManager.class);
3469                     storage.remountUid(uid);
3470                 }
3471             } finally {
3472                 Binder.restoreCallingIdentity(token);
3473             }
3474         }
3475     }
3476
3477     @Override
3478     public void revokeRuntimePermission(String packageName, String name, int userId) {
3479         if (!sUserManager.exists(userId)) {
3480             Log.e(TAG, "No such user:" + userId);
3481             return;
3482         }
3483
3484         mContext.enforceCallingOrSelfPermission(
3485                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3486                 "revokeRuntimePermission");
3487
3488         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3489                 "revokeRuntimePermission");
3490
3491         final SettingBase sb;
3492
3493         synchronized (mPackages) {
3494             final PackageParser.Package pkg = mPackages.get(packageName);
3495             if (pkg == null) {
3496                 throw new IllegalArgumentException("Unknown package: " + packageName);
3497             }
3498
3499             final BasePermission bp = mSettings.mPermissions.get(name);
3500             if (bp == null) {
3501                 throw new IllegalArgumentException("Unknown permission: " + name);
3502             }
3503
3504             enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3505
3506             sb = (SettingBase) pkg.mExtras;
3507             if (sb == null) {
3508                 throw new IllegalArgumentException("Unknown package: " + packageName);
3509             }
3510
3511             final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513             final int flags = permissionsState.getPermissionFlags(name, userId);
3514             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                 throw new SecurityException("Cannot revoke system fixed permission: "
3516                         + name + " for package: " + packageName);
3517             }
3518
3519             if (permissionsState.revokeRuntimePermission(bp, userId) ==
3520                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
3521                 return;
3522             }
3523
3524             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3525
3526             // Critical, after this call app should never have the permission.
3527             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3528         }
3529
3530         killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3531     }
3532
3533     @Override
3534     public void resetRuntimePermissions() {
3535         mContext.enforceCallingOrSelfPermission(
3536                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3537                 "revokeRuntimePermission");
3538
3539         int callingUid = Binder.getCallingUid();
3540         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3541             mContext.enforceCallingOrSelfPermission(
3542                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3543                     "resetRuntimePermissions");
3544         }
3545
3546         final int[] userIds;
3547
3548         synchronized (mPackages) {
3549             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3550             final int userCount = UserManagerService.getInstance().getUserIds().length;
3551             userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3552         }
3553
3554         for (int userId : userIds) {
3555             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3556         }
3557     }
3558
3559     @Override
3560     public int getPermissionFlags(String name, String packageName, int userId) {
3561         if (!sUserManager.exists(userId)) {
3562             return 0;
3563         }
3564
3565         mContext.enforceCallingOrSelfPermission(
3566                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3567                 "getPermissionFlags");
3568
3569         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3570                 "getPermissionFlags");
3571
3572         synchronized (mPackages) {
3573             final PackageParser.Package pkg = mPackages.get(packageName);
3574             if (pkg == null) {
3575                 throw new IllegalArgumentException("Unknown package: " + packageName);
3576             }
3577
3578             final BasePermission bp = mSettings.mPermissions.get(name);
3579             if (bp == null) {
3580                 throw new IllegalArgumentException("Unknown permission: " + name);
3581             }
3582
3583             SettingBase sb = (SettingBase) pkg.mExtras;
3584             if (sb == null) {
3585                 throw new IllegalArgumentException("Unknown package: " + packageName);
3586             }
3587
3588             PermissionsState permissionsState = sb.getPermissionsState();
3589             return permissionsState.getPermissionFlags(name, userId);
3590         }
3591     }
3592
3593     @Override
3594     public void updatePermissionFlags(String name, String packageName, int flagMask,
3595             int flagValues, int userId) {
3596         if (!sUserManager.exists(userId)) {
3597             return;
3598         }
3599
3600         mContext.enforceCallingOrSelfPermission(
3601                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3602                 "updatePermissionFlags");
3603
3604         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3605                 "updatePermissionFlags");
3606
3607         // Only the system can change system fixed flags.
3608         if (getCallingUid() != Process.SYSTEM_UID) {
3609             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611         }
3612
3613         synchronized (mPackages) {
3614             final PackageParser.Package pkg = mPackages.get(packageName);
3615             if (pkg == null) {
3616                 throw new IllegalArgumentException("Unknown package: " + packageName);
3617             }
3618
3619             final BasePermission bp = mSettings.mPermissions.get(name);
3620             if (bp == null) {
3621                 throw new IllegalArgumentException("Unknown permission: " + name);
3622             }
3623
3624             SettingBase sb = (SettingBase) pkg.mExtras;
3625             if (sb == null) {
3626                 throw new IllegalArgumentException("Unknown package: " + packageName);
3627             }
3628
3629             PermissionsState permissionsState = sb.getPermissionsState();
3630
3631             // Only the package manager can change flags for system component permissions.
3632             final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3633             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3634                 return;
3635             }
3636
3637             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3638
3639             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3640                 // Install and runtime permissions are stored in different places,
3641                 // so figure out what permission changed and persist the change.
3642                 if (permissionsState.getInstallPermissionState(name) != null) {
3643                     scheduleWriteSettingsLocked();
3644                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3645                         || hadState) {
3646                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3647                 }
3648             }
3649         }
3650     }
3651
3652     /**
3653      * Update the permission flags for all packages and runtime permissions of a user in order
3654      * to allow device or profile owner to remove POLICY_FIXED.
3655      */
3656     @Override
3657     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3658         if (!sUserManager.exists(userId)) {
3659             return;
3660         }
3661
3662         mContext.enforceCallingOrSelfPermission(
3663                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3664                 "updatePermissionFlagsForAllApps");
3665
3666         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3667                 "updatePermissionFlagsForAllApps");
3668
3669         // Only the system can change system fixed flags.
3670         if (getCallingUid() != Process.SYSTEM_UID) {
3671             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3672             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3673         }
3674
3675         synchronized (mPackages) {
3676             boolean changed = false;
3677             final int packageCount = mPackages.size();
3678             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3679                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3680                 SettingBase sb = (SettingBase) pkg.mExtras;
3681                 if (sb == null) {
3682                     continue;
3683                 }
3684                 PermissionsState permissionsState = sb.getPermissionsState();
3685                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3686                         userId, flagMask, flagValues);
3687             }
3688             if (changed) {
3689                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3690             }
3691         }
3692     }
3693
3694     @Override
3695     public boolean shouldShowRequestPermissionRationale(String permissionName,
3696             String packageName, int userId) {
3697         if (UserHandle.getCallingUserId() != userId) {
3698             mContext.enforceCallingPermission(
3699                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3700                     "canShowRequestPermissionRationale for user " + userId);
3701         }
3702
3703         final int uid = getPackageUid(packageName, userId);
3704         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3705             return false;
3706         }
3707
3708         if (checkPermission(permissionName, packageName, userId)
3709                 == PackageManager.PERMISSION_GRANTED) {
3710             return false;
3711         }
3712
3713         final int flags;
3714
3715         final long identity = Binder.clearCallingIdentity();
3716         try {
3717             flags = getPermissionFlags(permissionName,
3718                     packageName, userId);
3719         } finally {
3720             Binder.restoreCallingIdentity(identity);
3721         }
3722
3723         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3724                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3725                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
3726
3727         if ((flags & fixedFlags) != 0) {
3728             return false;
3729         }
3730
3731         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3732     }
3733
3734     void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3735         BasePermission bp = mSettings.mPermissions.get(permission);
3736         if (bp == null) {
3737             throw new SecurityException("Missing " + permission + " permission");
3738         }
3739
3740         SettingBase sb = (SettingBase) pkg.mExtras;
3741         PermissionsState permissionsState = sb.getPermissionsState();
3742
3743         if (permissionsState.grantInstallPermission(bp) !=
3744                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
3745             scheduleWriteSettingsLocked();
3746         }
3747     }
3748
3749     @Override
3750     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3751         mContext.enforceCallingOrSelfPermission(
3752                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3753                 "addOnPermissionsChangeListener");
3754
3755         synchronized (mPackages) {
3756             mOnPermissionChangeListeners.addListenerLocked(listener);
3757         }
3758     }
3759
3760     @Override
3761     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3762         synchronized (mPackages) {
3763             mOnPermissionChangeListeners.removeListenerLocked(listener);
3764         }
3765     }
3766
3767     @Override
3768     public boolean isProtectedBroadcast(String actionName) {
3769         synchronized (mPackages) {
3770             return mProtectedBroadcasts.contains(actionName);
3771         }
3772     }
3773
3774     @Override
3775     public int checkSignatures(String pkg1, String pkg2) {
3776         synchronized (mPackages) {
3777             final PackageParser.Package p1 = mPackages.get(pkg1);
3778             final PackageParser.Package p2 = mPackages.get(pkg2);
3779             if (p1 == null || p1.mExtras == null
3780                     || p2 == null || p2.mExtras == null) {
3781                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3782             }
3783             return compareSignatures(p1.mSignatures, p2.mSignatures);
3784         }
3785     }
3786
3787     @Override
3788     public int checkUidSignatures(int uid1, int uid2) {
3789         // Map to base uids.
3790         uid1 = UserHandle.getAppId(uid1);
3791         uid2 = UserHandle.getAppId(uid2);
3792         // reader
3793         synchronized (mPackages) {
3794             Signature[] s1;
3795             Signature[] s2;
3796             Object obj = mSettings.getUserIdLPr(uid1);
3797             if (obj != null) {
3798                 if (obj instanceof SharedUserSetting) {
3799                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3800                 } else if (obj instanceof PackageSetting) {
3801                     s1 = ((PackageSetting)obj).signatures.mSignatures;
3802                 } else {
3803                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3804                 }
3805             } else {
3806                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3807             }
3808             obj = mSettings.getUserIdLPr(uid2);
3809             if (obj != null) {
3810                 if (obj instanceof SharedUserSetting) {
3811                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3812                 } else if (obj instanceof PackageSetting) {
3813                     s2 = ((PackageSetting)obj).signatures.mSignatures;
3814                 } else {
3815                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3816                 }
3817             } else {
3818                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3819             }
3820             return compareSignatures(s1, s2);
3821         }
3822     }
3823
3824     private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3825         final long identity = Binder.clearCallingIdentity();
3826         try {
3827             if (sb instanceof SharedUserSetting) {
3828                 SharedUserSetting sus = (SharedUserSetting) sb;
3829                 final int packageCount = sus.packages.size();
3830                 for (int i = 0; i < packageCount; i++) {
3831                     PackageSetting susPs = sus.packages.valueAt(i);
3832                     if (userId == UserHandle.USER_ALL) {
3833                         killApplication(susPs.pkg.packageName, susPs.appId, reason);
3834                     } else {
3835                         final int uid = UserHandle.getUid(userId, susPs.appId);
3836                         killUid(uid, reason);
3837                     }
3838                 }
3839             } else if (sb instanceof PackageSetting) {
3840                 PackageSetting ps = (PackageSetting) sb;
3841                 if (userId == UserHandle.USER_ALL) {
3842                     killApplication(ps.pkg.packageName, ps.appId, reason);
3843                 } else {
3844                     final int uid = UserHandle.getUid(userId, ps.appId);
3845                     killUid(uid, reason);
3846                 }
3847             }
3848         } finally {
3849             Binder.restoreCallingIdentity(identity);
3850         }
3851     }
3852
3853     private static void killUid(int uid, String reason) {
3854         IActivityManager am = ActivityManagerNative.getDefault();
3855         if (am != null) {
3856             try {
3857                 am.killUid(uid, reason);
3858             } catch (RemoteException e) {
3859                 /* ignore - same process */
3860             }
3861         }
3862     }
3863
3864     /**
3865      * Compares two sets of signatures. Returns:
3866      * <br />
3867      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3868      * <br />
3869      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3870      * <br />
3871      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3872      * <br />
3873      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3874      * <br />
3875      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3876      */
3877     static int compareSignatures(Signature[] s1, Signature[] s2) {
3878         if (s1 == null) {
3879             return s2 == null
3880                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
3881                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3882         }
3883
3884         if (s2 == null) {
3885             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3886         }
3887
3888         if (s1.length != s2.length) {
3889             return PackageManager.SIGNATURE_NO_MATCH;
3890         }
3891
3892         // Since both signature sets are of size 1, we can compare without HashSets.
3893         if (s1.length == 1) {
3894             return s1[0].equals(s2[0]) ?
3895                     PackageManager.SIGNATURE_MATCH :
3896                     PackageManager.SIGNATURE_NO_MATCH;
3897         }
3898
3899         ArraySet<Signature> set1 = new ArraySet<Signature>();
3900         for (Signature sig : s1) {
3901             set1.add(sig);
3902         }
3903         ArraySet<Signature> set2 = new ArraySet<Signature>();
3904         for (Signature sig : s2) {
3905             set2.add(sig);
3906         }
3907         // Make sure s2 contains all signatures in s1.
3908         if (set1.equals(set2)) {
3909             return PackageManager.SIGNATURE_MATCH;
3910         }
3911         return PackageManager.SIGNATURE_NO_MATCH;
3912     }
3913
3914     /**
3915      * If the database version for this type of package (internal storage or
3916      * external storage) is less than the version where package signatures
3917      * were updated, return true.
3918      */
3919     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3920         return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3921                 DatabaseVersion.SIGNATURE_END_ENTITY))
3922                 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3923                         DatabaseVersion.SIGNATURE_END_ENTITY));
3924     }
3925
3926     /**
3927      * Used for backward compatibility to make sure any packages with
3928      * certificate chains get upgraded to the new style. {@code existingSigs}
3929      * will be in the old format (since they were stored on disk from before the
3930      * system upgrade) and {@code scannedSigs} will be in the newer format.
3931      */
3932     private int compareSignaturesCompat(PackageSignatures existingSigs,
3933             PackageParser.Package scannedPkg) {
3934         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3935             return PackageManager.SIGNATURE_NO_MATCH;
3936         }
3937
3938         ArraySet<Signature> existingSet = new ArraySet<Signature>();
3939         for (Signature sig : existingSigs.mSignatures) {
3940             existingSet.add(sig);
3941         }
3942         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3943         for (Signature sig : scannedPkg.mSignatures) {
3944             try {
3945                 Signature[] chainSignatures = sig.getChainSignatures();
3946                 for (Signature chainSig : chainSignatures) {
3947                     scannedCompatSet.add(chainSig);
3948                 }
3949             } catch (CertificateEncodingException e) {
3950                 scannedCompatSet.add(sig);
3951             }
3952         }
3953         /*
3954          * Make sure the expanded scanned set contains all signatures in the
3955          * existing one.
3956          */
3957         if (scannedCompatSet.equals(existingSet)) {
3958             // Migrate the old signatures to the new scheme.
3959             existingSigs.assignSignatures(scannedPkg.mSignatures);
3960             // The new KeySets will be re-added later in the scanning process.
3961             synchronized (mPackages) {
3962                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3963             }
3964             return PackageManager.SIGNATURE_MATCH;
3965         }
3966         return PackageManager.SIGNATURE_NO_MATCH;
3967     }
3968
3969     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3970         if (isExternal(scannedPkg)) {
3971             return mSettings.isExternalDatabaseVersionOlderThan(
3972                     DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3973         } else {
3974             return mSettings.isInternalDatabaseVersionOlderThan(
3975                     DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3976         }
3977     }
3978
3979     private int compareSignaturesRecover(PackageSignatures existingSigs,
3980             PackageParser.Package scannedPkg) {
3981         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3982             return PackageManager.SIGNATURE_NO_MATCH;
3983         }
3984
3985         String msg = null;
3986         try {
3987             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3988                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3989                         + scannedPkg.packageName);
3990                 return PackageManager.SIGNATURE_MATCH;
3991             }
3992         } catch (CertificateException e) {
3993             msg = e.getMessage();
3994         }
3995
3996         logCriticalInfo(Log.INFO,
3997                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3998         return PackageManager.SIGNATURE_NO_MATCH;
3999     }
4000
4001     @Override
4002     public String[] getPackagesForUid(int uid) {
4003         uid = UserHandle.getAppId(uid);
4004         // reader
4005         synchronized (mPackages) {
4006             Object obj = mSettings.getUserIdLPr(uid);
4007             if (obj instanceof SharedUserSetting) {
4008                 final SharedUserSetting sus = (SharedUserSetting) obj;
4009                 final int N = sus.packages.size();
4010                 final String[] res = new String[N];
4011                 final Iterator<PackageSetting> it = sus.packages.iterator();
4012                 int i = 0;
4013                 while (it.hasNext()) {
4014                     res[i++] = it.next().name;
4015                 }
4016                 return res;
4017             } else if (obj instanceof PackageSetting) {
4018                 final PackageSetting ps = (PackageSetting) obj;
4019                 return new String[] { ps.name };
4020             }
4021         }
4022         return null;
4023     }
4024
4025     @Override
4026     public String getNameForUid(int uid) {
4027         // reader
4028         synchronized (mPackages) {
4029             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030             if (obj instanceof SharedUserSetting) {
4031                 final SharedUserSetting sus = (SharedUserSetting) obj;
4032                 return sus.name + ":" + sus.userId;
4033             } else if (obj instanceof PackageSetting) {
4034                 final PackageSetting ps = (PackageSetting) obj;
4035                 return ps.name;
4036             }
4037         }
4038         return null;
4039     }
4040
4041     @Override
4042     public int getUidForSharedUser(String sharedUserName) {
4043         if(sharedUserName == null) {
4044             return -1;
4045         }
4046         // reader
4047         synchronized (mPackages) {
4048             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4049             if (suid == null) {
4050                 return -1;
4051             }
4052             return suid.userId;
4053         }
4054     }
4055
4056     @Override
4057     public int getFlagsForUid(int uid) {
4058         synchronized (mPackages) {
4059             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4060             if (obj instanceof SharedUserSetting) {
4061                 final SharedUserSetting sus = (SharedUserSetting) obj;
4062                 return sus.pkgFlags;
4063             } else if (obj instanceof PackageSetting) {
4064                 final PackageSetting ps = (PackageSetting) obj;
4065                 return ps.pkgFlags;
4066             }
4067         }
4068         return 0;
4069     }
4070
4071     @Override
4072     public int getPrivateFlagsForUid(int uid) {
4073         synchronized (mPackages) {
4074             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4075             if (obj instanceof SharedUserSetting) {
4076                 final SharedUserSetting sus = (SharedUserSetting) obj;
4077                 return sus.pkgPrivateFlags;
4078             } else if (obj instanceof PackageSetting) {
4079                 final PackageSetting ps = (PackageSetting) obj;
4080                 return ps.pkgPrivateFlags;
4081             }
4082         }
4083         return 0;
4084     }
4085
4086     @Override
4087     public boolean isUidPrivileged(int uid) {
4088         uid = UserHandle.getAppId(uid);
4089         // reader
4090         synchronized (mPackages) {
4091             Object obj = mSettings.getUserIdLPr(uid);
4092             if (obj instanceof SharedUserSetting) {
4093                 final SharedUserSetting sus = (SharedUserSetting) obj;
4094                 final Iterator<PackageSetting> it = sus.packages.iterator();
4095                 while (it.hasNext()) {
4096                     if (it.next().isPrivileged()) {
4097                         return true;
4098                     }
4099                 }
4100             } else if (obj instanceof PackageSetting) {
4101                 final PackageSetting ps = (PackageSetting) obj;
4102                 return ps.isPrivileged();
4103             }
4104         }
4105         return false;
4106     }
4107
4108     @Override
4109     public String[] getAppOpPermissionPackages(String permissionName) {
4110         synchronized (mPackages) {
4111             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4112             if (pkgs == null) {
4113                 return null;
4114             }
4115             return pkgs.toArray(new String[pkgs.size()]);
4116         }
4117     }
4118
4119     @Override
4120     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4121             int flags, int userId) {
4122         if (!sUserManager.exists(userId)) return null;
4123         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4124         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4125         return chooseBestActivity(intent, resolvedType, flags, query, userId);
4126     }
4127
4128     @Override
4129     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4130             IntentFilter filter, int match, ComponentName activity) {
4131         final int userId = UserHandle.getCallingUserId();
4132         if (DEBUG_PREFERRED) {
4133             Log.v(TAG, "setLastChosenActivity intent=" + intent
4134                 + " resolvedType=" + resolvedType
4135                 + " flags=" + flags
4136                 + " filter=" + filter
4137                 + " match=" + match
4138                 + " activity=" + activity);
4139             filter.dump(new PrintStreamPrinter(System.out), "    ");
4140         }
4141         intent.setComponent(null);
4142         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4143         // Find any earlier preferred or last chosen entries and nuke them
4144         findPreferredActivity(intent, resolvedType,
4145                 flags, query, 0, false, true, false, userId);
4146         // Add the new activity as the last chosen for this filter
4147         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4148                 "Setting last chosen");
4149     }
4150
4151     @Override
4152     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4153         final int userId = UserHandle.getCallingUserId();
4154         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4155         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4156         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4157                 false, false, false, userId);
4158     }
4159
4160     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4161             int flags, List<ResolveInfo> query, int userId) {
4162         if (query != null) {
4163             final int N = query.size();
4164             if (N == 1) {
4165                 return query.get(0);
4166             } else if (N > 1) {
4167                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4168                 // If there is more than one activity with the same priority,
4169                 // then let the user decide between them.
4170                 ResolveInfo r0 = query.get(0);
4171                 ResolveInfo r1 = query.get(1);
4172                 if (DEBUG_INTENT_MATCHING || debug) {
4173                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4174                             + r1.activityInfo.name + "=" + r1.priority);
4175                 }
4176                 // If the first activity has a higher priority, or a different
4177                 // default, then it is always desireable to pick it.
4178                 if (r0.priority != r1.priority
4179                         || r0.preferredOrder != r1.preferredOrder
4180                         || r0.isDefault != r1.isDefault) {
4181                     return query.get(0);
4182                 }
4183                 // If we have saved a preference for a preferred activity for
4184                 // this Intent, use that.
4185                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4186                         flags, query, r0.priority, true, false, debug, userId);
4187                 if (ri != null) {
4188                     return ri;
4189                 }
4190                 if (userId != 0) {
4191                     ri = new ResolveInfo(mResolveInfo);
4192                     ri.activityInfo = new ActivityInfo(ri.activityInfo);
4193                     ri.activityInfo.applicationInfo = new ApplicationInfo(
4194                             ri.activityInfo.applicationInfo);
4195                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4196                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4197                     return ri;
4198                 }
4199                 return mResolveInfo;
4200             }
4201         }
4202         return null;
4203     }
4204
4205     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4206             int flags, List<ResolveInfo> query, boolean debug, int userId) {
4207         final int N = query.size();
4208         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4209                 .get(userId);
4210         // Get the list of persistent preferred activities that handle the intent
4211         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4212         List<PersistentPreferredActivity> pprefs = ppir != null
4213                 ? ppir.queryIntent(intent, resolvedType,
4214                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4215                 : null;
4216         if (pprefs != null && pprefs.size() > 0) {
4217             final int M = pprefs.size();
4218             for (int i=0; i<M; i++) {
4219                 final PersistentPreferredActivity ppa = pprefs.get(i);
4220                 if (DEBUG_PREFERRED || debug) {
4221                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4222                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4223                             + "\n  component=" + ppa.mComponent);
4224                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4225                 }
4226                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4227                         flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4228                 if (DEBUG_PREFERRED || debug) {
4229                     Slog.v(TAG, "Found persistent preferred activity:");
4230                     if (ai != null) {
4231                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4232                     } else {
4233                         Slog.v(TAG, "  null");
4234                     }
4235                 }
4236                 if (ai == null) {
4237                     // This previously registered persistent preferred activity
4238                     // component is no longer known. Ignore it and do NOT remove it.
4239                     continue;
4240                 }
4241                 for (int j=0; j<N; j++) {
4242                     final ResolveInfo ri = query.get(j);
4243                     if (!ri.activityInfo.applicationInfo.packageName
4244                             .equals(ai.applicationInfo.packageName)) {
4245                         continue;
4246                     }
4247                     if (!ri.activityInfo.name.equals(ai.name)) {
4248                         continue;
4249                     }
4250                     //  Found a persistent preference that can handle the intent.
4251                     if (DEBUG_PREFERRED || debug) {
4252                         Slog.v(TAG, "Returning persistent preferred activity: " +
4253                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4254                     }
4255                     return ri;
4256                 }
4257             }
4258         }
4259         return null;
4260     }
4261
4262     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4263             List<ResolveInfo> query, int priority, boolean always,
4264             boolean removeMatches, boolean debug, int userId) {
4265         if (!sUserManager.exists(userId)) return null;
4266         // writer
4267         synchronized (mPackages) {
4268             if (intent.getSelector() != null) {
4269                 intent = intent.getSelector();
4270             }
4271             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4272
4273             // Try to find a matching persistent preferred activity.
4274             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4275                     debug, userId);
4276
4277             // If a persistent preferred activity matched, use it.
4278             if (pri != null) {
4279                 return pri;
4280             }
4281
4282             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4283             // Get the list of preferred activities that handle the intent
4284             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4285             List<PreferredActivity> prefs = pir != null
4286                     ? pir.queryIntent(intent, resolvedType,
4287                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4288                     : null;
4289             if (prefs != null && prefs.size() > 0) {
4290                 boolean changed = false;
4291                 try {
4292                     // First figure out how good the original match set is.
4293                     // We will only allow preferred activities that came
4294                     // from the same match quality.
4295                     int match = 0;
4296
4297                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4298
4299                     final int N = query.size();
4300                     for (int j=0; j<N; j++) {
4301                         final ResolveInfo ri = query.get(j);
4302                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4303                                 + ": 0x" + Integer.toHexString(match));
4304                         if (ri.match > match) {
4305                             match = ri.match;
4306                         }
4307                     }
4308
4309                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4310                             + Integer.toHexString(match));
4311
4312                     match &= IntentFilter.MATCH_CATEGORY_MASK;
4313                     final int M = prefs.size();
4314                     for (int i=0; i<M; i++) {
4315                         final PreferredActivity pa = prefs.get(i);
4316                         if (DEBUG_PREFERRED || debug) {
4317                             Slog.v(TAG, "Checking PreferredActivity ds="
4318                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4319                                     + "\n  component=" + pa.mPref.mComponent);
4320                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                         }
4322                         if (pa.mPref.mMatch != match) {
4323                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4324                                     + Integer.toHexString(pa.mPref.mMatch));
4325                             continue;
4326                         }
4327                         // If it's not an "always" type preferred activity and that's what we're
4328                         // looking for, skip it.
4329                         if (always && !pa.mPref.mAlways) {
4330                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4331                             continue;
4332                         }
4333                         final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4334                                 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4335                         if (DEBUG_PREFERRED || debug) {
4336                             Slog.v(TAG, "Found preferred activity:");
4337                             if (ai != null) {
4338                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4339                             } else {
4340                                 Slog.v(TAG, "  null");
4341                             }
4342                         }
4343                         if (ai == null) {
4344                             // This previously registered preferred activity
4345                             // component is no longer known.  Most likely an update
4346                             // to the app was installed and in the new version this
4347                             // component no longer exists.  Clean it up by removing
4348                             // it from the preferred activities list, and skip it.
4349                             Slog.w(TAG, "Removing dangling preferred activity: "
4350                                     + pa.mPref.mComponent);
4351                             pir.removeFilter(pa);
4352                             changed = true;
4353                             continue;
4354                         }
4355                         for (int j=0; j<N; j++) {
4356                             final ResolveInfo ri = query.get(j);
4357                             if (!ri.activityInfo.applicationInfo.packageName
4358                                     .equals(ai.applicationInfo.packageName)) {
4359                                 continue;
4360                             }
4361                             if (!ri.activityInfo.name.equals(ai.name)) {
4362                                 continue;
4363                             }
4364
4365                             if (removeMatches) {
4366                                 pir.removeFilter(pa);
4367                                 changed = true;
4368                                 if (DEBUG_PREFERRED) {
4369                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4370                                 }
4371                                 break;
4372                             }
4373
4374                             // Okay we found a previously set preferred or last chosen app.
4375                             // If the result set is different from when this
4376                             // was created, we need to clear it and re-ask the
4377                             // user their preference, if we're looking for an "always" type entry.
4378                             if (always && !pa.mPref.sameSet(query)) {
4379                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
4380                                         + intent + " type " + resolvedType);
4381                                 if (DEBUG_PREFERRED) {
4382                                     Slog.v(TAG, "Removing preferred activity since set changed "
4383                                             + pa.mPref.mComponent);
4384                                 }
4385                                 pir.removeFilter(pa);
4386                                 // Re-add the filter as a "last chosen" entry (!always)
4387                                 PreferredActivity lastChosen = new PreferredActivity(
4388                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4389                                 pir.addFilter(lastChosen);
4390                                 changed = true;
4391                                 return null;
4392                             }
4393
4394                             // Yay! Either the set matched or we're looking for the last chosen
4395                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4396                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4397                             return ri;
4398                         }
4399                     }
4400                 } finally {
4401                     if (changed) {
4402                         if (DEBUG_PREFERRED) {
4403                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4404                         }
4405                         scheduleWritePackageRestrictionsLocked(userId);
4406                     }
4407                 }
4408             }
4409         }
4410         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4411         return null;
4412     }
4413
4414     /*
4415      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4416      */
4417     @Override
4418     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4419             int targetUserId) {
4420         mContext.enforceCallingOrSelfPermission(
4421                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4422         List<CrossProfileIntentFilter> matches =
4423                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4424         if (matches != null) {
4425             int size = matches.size();
4426             for (int i = 0; i < size; i++) {
4427                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
4428             }
4429         }
4430         if (hasWebURI(intent)) {
4431             // cross-profile app linking works only towards the parent.
4432             final UserInfo parent = getProfileParent(sourceUserId);
4433             synchronized(mPackages) {
4434                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4435                         intent, resolvedType, 0, sourceUserId, parent.id);
4436                 return xpDomainInfo != null
4437                         && xpDomainInfo.bestDomainVerificationStatus !=
4438                                 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4439             }
4440         }
4441         return false;
4442     }
4443
4444     private UserInfo getProfileParent(int userId) {
4445         final long identity = Binder.clearCallingIdentity();
4446         try {
4447             return sUserManager.getProfileParent(userId);
4448         } finally {
4449             Binder.restoreCallingIdentity(identity);
4450         }
4451     }
4452
4453     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4454             String resolvedType, int userId) {
4455         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4456         if (resolver != null) {
4457             return resolver.queryIntent(intent, resolvedType, false, userId);
4458         }
4459         return null;
4460     }
4461
4462     @Override
4463     public List<ResolveInfo> queryIntentActivities(Intent intent,
4464             String resolvedType, int flags, int userId) {
4465         if (!sUserManager.exists(userId)) return Collections.emptyList();
4466         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4467         ComponentName comp = intent.getComponent();
4468         if (comp == null) {
4469             if (intent.getSelector() != null) {
4470                 intent = intent.getSelector();
4471                 comp = intent.getComponent();
4472             }
4473         }
4474
4475         if (comp != null) {
4476             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4477             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4478             if (ai != null) {
4479                 final ResolveInfo ri = new ResolveInfo();
4480                 ri.activityInfo = ai;
4481                 list.add(ri);
4482             }
4483             return list;
4484         }
4485
4486         // reader
4487         synchronized (mPackages) {
4488             final String pkgName = intent.getPackage();
4489             if (pkgName == null) {
4490                 List<CrossProfileIntentFilter> matchingFilters =
4491                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4492                 // Check for results that need to skip the current profile.
4493                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4494                         resolvedType, flags, userId);
4495                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4496                     List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4497                     result.add(xpResolveInfo);
4498                     return filterIfNotPrimaryUser(result, userId);
4499                 }
4500
4501                 // Check for results in the current profile.
4502                 List<ResolveInfo> result = mActivities.queryIntent(
4503                         intent, resolvedType, flags, userId);
4504
4505                 // Check for cross profile results.
4506                 xpResolveInfo = queryCrossProfileIntents(
4507                         matchingFilters, intent, resolvedType, flags, userId);
4508                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4509                     result.add(xpResolveInfo);
4510                     Collections.sort(result, mResolvePrioritySorter);
4511                 }
4512                 result = filterIfNotPrimaryUser(result, userId);
4513                 if (hasWebURI(intent)) {
4514                     CrossProfileDomainInfo xpDomainInfo = null;
4515                     final UserInfo parent = getProfileParent(userId);
4516                     if (parent != null) {
4517                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4518                                 flags, userId, parent.id);
4519                     }
4520                     if (xpDomainInfo != null) {
4521                         if (xpResolveInfo != null) {
4522                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
4523                             // in the result.
4524                             result.remove(xpResolveInfo);
4525                         }
4526                         if (result.size() == 0) {
4527                             result.add(xpDomainInfo.resolveInfo);
4528                             return result;
4529                         }
4530                     } else if (result.size() <= 1) {
4531                         return result;
4532                     }
4533                     result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4534                             xpDomainInfo, userId);
4535                     Collections.sort(result, mResolvePrioritySorter);
4536                 }
4537                 return result;
4538             }
4539             final PackageParser.Package pkg = mPackages.get(pkgName);
4540             if (pkg != null) {
4541                 return filterIfNotPrimaryUser(
4542                         mActivities.queryIntentForPackage(
4543                                 intent, resolvedType, flags, pkg.activities, userId),
4544                         userId);
4545             }
4546             return new ArrayList<ResolveInfo>();
4547         }
4548     }
4549
4550     private static class CrossProfileDomainInfo {
4551         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4552         ResolveInfo resolveInfo;
4553         /* Best domain verification status of the activities found in the other profile */
4554         int bestDomainVerificationStatus;
4555     }
4556
4557     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4558             String resolvedType, int flags, int sourceUserId, int parentUserId) {
4559         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4560                 sourceUserId)) {
4561             return null;
4562         }
4563         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4564                 resolvedType, flags, parentUserId);
4565
4566         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4567             return null;
4568         }
4569         CrossProfileDomainInfo result = null;
4570         int size = resultTargetUser.size();
4571         for (int i = 0; i < size; i++) {
4572             ResolveInfo riTargetUser = resultTargetUser.get(i);
4573             // Intent filter verification is only for filters that specify a host. So don't return
4574             // those that handle all web uris.
4575             if (riTargetUser.handleAllWebDataURI) {
4576                 continue;
4577             }
4578             String packageName = riTargetUser.activityInfo.packageName;
4579             PackageSetting ps = mSettings.mPackages.get(packageName);
4580             if (ps == null) {
4581                 continue;
4582             }
4583             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4584             int status = (int)(verificationState >> 32);
4585             if (result == null) {
4586                 result = new CrossProfileDomainInfo();
4587                 result.resolveInfo =
4588                         createForwardingResolveInfo(null, sourceUserId, parentUserId);
4589                 result.bestDomainVerificationStatus = status;
4590             } else {
4591                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4592                         result.bestDomainVerificationStatus);
4593             }
4594         }
4595         return result;
4596     }
4597
4598     /**
4599      * Verification statuses are ordered from the worse to the best, except for
4600      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4601      */
4602     private int bestDomainVerificationStatus(int status1, int status2) {
4603         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4604             return status2;
4605         }
4606         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4607             return status1;
4608         }
4609         return (int) MathUtils.max(status1, status2);
4610     }
4611
4612     private boolean isUserEnabled(int userId) {
4613         long callingId = Binder.clearCallingIdentity();
4614         try {
4615             UserInfo userInfo = sUserManager.getUserInfo(userId);
4616             return userInfo != null && userInfo.isEnabled();
4617         } finally {
4618             Binder.restoreCallingIdentity(callingId);
4619         }
4620     }
4621
4622     /**
4623      * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4624      *
4625      * @return filtered list
4626      */
4627     private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4628         if (userId == UserHandle.USER_OWNER) {
4629             return resolveInfos;
4630         }
4631         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4632             ResolveInfo info = resolveInfos.get(i);
4633             if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4634                 resolveInfos.remove(i);
4635             }
4636         }
4637         return resolveInfos;
4638     }
4639
4640     private static boolean hasWebURI(Intent intent) {
4641         if (intent.getData() == null) {
4642             return false;
4643         }
4644         final String scheme = intent.getScheme();
4645         if (TextUtils.isEmpty(scheme)) {
4646             return false;
4647         }
4648         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4649     }
4650
4651     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4652             int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4653             int userId) {
4654         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4655             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4656                     candidates.size());
4657         }
4658
4659         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4660         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4661         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4662         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4663         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4664
4665         synchronized (mPackages) {
4666             final int count = candidates.size();
4667             // First, try to use linked apps. Partition the candidates into four lists:
4668             // one for the final results, one for the "do not use ever", one for "undefined status"
4669             // and finally one for "browser app type".
4670             for (int n=0; n<count; n++) {
4671                 ResolveInfo info = candidates.get(n);
4672                 String packageName = info.activityInfo.packageName;
4673                 PackageSetting ps = mSettings.mPackages.get(packageName);
4674                 if (ps != null) {
4675                     // Add to the special match all list (Browser use case)
4676                     if (info.handleAllWebDataURI) {
4677                         matchAllList.add(info);
4678                         continue;
4679                     }
4680                     // Try to get the status from User settings first
4681                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4682                     int status = (int)(packedStatus >> 32);
4683                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4684                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4685                         if (DEBUG_DOMAIN_VERIFICATION) {
4686                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4687                                     + " : linkgen=" + linkGeneration);
4688                         }
4689                         // Use link-enabled generation as preferredOrder, i.e.
4690                         // prefer newly-enabled over earlier-enabled.
4691                         info.preferredOrder = linkGeneration;
4692                         alwaysList.add(info);
4693                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4694                         if (DEBUG_DOMAIN_VERIFICATION) {
4695                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4696                         }
4697                         neverList.add(info);
4698                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4699                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4700                         if (DEBUG_DOMAIN_VERIFICATION) {
4701                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4702                         }
4703                         undefinedList.add(info);
4704                     }
4705                 }
4706             }
4707             // First try to add the "always" resolution(s) for the current user, if any
4708             if (alwaysList.size() > 0) {
4709                 result.addAll(alwaysList);
4710             // if there is an "always" for the parent user, add it.
4711             } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4712                     == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4713                 result.add(xpDomainInfo.resolveInfo);
4714             } else {
4715                 // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4716                 result.addAll(undefinedList);
4717                 if (xpDomainInfo != null && (
4718                         xpDomainInfo.bestDomainVerificationStatus
4719                         == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4720                         || xpDomainInfo.bestDomainVerificationStatus
4721                         == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4722                     result.add(xpDomainInfo.resolveInfo);
4723                 }
4724                 // Also add Browsers (all of them or only the default one)
4725                 if ((flags & MATCH_ALL) != 0) {
4726                     result.addAll(matchAllList);
4727                 } else {
4728                     // Try to add the Default Browser if we can
4729                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4730                             UserHandle.myUserId());
4731                     if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4732                         boolean defaultBrowserFound = false;
4733                         final int browserCount = matchAllList.size();
4734                         for (int n=0; n<browserCount; n++) {
4735                             ResolveInfo browser = matchAllList.get(n);
4736                             if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4737                                 result.add(browser);
4738                                 defaultBrowserFound = true;
4739                                 break;
4740                             }
4741                         }
4742                         if (!defaultBrowserFound) {
4743                             result.addAll(matchAllList);
4744                         }
4745                     } else {
4746                         result.addAll(matchAllList);
4747                     }
4748                 }
4749
4750                 // If there is nothing selected, add all candidates and remove the ones that the user
4751                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4752                 if (result.size() == 0) {
4753                     result.addAll(candidates);
4754                     result.removeAll(neverList);
4755                 }
4756             }
4757         }
4758         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4759             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4760                     result.size());
4761             for (ResolveInfo info : result) {
4762                 Slog.v(TAG, "  + " + info.activityInfo);
4763             }
4764         }
4765         return result;
4766     }
4767
4768     // Returns a packed value as a long:
4769     //
4770     // high 'int'-sized word: link status: undefined/ask/never/always.
4771     // low 'int'-sized word: relative priority among 'always' results.
4772     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4773         long result = ps.getDomainVerificationStatusForUser(userId);
4774         // if none available, get the master status
4775         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4776             if (ps.getIntentFilterVerificationInfo() != null) {
4777                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4778             }
4779         }
4780         return result;
4781     }
4782
4783     private ResolveInfo querySkipCurrentProfileIntents(
4784             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4785             int flags, int sourceUserId) {
4786         if (matchingFilters != null) {
4787             int size = matchingFilters.size();
4788             for (int i = 0; i < size; i ++) {
4789                 CrossProfileIntentFilter filter = matchingFilters.get(i);
4790                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4791                     // Checking if there are activities in the target user that can handle the
4792                     // intent.
4793                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4794                             flags, sourceUserId);
4795                     if (resolveInfo != null) {
4796                         return resolveInfo;
4797                     }
4798                 }
4799             }
4800         }
4801         return null;
4802     }
4803
4804     // Return matching ResolveInfo if any for skip current profile intent filters.
4805     private ResolveInfo queryCrossProfileIntents(
4806             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4807             int flags, int sourceUserId) {
4808         if (matchingFilters != null) {
4809             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4810             // match the same intent. For performance reasons, it is better not to
4811             // run queryIntent twice for the same userId
4812             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4813             int size = matchingFilters.size();
4814             for (int i = 0; i < size; i++) {
4815                 CrossProfileIntentFilter filter = matchingFilters.get(i);
4816                 int targetUserId = filter.getTargetUserId();
4817                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4818                         && !alreadyTriedUserIds.get(targetUserId)) {
4819                     // Checking if there are activities in the target user that can handle the
4820                     // intent.
4821                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4822                             flags, sourceUserId);
4823                     if (resolveInfo != null) return resolveInfo;
4824                     alreadyTriedUserIds.put(targetUserId, true);
4825                 }
4826             }
4827         }
4828         return null;
4829     }
4830
4831     private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4832             String resolvedType, int flags, int sourceUserId) {
4833         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4834                 resolvedType, flags, filter.getTargetUserId());
4835         if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4836             return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4837         }
4838         return null;
4839     }
4840
4841     private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4842             int sourceUserId, int targetUserId) {
4843         ResolveInfo forwardingResolveInfo = new ResolveInfo();
4844         String className;
4845         if (targetUserId == UserHandle.USER_OWNER) {
4846             className = FORWARD_INTENT_TO_USER_OWNER;
4847         } else {
4848             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4849         }
4850         ComponentName forwardingActivityComponentName = new ComponentName(
4851                 mAndroidApplication.packageName, className);
4852         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4853                 sourceUserId);
4854         if (targetUserId == UserHandle.USER_OWNER) {
4855             forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4856             forwardingResolveInfo.noResourceId = true;
4857         }
4858         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4859         forwardingResolveInfo.priority = 0;
4860         forwardingResolveInfo.preferredOrder = 0;
4861         forwardingResolveInfo.match = 0;
4862         forwardingResolveInfo.isDefault = true;
4863         forwardingResolveInfo.filter = filter;
4864         forwardingResolveInfo.targetUserId = targetUserId;
4865         return forwardingResolveInfo;
4866     }
4867
4868     @Override
4869     public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4870             Intent[] specifics, String[] specificTypes, Intent intent,
4871             String resolvedType, int flags, int userId) {
4872         if (!sUserManager.exists(userId)) return Collections.emptyList();
4873         enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4874                 false, "query intent activity options");
4875         final String resultsAction = intent.getAction();
4876
4877         List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4878                 | PackageManager.GET_RESOLVED_FILTER, userId);
4879
4880         if (DEBUG_INTENT_MATCHING) {
4881             Log.v(TAG, "Query " + intent + ": " + results);
4882         }
4883
4884         int specificsPos = 0;
4885         int N;
4886
4887         // todo: note that the algorithm used here is O(N^2).  This
4888         // isn't a problem in our current environment, but if we start running
4889         // into situations where we have more than 5 or 10 matches then this
4890         // should probably be changed to something smarter...
4891
4892         // First we go through and resolve each of the specific items
4893         // that were supplied, taking care of removing any corresponding
4894         // duplicate items in the generic resolve list.
4895         if (specifics != null) {
4896             for (int i=0; i<specifics.length; i++) {
4897                 final Intent sintent = specifics[i];
4898                 if (sintent == null) {
4899                     continue;
4900                 }
4901
4902                 if (DEBUG_INTENT_MATCHING) {
4903                     Log.v(TAG, "Specific #" + i + ": " + sintent);
4904                 }
4905
4906                 String action = sintent.getAction();
4907                 if (resultsAction != null && resultsAction.equals(action)) {
4908                     // If this action was explicitly requested, then don't
4909                     // remove things that have it.
4910                     action = null;
4911                 }
4912
4913                 ResolveInfo ri = null;
4914                 ActivityInfo ai = null;
4915
4916                 ComponentName comp = sintent.getComponent();
4917                 if (comp == null) {
4918                     ri = resolveIntent(
4919                         sintent,
4920                         specificTypes != null ? specificTypes[i] : null,
4921                             flags, userId);
4922                     if (ri == null) {
4923                         continue;
4924                     }
4925                     if (ri == mResolveInfo) {
4926                         // ACK!  Must do something better with this.
4927                     }
4928                     ai = ri.activityInfo;
4929                     comp = new ComponentName(ai.applicationInfo.packageName,
4930                             ai.name);
4931                 } else {
4932                     ai = getActivityInfo(comp, flags, userId);
4933                     if (ai == null) {
4934                         continue;
4935                     }
4936                 }
4937
4938                 // Look for any generic query activities that are duplicates
4939                 // of this specific one, and remove them from the results.
4940                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4941                 N = results.size();
4942                 int j;
4943                 for (j=specificsPos; j<N; j++) {
4944                     ResolveInfo sri = results.get(j);
4945                     if ((sri.activityInfo.name.equals(comp.getClassName())
4946                             && sri.activityInfo.applicationInfo.packageName.equals(
4947                                     comp.getPackageName()))
4948                         || (action != null && sri.filter.matchAction(action))) {
4949                         results.remove(j);
4950                         if (DEBUG_INTENT_MATCHING) Log.v(
4951                             TAG, "Removing duplicate item from " + j
4952                             + " due to specific " + specificsPos);
4953                         if (ri == null) {
4954                             ri = sri;
4955                         }
4956                         j--;
4957                         N--;
4958                     }
4959                 }
4960
4961                 // Add this specific item to its proper place.
4962                 if (ri == null) {
4963                     ri = new ResolveInfo();
4964                     ri.activityInfo = ai;
4965                 }
4966                 results.add(specificsPos, ri);
4967                 ri.specificIndex = i;
4968                 specificsPos++;
4969             }
4970         }
4971
4972         // Now we go through the remaining generic results and remove any
4973         // duplicate actions that are found here.
4974         N = results.size();
4975         for (int i=specificsPos; i<N-1; i++) {
4976             final ResolveInfo rii = results.get(i);
4977             if (rii.filter == null) {
4978                 continue;
4979             }
4980
4981             // Iterate over all of the actions of this result's intent
4982             // filter...  typically this should be just one.
4983             final Iterator<String> it = rii.filter.actionsIterator();
4984             if (it == null) {
4985                 continue;
4986             }
4987             while (it.hasNext()) {
4988                 final String action = it.next();
4989                 if (resultsAction != null && resultsAction.equals(action)) {
4990                     // If this action was explicitly requested, then don't
4991                     // remove things that have it.
4992                     continue;
4993                 }
4994                 for (int j=i+1; j<N; j++) {
4995                     final ResolveInfo rij = results.get(j);
4996                     if (rij.filter != null && rij.filter.hasAction(action)) {
4997                         results.remove(j);
4998                         if (DEBUG_INTENT_MATCHING) Log.v(
4999                             TAG, "Removing duplicate item from " + j
5000                             + " due to action " + action + " at " + i);
5001                         j--;
5002                         N--;
5003                     }
5004                 }
5005             }
5006
5007             // If the caller didn't request filter information, drop it now
5008             // so we don't have to marshall/unmarshall it.
5009             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5010                 rii.filter = null;
5011             }
5012         }
5013
5014         // Filter out the caller activity if so requested.
5015         if (caller != null) {
5016             N = results.size();
5017             for (int i=0; i<N; i++) {
5018                 ActivityInfo ainfo = results.get(i).activityInfo;
5019                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5020                         && caller.getClassName().equals(ainfo.name)) {
5021                     results.remove(i);
5022                     break;
5023                 }
5024             }
5025         }
5026
5027         // If the caller didn't request filter information,
5028         // drop them now so we don't have to
5029         // marshall/unmarshall it.
5030         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5031             N = results.size();
5032             for (int i=0; i<N; i++) {
5033                 results.get(i).filter = null;
5034             }
5035         }
5036
5037         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5038         return results;
5039     }
5040
5041     @Override
5042     public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5043             int userId) {
5044         if (!sUserManager.exists(userId)) return Collections.emptyList();
5045         ComponentName comp = intent.getComponent();
5046         if (comp == null) {
5047             if (intent.getSelector() != null) {
5048                 intent = intent.getSelector();
5049                 comp = intent.getComponent();
5050             }
5051         }
5052         if (comp != null) {
5053             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5054             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5055             if (ai != null) {
5056                 ResolveInfo ri = new ResolveInfo();
5057                 ri.activityInfo = ai;
5058                 list.add(ri);
5059             }
5060             return list;
5061         }
5062
5063         // reader
5064         synchronized (mPackages) {
5065             String pkgName = intent.getPackage();
5066             if (pkgName == null) {
5067                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5068             }
5069             final PackageParser.Package pkg = mPackages.get(pkgName);
5070             if (pkg != null) {
5071                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5072                         userId);
5073             }
5074             return null;
5075         }
5076     }
5077
5078     @Override
5079     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5080         List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5081         if (!sUserManager.exists(userId)) return null;
5082         if (query != null) {
5083             if (query.size() >= 1) {
5084                 // If there is more than one service with the same priority,
5085                 // just arbitrarily pick the first one.
5086                 return query.get(0);
5087             }
5088         }
5089         return null;
5090     }
5091
5092     @Override
5093     public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5094             int userId) {
5095         if (!sUserManager.exists(userId)) return Collections.emptyList();
5096         ComponentName comp = intent.getComponent();
5097         if (comp == null) {
5098             if (intent.getSelector() != null) {
5099                 intent = intent.getSelector();
5100                 comp = intent.getComponent();
5101             }
5102         }
5103         if (comp != null) {
5104             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5105             final ServiceInfo si = getServiceInfo(comp, flags, userId);
5106             if (si != null) {
5107                 final ResolveInfo ri = new ResolveInfo();
5108                 ri.serviceInfo = si;
5109                 list.add(ri);
5110             }
5111             return list;
5112         }
5113
5114         // reader
5115         synchronized (mPackages) {
5116             String pkgName = intent.getPackage();
5117             if (pkgName == null) {
5118                 return mServices.queryIntent(intent, resolvedType, flags, userId);
5119             }
5120             final PackageParser.Package pkg = mPackages.get(pkgName);
5121             if (pkg != null) {
5122                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5123                         userId);
5124             }
5125             return null;
5126         }
5127     }
5128
5129     @Override
5130     public List<ResolveInfo> queryIntentContentProviders(
5131             Intent intent, String resolvedType, int flags, int userId) {
5132         if (!sUserManager.exists(userId)) return Collections.emptyList();
5133         ComponentName comp = intent.getComponent();
5134         if (comp == null) {
5135             if (intent.getSelector() != null) {
5136                 intent = intent.getSelector();
5137                 comp = intent.getComponent();
5138             }
5139         }
5140         if (comp != null) {
5141             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5142             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5143             if (pi != null) {
5144                 final ResolveInfo ri = new ResolveInfo();
5145                 ri.providerInfo = pi;
5146                 list.add(ri);
5147             }
5148             return list;
5149         }
5150
5151         // reader
5152         synchronized (mPackages) {
5153             String pkgName = intent.getPackage();
5154             if (pkgName == null) {
5155                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
5156             }
5157             final PackageParser.Package pkg = mPackages.get(pkgName);
5158             if (pkg != null) {
5159                 return mProviders.queryIntentForPackage(
5160                         intent, resolvedType, flags, pkg.providers, userId);
5161             }
5162             return null;
5163         }
5164     }
5165
5166     @Override
5167     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5168         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5169
5170         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5171
5172         // writer
5173         synchronized (mPackages) {
5174             ArrayList<PackageInfo> list;
5175             if (listUninstalled) {
5176                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5177                 for (PackageSetting ps : mSettings.mPackages.values()) {
5178                     PackageInfo pi;
5179                     if (ps.pkg != null) {
5180                         pi = generatePackageInfo(ps.pkg, flags, userId);
5181                     } else {
5182                         pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5183                     }
5184                     if (pi != null) {
5185                         list.add(pi);
5186                     }
5187                 }
5188             } else {
5189                 list = new ArrayList<PackageInfo>(mPackages.size());
5190                 for (PackageParser.Package p : mPackages.values()) {
5191                     PackageInfo pi = generatePackageInfo(p, flags, userId);
5192                     if (pi != null) {
5193                         list.add(pi);
5194                     }
5195                 }
5196             }
5197
5198             return new ParceledListSlice<PackageInfo>(list);
5199         }
5200     }
5201
5202     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5203             String[] permissions, boolean[] tmp, int flags, int userId) {
5204         int numMatch = 0;
5205         final PermissionsState permissionsState = ps.getPermissionsState();
5206         for (int i=0; i<permissions.length; i++) {
5207             final String permission = permissions[i];
5208             if (permissionsState.hasPermission(permission, userId)) {
5209                 tmp[i] = true;
5210                 numMatch++;
5211             } else {
5212                 tmp[i] = false;
5213             }
5214         }
5215         if (numMatch == 0) {
5216             return;
5217         }
5218         PackageInfo pi;
5219         if (ps.pkg != null) {
5220             pi = generatePackageInfo(ps.pkg, flags, userId);
5221         } else {
5222             pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5223         }
5224         // The above might return null in cases of uninstalled apps or install-state
5225         // skew across users/profiles.
5226         if (pi != null) {
5227             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5228                 if (numMatch == permissions.length) {
5229                     pi.requestedPermissions = permissions;
5230                 } else {
5231                     pi.requestedPermissions = new String[numMatch];
5232                     numMatch = 0;
5233                     for (int i=0; i<permissions.length; i++) {
5234                         if (tmp[i]) {
5235                             pi.requestedPermissions[numMatch] = permissions[i];
5236                             numMatch++;
5237                         }
5238                     }
5239                 }
5240             }
5241             list.add(pi);
5242         }
5243     }
5244
5245     @Override
5246     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5247             String[] permissions, int flags, int userId) {
5248         if (!sUserManager.exists(userId)) return null;
5249         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5250
5251         // writer
5252         synchronized (mPackages) {
5253             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5254             boolean[] tmpBools = new boolean[permissions.length];
5255             if (listUninstalled) {
5256                 for (PackageSetting ps : mSettings.mPackages.values()) {
5257                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5258                 }
5259             } else {
5260                 for (PackageParser.Package pkg : mPackages.values()) {
5261                     PackageSetting ps = (PackageSetting)pkg.mExtras;
5262                     if (ps != null) {
5263                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5264                                 userId);
5265                     }
5266                 }
5267             }
5268
5269             return new ParceledListSlice<PackageInfo>(list);
5270         }
5271     }
5272
5273     @Override
5274     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5275         if (!sUserManager.exists(userId)) return null;
5276         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5277
5278         // writer
5279         synchronized (mPackages) {
5280             ArrayList<ApplicationInfo> list;
5281             if (listUninstalled) {
5282                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5283                 for (PackageSetting ps : mSettings.mPackages.values()) {
5284                     ApplicationInfo ai;
5285                     if (ps.pkg != null) {
5286                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5287                                 ps.readUserState(userId), userId);
5288                     } else {
5289                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5290                     }
5291                     if (ai != null) {
5292                         list.add(ai);
5293                     }
5294                 }
5295             } else {
5296                 list = new ArrayList<ApplicationInfo>(mPackages.size());
5297                 for (PackageParser.Package p : mPackages.values()) {
5298                     if (p.mExtras != null) {
5299                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5300                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
5301                         if (ai != null) {
5302                             list.add(ai);
5303                         }
5304                     }
5305                 }
5306             }
5307
5308             return new ParceledListSlice<ApplicationInfo>(list);
5309         }
5310     }
5311
5312     public List<ApplicationInfo> getPersistentApplications(int flags) {
5313         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5314
5315         // reader
5316         synchronized (mPackages) {
5317             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5318             final int userId = UserHandle.getCallingUserId();
5319             while (i.hasNext()) {
5320                 final PackageParser.Package p = i.next();
5321                 if (p.applicationInfo != null
5322                         && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5323                         && (!mSafeMode || isSystemApp(p))) {
5324                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
5325                     if (ps != null) {
5326                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5327                                 ps.readUserState(userId), userId);
5328                         if (ai != null) {
5329                             finalList.add(ai);
5330                         }
5331                     }
5332                 }
5333             }
5334         }
5335
5336         return finalList;
5337     }
5338
5339     @Override
5340     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5341         if (!sUserManager.exists(userId)) return null;
5342         // reader
5343         synchronized (mPackages) {
5344             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5345             PackageSetting ps = provider != null
5346                     ? mSettings.mPackages.get(provider.owner.packageName)
5347                     : null;
5348             return ps != null
5349                     && mSettings.isEnabledLPr(provider.info, flags, userId)
5350                     && (!mSafeMode || (provider.info.applicationInfo.flags
5351                             &ApplicationInfo.FLAG_SYSTEM) != 0)
5352                     ? PackageParser.generateProviderInfo(provider, flags,
5353                             ps.readUserState(userId), userId)
5354                     : null;
5355         }
5356     }
5357
5358     /**
5359      * @deprecated
5360      */
5361     @Deprecated
5362     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5363         // reader
5364         synchronized (mPackages) {
5365             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5366                     .entrySet().iterator();
5367             final int userId = UserHandle.getCallingUserId();
5368             while (i.hasNext()) {
5369                 Map.Entry<String, PackageParser.Provider> entry = i.next();
5370                 PackageParser.Provider p = entry.getValue();
5371                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5372
5373                 if (ps != null && p.syncable
5374                         && (!mSafeMode || (p.info.applicationInfo.flags
5375                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5376                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5377                             ps.readUserState(userId), userId);
5378                     if (info != null) {
5379                         outNames.add(entry.getKey());
5380                         outInfo.add(info);
5381                     }
5382                 }
5383             }
5384         }
5385     }
5386
5387     @Override
5388     public List<ProviderInfo> queryContentProviders(String processName,
5389             int uid, int flags) {
5390         ArrayList<ProviderInfo> finalList = null;
5391         // reader
5392         synchronized (mPackages) {
5393             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5394             final int userId = processName != null ?
5395                     UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5396             while (i.hasNext()) {
5397                 final PackageParser.Provider p = i.next();
5398                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5399                 if (ps != null && p.info.authority != null
5400                         && (processName == null
5401                                 || (p.info.processName.equals(processName)
5402                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5403                         && mSettings.isEnabledLPr(p.info, flags, userId)
5404                         && (!mSafeMode
5405                                 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5406                     if (finalList == null) {
5407                         finalList = new ArrayList<ProviderInfo>(3);
5408                     }
5409                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5410                             ps.readUserState(userId), userId);
5411                     if (info != null) {
5412                         finalList.add(info);
5413                     }
5414                 }
5415             }
5416         }
5417
5418         if (finalList != null) {
5419             Collections.sort(finalList, mProviderInitOrderSorter);
5420         }
5421
5422         return finalList;
5423     }
5424
5425     @Override
5426     public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5427             int flags) {
5428         // reader
5429         synchronized (mPackages) {
5430             final PackageParser.Instrumentation i = mInstrumentation.get(name);
5431             return PackageParser.generateInstrumentationInfo(i, flags);
5432         }
5433     }
5434
5435     @Override
5436     public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5437             int flags) {
5438         ArrayList<InstrumentationInfo> finalList =
5439             new ArrayList<InstrumentationInfo>();
5440
5441         // reader
5442         synchronized (mPackages) {
5443             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5444             while (i.hasNext()) {
5445                 final PackageParser.Instrumentation p = i.next();
5446                 if (targetPackage == null
5447                         || targetPackage.equals(p.info.targetPackage)) {
5448                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5449                             flags);
5450                     if (ii != null) {
5451                         finalList.add(ii);
5452                     }
5453                 }
5454             }
5455         }
5456
5457         return finalList;
5458     }
5459
5460     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5461         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5462         if (overlays == null) {
5463             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5464             return;
5465         }
5466         for (PackageParser.Package opkg : overlays.values()) {
5467             // Not much to do if idmap fails: we already logged the error
5468             // and we certainly don't want to abort installation of pkg simply
5469             // because an overlay didn't fit properly. For these reasons,
5470             // ignore the return value of createIdmapForPackagePairLI.
5471             createIdmapForPackagePairLI(pkg, opkg);
5472         }
5473     }
5474
5475     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5476             PackageParser.Package opkg) {
5477         if (!opkg.mTrustedOverlay) {
5478             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5479                     opkg.baseCodePath + ": overlay not trusted");
5480             return false;
5481         }
5482         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5483         if (overlaySet == null) {
5484             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5485                     opkg.baseCodePath + " but target package has no known overlays");
5486             return false;
5487         }
5488         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5489         // TODO: generate idmap for split APKs
5490         if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5491             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5492                     + opkg.baseCodePath);
5493             return false;
5494         }
5495         PackageParser.Package[] overlayArray =
5496             overlaySet.values().toArray(new PackageParser.Package[0]);
5497         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5498             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5499                 return p1.mOverlayPriority - p2.mOverlayPriority;
5500             }
5501         };
5502         Arrays.sort(overlayArray, cmp);
5503
5504         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5505         int i = 0;
5506         for (PackageParser.Package p : overlayArray) {
5507             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5508         }
5509         return true;
5510     }
5511
5512     private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5513         final File[] files = dir.listFiles();
5514         if (ArrayUtils.isEmpty(files)) {
5515             Log.d(TAG, "No files in app dir " + dir);
5516             return;
5517         }
5518
5519         if (DEBUG_PACKAGE_SCANNING) {
5520             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5521                     + " flags=0x" + Integer.toHexString(parseFlags));
5522         }
5523
5524         for (File file : files) {
5525             final boolean isPackage = (isApkFile(file) || file.isDirectory())
5526                     && !PackageInstallerService.isStageName(file.getName());
5527             if (!isPackage) {
5528                 // Ignore entries which are not packages
5529                 continue;
5530             }
5531             try {
5532                 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5533                         scanFlags, currentTime, null);
5534             } catch (PackageManagerException e) {
5535                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5536
5537                 // Delete invalid userdata apps
5538                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5539                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5540                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5541                     if (file.isDirectory()) {
5542                         mInstaller.rmPackageDir(file.getAbsolutePath());
5543                     } else {
5544                         file.delete();
5545                     }
5546                 }
5547             }
5548         }
5549     }
5550
5551     private static File getSettingsProblemFile() {
5552         File dataDir = Environment.getDataDirectory();
5553         File systemDir = new File(dataDir, "system");
5554         File fname = new File(systemDir, "uiderrors.txt");
5555         return fname;
5556     }
5557
5558     static void reportSettingsProblem(int priority, String msg) {
5559         logCriticalInfo(priority, msg);
5560     }
5561
5562     static void logCriticalInfo(int priority, String msg) {
5563         Slog.println(priority, TAG, msg);
5564         EventLogTags.writePmCriticalInfo(msg);
5565         try {
5566             File fname = getSettingsProblemFile();
5567             FileOutputStream out = new FileOutputStream(fname, true);
5568             PrintWriter pw = new FastPrintWriter(out);
5569             SimpleDateFormat formatter = new SimpleDateFormat();
5570             String dateString = formatter.format(new Date(System.currentTimeMillis()));
5571             pw.println(dateString + ": " + msg);
5572             pw.close();
5573             FileUtils.setPermissions(
5574                     fname.toString(),
5575                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5576                     -1, -1);
5577         } catch (java.io.IOException e) {
5578         }
5579     }
5580
5581     private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5582             PackageParser.Package pkg, File srcFile, int parseFlags)
5583             throws PackageManagerException {
5584         if (ps != null
5585                 && ps.codePath.equals(srcFile)
5586                 && ps.timeStamp == srcFile.lastModified()
5587                 && !isCompatSignatureUpdateNeeded(pkg)
5588                 && !isRecoverSignatureUpdateNeeded(pkg)) {
5589             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5590             KeySetManagerService ksms = mSettings.mKeySetManagerService;
5591             ArraySet<PublicKey> signingKs;
5592             synchronized (mPackages) {
5593                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5594             }
5595             if (ps.signatures.mSignatures != null
5596                     && ps.signatures.mSignatures.length != 0
5597                     && signingKs != null) {
5598                 // Optimization: reuse the existing cached certificates
5599                 // if the package appears to be unchanged.
5600                 pkg.mSignatures = ps.signatures.mSignatures;
5601                 pkg.mSigningKeys = signingKs;
5602                 return;
5603             }
5604
5605             Slog.w(TAG, "PackageSetting for " + ps.name
5606                     + " is missing signatures.  Collecting certs again to recover them.");
5607         } else {
5608             Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5609         }
5610
5611         try {
5612             pp.collectCertificates(pkg, parseFlags);
5613             pp.collectManifestDigest(pkg);
5614         } catch (PackageParserException e) {
5615             throw PackageManagerException.from(e);
5616         }
5617     }
5618
5619     /*
5620      *  Scan a package and return the newly parsed package.
5621      *  Returns null in case of errors and the error code is stored in mLastScanError
5622      */
5623     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5624             long currentTime, UserHandle user) throws PackageManagerException {
5625         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5626         parseFlags |= mDefParseFlags;
5627         PackageParser pp = new PackageParser();
5628         pp.setSeparateProcesses(mSeparateProcesses);
5629         pp.setOnlyCoreApps(mOnlyCore);
5630         pp.setDisplayMetrics(mMetrics);
5631
5632         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5633             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5634         }
5635
5636         final PackageParser.Package pkg;
5637         try {
5638             pkg = pp.parsePackage(scanFile, parseFlags);
5639         } catch (PackageParserException e) {
5640             throw PackageManagerException.from(e);
5641         }
5642
5643         PackageSetting ps = null;
5644         PackageSetting updatedPkg;
5645         // reader
5646         synchronized (mPackages) {
5647             // Look to see if we already know about this package.
5648             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5649             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5650                 // This package has been renamed to its original name.  Let's
5651                 // use that.
5652                 ps = mSettings.peekPackageLPr(oldName);
5653             }
5654             // If there was no original package, see one for the real package name.
5655             if (ps == null) {
5656                 ps = mSettings.peekPackageLPr(pkg.packageName);
5657             }
5658             // Check to see if this package could be hiding/updating a system
5659             // package.  Must look for it either under the original or real
5660             // package name depending on our state.
5661             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5662             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5663         }
5664         boolean updatedPkgBetter = false;
5665         // First check if this is a system package that may involve an update
5666         if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5667             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5668             // it needs to drop FLAG_PRIVILEGED.
5669             if (locationIsPrivileged(scanFile)) {
5670                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5671             } else {
5672                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5673             }
5674
5675             if (ps != null && !ps.codePath.equals(scanFile)) {
5676                 // The path has changed from what was last scanned...  check the
5677                 // version of the new path against what we have stored to determine
5678                 // what to do.
5679                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5680                 if (pkg.mVersionCode <= ps.versionCode) {
5681                     // The system package has been updated and the code path does not match
5682                     // Ignore entry. Skip it.
5683                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5684                             + " ignored: updated version " + ps.versionCode
5685                             + " better than this " + pkg.mVersionCode);
5686                     if (!updatedPkg.codePath.equals(scanFile)) {
5687                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5688                                 + ps.name + " changing from " + updatedPkg.codePathString
5689                                 + " to " + scanFile);
5690                         updatedPkg.codePath = scanFile;
5691                         updatedPkg.codePathString = scanFile.toString();
5692                         updatedPkg.resourcePath = scanFile;
5693                         updatedPkg.resourcePathString = scanFile.toString();
5694                     }
5695                     updatedPkg.pkg = pkg;
5696                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5697                             "Package " + ps.name + " at " + scanFile
5698                                     + " ignored: updated version " + ps.versionCode
5699                                     + " better than this " + pkg.mVersionCode);
5700                 } else {
5701                     // The current app on the system partition is better than
5702                     // what we have updated to on the data partition; switch
5703                     // back to the system partition version.
5704                     // At this point, its safely assumed that package installation for
5705                     // apps in system partition will go through. If not there won't be a working
5706                     // version of the app
5707                     // writer
5708                     synchronized (mPackages) {
5709                         // Just remove the loaded entries from package lists.
5710                         mPackages.remove(ps.name);
5711                     }
5712
5713                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5714                             + " reverting from " + ps.codePathString
5715                             + ": new version " + pkg.mVersionCode
5716                             + " better than installed " + ps.versionCode);
5717
5718                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5719                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5720                     synchronized (mInstallLock) {
5721                         args.cleanUpResourcesLI();
5722                     }
5723                     synchronized (mPackages) {
5724                         mSettings.enableSystemPackageLPw(ps.name);
5725                     }
5726                     updatedPkgBetter = true;
5727                 }
5728             }
5729         }
5730
5731         if (updatedPkg != null) {
5732             // An updated system app will not have the PARSE_IS_SYSTEM flag set
5733             // initially
5734             parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5735
5736             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5737             // flag set initially
5738             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5739                 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5740             }
5741         }
5742
5743         // Verify certificates against what was last scanned
5744         collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5745
5746         /*
5747          * A new system app appeared, but we already had a non-system one of the
5748          * same name installed earlier.
5749          */
5750         boolean shouldHideSystemApp = false;
5751         if (updatedPkg == null && ps != null
5752                 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5753             /*
5754              * Check to make sure the signatures match first. If they don't,
5755              * wipe the installed application and its data.
5756              */
5757             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5758                     != PackageManager.SIGNATURE_MATCH) {
5759                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5760                         + " signatures don't match existing userdata copy; removing");
5761                 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5762                 ps = null;
5763             } else {
5764                 /*
5765                  * If the newly-added system app is an older version than the
5766                  * already installed version, hide it. It will be scanned later
5767                  * and re-added like an update.
5768                  */
5769                 if (pkg.mVersionCode <= ps.versionCode) {
5770                     shouldHideSystemApp = true;
5771                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5772                             + " but new version " + pkg.mVersionCode + " better than installed "
5773                             + ps.versionCode + "; hiding system");
5774                 } else {
5775                     /*
5776                      * The newly found system app is a newer version that the
5777                      * one previously installed. Simply remove the
5778                      * already-installed application and replace it with our own
5779                      * while keeping the application data.
5780                      */
5781                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5782                             + " reverting from " + ps.codePathString + ": new version "
5783                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
5784                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5785                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5786                     synchronized (mInstallLock) {
5787                         args.cleanUpResourcesLI();
5788                     }
5789                 }
5790             }
5791         }
5792
5793         // The apk is forward locked (not public) if its code and resources
5794         // are kept in different files. (except for app in either system or
5795         // vendor path).
5796         // TODO grab this value from PackageSettings
5797         if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5798             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5799                 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5800             }
5801         }
5802
5803         // TODO: extend to support forward-locked splits
5804         String resourcePath = null;
5805         String baseResourcePath = null;
5806         if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5807             if (ps != null && ps.resourcePathString != null) {
5808                 resourcePath = ps.resourcePathString;
5809                 baseResourcePath = ps.resourcePathString;
5810             } else {
5811                 // Should not happen at all. Just log an error.
5812                 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5813             }
5814         } else {
5815             resourcePath = pkg.codePath;
5816             baseResourcePath = pkg.baseCodePath;
5817         }
5818
5819         // Set application objects path explicitly.
5820         pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5821         pkg.applicationInfo.setCodePath(pkg.codePath);
5822         pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5823         pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5824         pkg.applicationInfo.setResourcePath(resourcePath);
5825         pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5826         pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5827
5828         // Note that we invoke the following method only if we are about to unpack an application
5829         PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5830                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
5831
5832         /*
5833          * If the system app should be overridden by a previously installed
5834          * data, hide the system app now and let the /data/app scan pick it up
5835          * again.
5836          */
5837         if (shouldHideSystemApp) {
5838             synchronized (mPackages) {
5839                 /*
5840                  * We have to grant systems permissions before we hide, because
5841                  * grantPermissions will assume the package update is trying to
5842                  * expand its permissions.
5843                  */
5844                 grantPermissionsLPw(pkg, true, pkg.packageName);
5845                 mSettings.disableSystemPackageLPw(pkg.packageName);
5846             }
5847         }
5848
5849         return scannedPkg;
5850     }
5851
5852     private static String fixProcessName(String defProcessName,
5853             String processName, int uid) {
5854         if (processName == null) {
5855             return defProcessName;
5856         }
5857         return processName;
5858     }
5859
5860     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5861             throws PackageManagerException {
5862         if (pkgSetting.signatures.mSignatures != null) {
5863             // Already existing package. Make sure signatures match
5864             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5865                     == PackageManager.SIGNATURE_MATCH;
5866             if (!match) {
5867                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5868                         == PackageManager.SIGNATURE_MATCH;
5869             }
5870             if (!match) {
5871                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5872                         == PackageManager.SIGNATURE_MATCH;
5873             }
5874             if (!match) {
5875                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5876                         + pkg.packageName + " signatures do not match the "
5877                         + "previously installed version; ignoring!");
5878             }
5879         }
5880
5881         // Check for shared user signatures
5882         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5883             // Already existing package. Make sure signatures match
5884             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5885                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5886             if (!match) {
5887                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5888                         == PackageManager.SIGNATURE_MATCH;
5889             }
5890             if (!match) {
5891                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5892                         == PackageManager.SIGNATURE_MATCH;
5893             }
5894             if (!match) {
5895                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5896                         "Package " + pkg.packageName
5897                         + " has no signatures that match those in shared user "
5898                         + pkgSetting.sharedUser.name + "; ignoring!");
5899             }
5900         }
5901     }
5902
5903     /**
5904      * Enforces that only the system UID or root's UID can call a method exposed
5905      * via Binder.
5906      *
5907      * @param message used as message if SecurityException is thrown
5908      * @throws SecurityException if the caller is not system or root
5909      */
5910     private static final void enforceSystemOrRoot(String message) {
5911         final int uid = Binder.getCallingUid();
5912         if (uid != Process.SYSTEM_UID && uid != 0) {
5913             throw new SecurityException(message);
5914         }
5915     }
5916
5917     @Override
5918     public void performBootDexOpt() {
5919         enforceSystemOrRoot("Only the system can request dexopt be performed");
5920
5921         // Before everything else, see whether we need to fstrim.
5922         try {
5923             IMountService ms = PackageHelper.getMountService();
5924             if (ms != null) {
5925                 final boolean isUpgrade = isUpgrade();
5926                 boolean doTrim = isUpgrade;
5927                 if (doTrim) {
5928                     Slog.w(TAG, "Running disk maintenance immediately due to system update");
5929                 } else {
5930                     final long interval = android.provider.Settings.Global.getLong(
5931                             mContext.getContentResolver(),
5932                             android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5933                             DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5934                     if (interval > 0) {
5935                         final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5936                         if (timeSinceLast > interval) {
5937                             doTrim = true;
5938                             Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5939                                     + "; running immediately");
5940                         }
5941                     }
5942                 }
5943                 if (doTrim) {
5944                     if (!isFirstBoot()) {
5945                         try {
5946                             ActivityManagerNative.getDefault().showBootMessage(
5947                                     mContext.getResources().getString(
5948                                             R.string.android_upgrading_fstrim), true);
5949                         } catch (RemoteException e) {
5950                         }
5951                     }
5952                     ms.runMaintenance();
5953                 }
5954             } else {
5955                 Slog.e(TAG, "Mount service unavailable!");
5956             }
5957         } catch (RemoteException e) {
5958             // Can't happen; MountService is local
5959         }
5960
5961         final ArraySet<PackageParser.Package> pkgs;
5962         synchronized (mPackages) {
5963             pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5964         }
5965
5966         if (pkgs != null) {
5967             // Sort apps by importance for dexopt ordering. Important apps are given more priority
5968             // in case the device runs out of space.
5969             ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5970             // Give priority to core apps.
5971             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5972                 PackageParser.Package pkg = it.next();
5973                 if (pkg.coreApp) {
5974                     if (DEBUG_DEXOPT) {
5975                         Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5976                     }
5977                     sortedPkgs.add(pkg);
5978                     it.remove();
5979                 }
5980             }
5981             // Give priority to system apps that listen for pre boot complete.
5982             Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5983             ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5984             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5985                 PackageParser.Package pkg = it.next();
5986                 if (pkgNames.contains(pkg.packageName)) {
5987                     if (DEBUG_DEXOPT) {
5988                         Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5989                     }
5990                     sortedPkgs.add(pkg);
5991                     it.remove();
5992                 }
5993             }
5994             // Give priority to system apps.
5995             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5996                 PackageParser.Package pkg = it.next();
5997                 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5998                     if (DEBUG_DEXOPT) {
5999                         Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6000                     }
6001                     sortedPkgs.add(pkg);
6002                     it.remove();
6003                 }
6004             }
6005             // Give priority to updated system apps.
6006             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6007                 PackageParser.Package pkg = it.next();
6008                 if (pkg.isUpdatedSystemApp()) {
6009                     if (DEBUG_DEXOPT) {
6010                         Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6011                     }
6012                     sortedPkgs.add(pkg);
6013                     it.remove();
6014                 }
6015             }
6016             // Give priority to apps that listen for boot complete.
6017             intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6018             pkgNames = getPackageNamesForIntent(intent);
6019             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6020                 PackageParser.Package pkg = it.next();
6021                 if (pkgNames.contains(pkg.packageName)) {
6022                     if (DEBUG_DEXOPT) {
6023                         Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6024                     }
6025                     sortedPkgs.add(pkg);
6026                     it.remove();
6027                 }
6028             }
6029             // Filter out packages that aren't recently used.
6030             filterRecentlyUsedApps(pkgs);
6031             // Add all remaining apps.
6032             for (PackageParser.Package pkg : pkgs) {
6033                 if (DEBUG_DEXOPT) {
6034                     Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6035                 }
6036                 sortedPkgs.add(pkg);
6037             }
6038
6039             // If we want to be lazy, filter everything that wasn't recently used.
6040             if (mLazyDexOpt) {
6041                 filterRecentlyUsedApps(sortedPkgs);
6042             }
6043
6044             int i = 0;
6045             int total = sortedPkgs.size();
6046             File dataDir = Environment.getDataDirectory();
6047             long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6048             if (lowThreshold == 0) {
6049                 throw new IllegalStateException("Invalid low memory threshold");
6050             }
6051             for (PackageParser.Package pkg : sortedPkgs) {
6052                 long usableSpace = dataDir.getUsableSpace();
6053                 if (usableSpace < lowThreshold) {
6054                     Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6055                     break;
6056                 }
6057                 performBootDexOpt(pkg, ++i, total);
6058             }
6059         }
6060     }
6061
6062     private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6063         // Filter out packages that aren't recently used.
6064         //
6065         // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6066         // should do a full dexopt.
6067         if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6068             int total = pkgs.size();
6069             int skipped = 0;
6070             long now = System.currentTimeMillis();
6071             for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6072                 PackageParser.Package pkg = i.next();
6073                 long then = pkg.mLastPackageUsageTimeInMills;
6074                 if (then + mDexOptLRUThresholdInMills < now) {
6075                     if (DEBUG_DEXOPT) {
6076                         Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6077                               ((then == 0) ? "never" : new Date(then)));
6078                     }
6079                     i.remove();
6080                     skipped++;
6081                 }
6082             }
6083             if (DEBUG_DEXOPT) {
6084                 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6085             }
6086         }
6087     }
6088
6089     private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6090         List<ResolveInfo> ris = null;
6091         try {
6092             ris = AppGlobals.getPackageManager().queryIntentReceivers(
6093                     intent, null, 0, UserHandle.USER_OWNER);
6094         } catch (RemoteException e) {
6095         }
6096         ArraySet<String> pkgNames = new ArraySet<String>();
6097         if (ris != null) {
6098             for (ResolveInfo ri : ris) {
6099                 pkgNames.add(ri.activityInfo.packageName);
6100             }
6101         }
6102         return pkgNames;
6103     }
6104
6105     private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6106         if (DEBUG_DEXOPT) {
6107             Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6108         }
6109         if (!isFirstBoot()) {
6110             try {
6111                 ActivityManagerNative.getDefault().showBootMessage(
6112                         mContext.getResources().getString(R.string.android_upgrading_apk,
6113                                 curr, total), true);
6114             } catch (RemoteException e) {
6115             }
6116         }
6117         PackageParser.Package p = pkg;
6118         synchronized (mInstallLock) {
6119             mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6120                     false /* force dex */, false /* defer */, true /* include dependencies */);
6121         }
6122     }
6123
6124     @Override
6125     public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6126         return performDexOpt(packageName, instructionSet, false);
6127     }
6128
6129     public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6130         boolean dexopt = mLazyDexOpt || backgroundDexopt;
6131         boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6132         if (!dexopt && !updateUsage) {
6133             // We aren't going to dexopt or update usage, so bail early.
6134             return false;
6135         }
6136         PackageParser.Package p;
6137         final String targetInstructionSet;
6138         synchronized (mPackages) {
6139             p = mPackages.get(packageName);
6140             if (p == null) {
6141                 return false;
6142             }
6143             if (updateUsage) {
6144                 p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6145             }
6146             mPackageUsage.write(false);
6147             if (!dexopt) {
6148                 // We aren't going to dexopt, so bail early.
6149                 return false;
6150             }
6151
6152             targetInstructionSet = instructionSet != null ? instructionSet :
6153                     getPrimaryInstructionSet(p.applicationInfo);
6154             if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6155                 return false;
6156             }
6157         }
6158
6159         synchronized (mInstallLock) {
6160             final String[] instructionSets = new String[] { targetInstructionSet };
6161             int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6162                     false /* forceDex */, false /* defer */, true /* inclDependencies */);
6163             return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6164         }
6165     }
6166
6167     public ArraySet<String> getPackagesThatNeedDexOpt() {
6168         ArraySet<String> pkgs = null;
6169         synchronized (mPackages) {
6170             for (PackageParser.Package p : mPackages.values()) {
6171                 if (DEBUG_DEXOPT) {
6172                     Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6173                 }
6174                 if (!p.mDexOptPerformed.isEmpty()) {
6175                     continue;
6176                 }
6177                 if (pkgs == null) {
6178                     pkgs = new ArraySet<String>();
6179                 }
6180                 pkgs.add(p.packageName);
6181             }
6182         }
6183         return pkgs;
6184     }
6185
6186     public void shutdown() {
6187         mPackageUsage.write(true);
6188     }
6189
6190     @Override
6191     public void forceDexOpt(String packageName) {
6192         enforceSystemOrRoot("forceDexOpt");
6193
6194         PackageParser.Package pkg;
6195         synchronized (mPackages) {
6196             pkg = mPackages.get(packageName);
6197             if (pkg == null) {
6198                 throw new IllegalArgumentException("Missing package: " + packageName);
6199             }
6200         }
6201
6202         synchronized (mInstallLock) {
6203             final String[] instructionSets = new String[] {
6204                     getPrimaryInstructionSet(pkg.applicationInfo) };
6205             final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6206                     true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6207             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6208                 throw new IllegalStateException("Failed to dexopt: " + res);
6209             }
6210         }
6211     }
6212
6213     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6214         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6215             Slog.w(TAG, "Unable to update from " + oldPkg.name
6216                     + " to " + newPkg.packageName
6217                     + ": old package not in system partition");
6218             return false;
6219         } else if (mPackages.get(oldPkg.name) != null) {
6220             Slog.w(TAG, "Unable to update from " + oldPkg.name
6221                     + " to " + newPkg.packageName
6222                     + ": old package still exists");
6223             return false;
6224         }
6225         return true;
6226     }
6227
6228     private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6229         int[] users = sUserManager.getUserIds();
6230         int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6231         if (res < 0) {
6232             return res;
6233         }
6234         for (int user : users) {
6235             if (user != 0) {
6236                 res = mInstaller.createUserData(volumeUuid, packageName,
6237                         UserHandle.getUid(user, uid), user, seinfo);
6238                 if (res < 0) {
6239                     return res;
6240                 }
6241             }
6242         }
6243         return res;
6244     }
6245
6246     private int removeDataDirsLI(String volumeUuid, String packageName) {
6247         int[] users = sUserManager.getUserIds();
6248         int res = 0;
6249         for (int user : users) {
6250             int resInner = mInstaller.remove(volumeUuid, packageName, user);
6251             if (resInner < 0) {
6252                 res = resInner;
6253             }
6254         }
6255
6256         return res;
6257     }
6258
6259     private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6260         int[] users = sUserManager.getUserIds();
6261         int res = 0;
6262         for (int user : users) {
6263             int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6264             if (resInner < 0) {
6265                 res = resInner;
6266             }
6267         }
6268         return res;
6269     }
6270
6271     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6272             PackageParser.Package changingLib) {
6273         if (file.path != null) {
6274             usesLibraryFiles.add(file.path);
6275             return;
6276         }
6277         PackageParser.Package p = mPackages.get(file.apk);
6278         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6279             // If we are doing this while in the middle of updating a library apk,
6280             // then we need to make sure to use that new apk for determining the
6281             // dependencies here.  (We haven't yet finished committing the new apk
6282             // to the package manager state.)
6283             if (p == null || p.packageName.equals(changingLib.packageName)) {
6284                 p = changingLib;
6285             }
6286         }
6287         if (p != null) {
6288             usesLibraryFiles.addAll(p.getAllCodePaths());
6289         }
6290     }
6291
6292     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6293             PackageParser.Package changingLib) throws PackageManagerException {
6294         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6295             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6296             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6297             for (int i=0; i<N; i++) {
6298                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6299                 if (file == null) {
6300                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6301                             "Package " + pkg.packageName + " requires unavailable shared library "
6302                             + pkg.usesLibraries.get(i) + "; failing!");
6303                 }
6304                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6305             }
6306             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6307             for (int i=0; i<N; i++) {
6308                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6309                 if (file == null) {
6310                     Slog.w(TAG, "Package " + pkg.packageName
6311                             + " desires unavailable shared library "
6312                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6313                 } else {
6314                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6315                 }
6316             }
6317             N = usesLibraryFiles.size();
6318             if (N > 0) {
6319                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6320             } else {
6321                 pkg.usesLibraryFiles = null;
6322             }
6323         }
6324     }
6325
6326     private static boolean hasString(List<String> list, List<String> which) {
6327         if (list == null) {
6328             return false;
6329         }
6330         for (int i=list.size()-1; i>=0; i--) {
6331             for (int j=which.size()-1; j>=0; j--) {
6332                 if (which.get(j).equals(list.get(i))) {
6333                     return true;
6334                 }
6335             }
6336         }
6337         return false;
6338     }
6339
6340     private void updateAllSharedLibrariesLPw() {
6341         for (PackageParser.Package pkg : mPackages.values()) {
6342             try {
6343                 updateSharedLibrariesLPw(pkg, null);
6344             } catch (PackageManagerException e) {
6345                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6346             }
6347         }
6348     }
6349
6350     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6351             PackageParser.Package changingPkg) {
6352         ArrayList<PackageParser.Package> res = null;
6353         for (PackageParser.Package pkg : mPackages.values()) {
6354             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6355                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6356                 if (res == null) {
6357                     res = new ArrayList<PackageParser.Package>();
6358                 }
6359                 res.add(pkg);
6360                 try {
6361                     updateSharedLibrariesLPw(pkg, changingPkg);
6362                 } catch (PackageManagerException e) {
6363                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6364                 }
6365             }
6366         }
6367         return res;
6368     }
6369
6370     /**
6371      * Derive the value of the {@code cpuAbiOverride} based on the provided
6372      * value and an optional stored value from the package settings.
6373      */
6374     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6375         String cpuAbiOverride = null;
6376
6377         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6378             cpuAbiOverride = null;
6379         } else if (abiOverride != null) {
6380             cpuAbiOverride = abiOverride;
6381         } else if (settings != null) {
6382             cpuAbiOverride = settings.cpuAbiOverrideString;
6383         }
6384
6385         return cpuAbiOverride;
6386     }
6387
6388     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6389             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6390         boolean success = false;
6391         try {
6392             final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6393                     currentTime, user);
6394             success = true;
6395             return res;
6396         } finally {
6397             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6398                 removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6399             }
6400         }
6401     }
6402
6403     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6404             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6405         final File scanFile = new File(pkg.codePath);
6406         if (pkg.applicationInfo.getCodePath() == null ||
6407                 pkg.applicationInfo.getResourcePath() == null) {
6408             // Bail out. The resource and code paths haven't been set.
6409             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6410                     "Code and resource paths haven't been set correctly");
6411         }
6412
6413         if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6414             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6415         } else {
6416             // Only allow system apps to be flagged as core apps.
6417             pkg.coreApp = false;
6418         }
6419
6420         if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6421             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6422         }
6423
6424         if (mCustomResolverComponentName != null &&
6425                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6426             setUpCustomResolverActivity(pkg);
6427         }
6428
6429         if (pkg.packageName.equals("android")) {
6430             synchronized (mPackages) {
6431                 if (mAndroidApplication != null) {
6432                     Slog.w(TAG, "*************************************************");
6433                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
6434                     Slog.w(TAG, " file=" + scanFile);
6435                     Slog.w(TAG, "*************************************************");
6436                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6437                             "Core android package being redefined.  Skipping.");
6438                 }
6439
6440                 // Set up information for our fall-back user intent resolution activity.
6441                 mPlatformPackage = pkg;
6442                 pkg.mVersionCode = mSdkVersion;
6443                 mAndroidApplication = pkg.applicationInfo;
6444
6445                 if (!mResolverReplaced) {
6446                     mResolveActivity.applicationInfo = mAndroidApplication;
6447                     mResolveActivity.name = ResolverActivity.class.getName();
6448                     mResolveActivity.packageName = mAndroidApplication.packageName;
6449                     mResolveActivity.processName = "system:ui";
6450                     mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6451                     mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6452                     mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6453                     mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6454                     mResolveActivity.exported = true;
6455                     mResolveActivity.enabled = true;
6456                     mResolveInfo.activityInfo = mResolveActivity;
6457                     mResolveInfo.priority = 0;
6458                     mResolveInfo.preferredOrder = 0;
6459                     mResolveInfo.match = 0;
6460                     mResolveComponentName = new ComponentName(
6461                             mAndroidApplication.packageName, mResolveActivity.name);
6462                 }
6463             }
6464         }
6465
6466         if (DEBUG_PACKAGE_SCANNING) {
6467             if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6468                 Log.d(TAG, "Scanning package " + pkg.packageName);
6469         }
6470
6471         if (mPackages.containsKey(pkg.packageName)
6472                 || mSharedLibraries.containsKey(pkg.packageName)) {
6473             throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6474                     "Application package " + pkg.packageName
6475                     + " already installed.  Skipping duplicate.");
6476         }
6477
6478         // If we're only installing presumed-existing packages, require that the
6479         // scanned APK is both already known and at the path previously established
6480         // for it.  Previously unknown packages we pick up normally, but if we have an
6481         // a priori expectation about this package's install presence, enforce it.
6482         // With a singular exception for new system packages. When an OTA contains
6483         // a new system package, we allow the codepath to change from a system location
6484         // to the user-installed location. If we don't allow this change, any newer,
6485         // user-installed version of the application will be ignored.
6486         if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6487             if (mExpectingBetter.containsKey(pkg.packageName)) {
6488                 logCriticalInfo(Log.WARN,
6489                         "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6490             } else {
6491                 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6492                 if (known != null) {
6493                     if (DEBUG_PACKAGE_SCANNING) {
6494                         Log.d(TAG, "Examining " + pkg.codePath
6495                                 + " and requiring known paths " + known.codePathString
6496                                 + " & " + known.resourcePathString);
6497                     }
6498                     if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6499                             || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6500                         throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6501                                 "Application package " + pkg.packageName
6502                                 + " found at " + pkg.applicationInfo.getCodePath()
6503                                 + " but expected at " + known.codePathString + "; ignoring.");
6504                     }
6505                 }
6506             }
6507         }
6508
6509         // Initialize package source and resource directories
6510         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6511         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6512
6513         SharedUserSetting suid = null;
6514         PackageSetting pkgSetting = null;
6515
6516         if (!isSystemApp(pkg)) {
6517             // Only system apps can use these features.
6518             pkg.mOriginalPackages = null;
6519             pkg.mRealPackage = null;
6520             pkg.mAdoptPermissions = null;
6521         }
6522
6523         // writer
6524         synchronized (mPackages) {
6525             if (pkg.mSharedUserId != null) {
6526                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6527                 if (suid == null) {
6528                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6529                             "Creating application package " + pkg.packageName
6530                             + " for shared user failed");
6531                 }
6532                 if (DEBUG_PACKAGE_SCANNING) {
6533                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6534                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6535                                 + "): packages=" + suid.packages);
6536                 }
6537             }
6538
6539             // Check if we are renaming from an original package name.
6540             PackageSetting origPackage = null;
6541             String realName = null;
6542             if (pkg.mOriginalPackages != null) {
6543                 // This package may need to be renamed to a previously
6544                 // installed name.  Let's check on that...
6545                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6546                 if (pkg.mOriginalPackages.contains(renamed)) {
6547                     // This package had originally been installed as the
6548                     // original name, and we have already taken care of
6549                     // transitioning to the new one.  Just update the new
6550                     // one to continue using the old name.
6551                     realName = pkg.mRealPackage;
6552                     if (!pkg.packageName.equals(renamed)) {
6553                         // Callers into this function may have already taken
6554                         // care of renaming the package; only do it here if
6555                         // it is not already done.
6556                         pkg.setPackageName(renamed);
6557                     }
6558
6559                 } else {
6560                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6561                         if ((origPackage = mSettings.peekPackageLPr(
6562                                 pkg.mOriginalPackages.get(i))) != null) {
6563                             // We do have the package already installed under its
6564                             // original name...  should we use it?
6565                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6566                                 // New package is not compatible with original.
6567                                 origPackage = null;
6568                                 continue;
6569                             } else if (origPackage.sharedUser != null) {
6570                                 // Make sure uid is compatible between packages.
6571                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6572                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6573                                             + " to " + pkg.packageName + ": old uid "
6574                                             + origPackage.sharedUser.name
6575                                             + " differs from " + pkg.mSharedUserId);
6576                                     origPackage = null;
6577                                     continue;
6578                                 }
6579                             } else {
6580                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6581                                         + pkg.packageName + " to old name " + origPackage.name);
6582                             }
6583                             break;
6584                         }
6585                     }
6586                 }
6587             }
6588
6589             if (mTransferedPackages.contains(pkg.packageName)) {
6590                 Slog.w(TAG, "Package " + pkg.packageName
6591                         + " was transferred to another, but its .apk remains");
6592             }
6593
6594             // Just create the setting, don't add it yet. For already existing packages
6595             // the PkgSetting exists already and doesn't have to be created.
6596             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6597                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6598                     pkg.applicationInfo.primaryCpuAbi,
6599                     pkg.applicationInfo.secondaryCpuAbi,
6600                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6601                     user, false);
6602             if (pkgSetting == null) {
6603                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6604                         "Creating application package " + pkg.packageName + " failed");
6605             }
6606
6607             if (pkgSetting.origPackage != null) {
6608                 // If we are first transitioning from an original package,
6609                 // fix up the new package's name now.  We need to do this after
6610                 // looking up the package under its new name, so getPackageLP
6611                 // can take care of fiddling things correctly.
6612                 pkg.setPackageName(origPackage.name);
6613
6614                 // File a report about this.
6615                 String msg = "New package " + pkgSetting.realName
6616                         + " renamed to replace old package " + pkgSetting.name;
6617                 reportSettingsProblem(Log.WARN, msg);
6618
6619                 // Make a note of it.
6620                 mTransferedPackages.add(origPackage.name);
6621
6622                 // No longer need to retain this.
6623                 pkgSetting.origPackage = null;
6624             }
6625
6626             if (realName != null) {
6627                 // Make a note of it.
6628                 mTransferedPackages.add(pkg.packageName);
6629             }
6630
6631             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6632                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6633             }
6634
6635             if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6636                 // Check all shared libraries and map to their actual file path.
6637                 // We only do this here for apps not on a system dir, because those
6638                 // are the only ones that can fail an install due to this.  We
6639                 // will take care of the system apps by updating all of their
6640                 // library paths after the scan is done.
6641                 updateSharedLibrariesLPw(pkg, null);
6642             }
6643
6644             if (mFoundPolicyFile) {
6645                 SELinuxMMAC.assignSeinfoValue(pkg);
6646             }
6647
6648             pkg.applicationInfo.uid = pkgSetting.appId;
6649             pkg.mExtras = pkgSetting;
6650             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6651                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6652                     // We just determined the app is signed correctly, so bring
6653                     // over the latest parsed certs.
6654                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6655                 } else {
6656                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6657                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6658                                 "Package " + pkg.packageName + " upgrade keys do not match the "
6659                                 + "previously installed version");
6660                     } else {
6661                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
6662                         String msg = "System package " + pkg.packageName
6663                             + " signature changed; retaining data.";
6664                         reportSettingsProblem(Log.WARN, msg);
6665                     }
6666                 }
6667             } else {
6668                 try {
6669                     verifySignaturesLP(pkgSetting, pkg);
6670                     // We just determined the app is signed correctly, so bring
6671                     // over the latest parsed certs.
6672                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6673                 } catch (PackageManagerException e) {
6674                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6675                         throw e;
6676                     }
6677                     // The signature has changed, but this package is in the system
6678                     // image...  let's recover!
6679                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6680                     // However...  if this package is part of a shared user, but it
6681                     // doesn't match the signature of the shared user, let's fail.
6682                     // What this means is that you can't change the signatures
6683                     // associated with an overall shared user, which doesn't seem all
6684                     // that unreasonable.
6685                     if (pkgSetting.sharedUser != null) {
6686                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6687                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6688                             throw new PackageManagerException(
6689                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6690                                             "Signature mismatch for shared user : "
6691                                             + pkgSetting.sharedUser);
6692                         }
6693                     }
6694                     // File a report about this.
6695                     String msg = "System package " + pkg.packageName
6696                         + " signature changed; retaining data.";
6697                     reportSettingsProblem(Log.WARN, msg);
6698                 }
6699             }
6700             // Verify that this new package doesn't have any content providers
6701             // that conflict with existing packages.  Only do this if the
6702             // package isn't already installed, since we don't want to break
6703             // things that are installed.
6704             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6705                 final int N = pkg.providers.size();
6706                 int i;
6707                 for (i=0; i<N; i++) {
6708                     PackageParser.Provider p = pkg.providers.get(i);
6709                     if (p.info.authority != null) {
6710                         String names[] = p.info.authority.split(";");
6711                         for (int j = 0; j < names.length; j++) {
6712                             if (mProvidersByAuthority.containsKey(names[j])) {
6713                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6714                                 final String otherPackageName =
6715                                         ((other != null && other.getComponentName() != null) ?
6716                                                 other.getComponentName().getPackageName() : "?");
6717                                 throw new PackageManagerException(
6718                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
6719                                                 "Can't install because provider name " + names[j]
6720                                                 + " (in package " + pkg.applicationInfo.packageName
6721                                                 + ") is already used by " + otherPackageName);
6722                             }
6723                         }
6724                     }
6725                 }
6726             }
6727
6728             if (pkg.mAdoptPermissions != null) {
6729                 // This package wants to adopt ownership of permissions from
6730                 // another package.
6731                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6732                     final String origName = pkg.mAdoptPermissions.get(i);
6733                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
6734                     if (orig != null) {
6735                         if (verifyPackageUpdateLPr(orig, pkg)) {
6736                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
6737                                     + pkg.packageName);
6738                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
6739                         }
6740                     }
6741                 }
6742             }
6743         }
6744
6745         final String pkgName = pkg.packageName;
6746
6747         final long scanFileTime = scanFile.lastModified();
6748         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6749         pkg.applicationInfo.processName = fixProcessName(
6750                 pkg.applicationInfo.packageName,
6751                 pkg.applicationInfo.processName,
6752                 pkg.applicationInfo.uid);
6753
6754         File dataPath;
6755         if (mPlatformPackage == pkg) {
6756             // The system package is special.
6757             dataPath = new File(Environment.getDataDirectory(), "system");
6758
6759             pkg.applicationInfo.dataDir = dataPath.getPath();
6760
6761         } else {
6762             // This is a normal package, need to make its data directory.
6763             dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6764                     UserHandle.USER_OWNER, pkg.packageName);
6765
6766             boolean uidError = false;
6767             if (dataPath.exists()) {
6768                 int currentUid = 0;
6769                 try {
6770                     StructStat stat = Os.stat(dataPath.getPath());
6771                     currentUid = stat.st_uid;
6772                 } catch (ErrnoException e) {
6773                     Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6774                 }
6775
6776                 // If we have mismatched owners for the data path, we have a problem.
6777                 if (currentUid != pkg.applicationInfo.uid) {
6778                     boolean recovered = false;
6779                     if (currentUid == 0) {
6780                         // The directory somehow became owned by root.  Wow.
6781                         // This is probably because the system was stopped while
6782                         // installd was in the middle of messing with its libs
6783                         // directory.  Ask installd to fix that.
6784                         int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6785                                 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6786                         if (ret >= 0) {
6787                             recovered = true;
6788                             String msg = "Package " + pkg.packageName
6789                                     + " unexpectedly changed to uid 0; recovered to " +
6790                                     + pkg.applicationInfo.uid;
6791                             reportSettingsProblem(Log.WARN, msg);
6792                         }
6793                     }
6794                     if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6795                             || (scanFlags&SCAN_BOOTING) != 0)) {
6796                         // If this is a system app, we can at least delete its
6797                         // current data so the application will still work.
6798                         int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6799                         if (ret >= 0) {
6800                             // TODO: Kill the processes first
6801                             // Old data gone!
6802                             String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6803                                     ? "System package " : "Third party package ";
6804                             String msg = prefix + pkg.packageName
6805                                     + " has changed from uid: "
6806                                     + currentUid + " to "
6807                                     + pkg.applicationInfo.uid + "; old data erased";
6808                             reportSettingsProblem(Log.WARN, msg);
6809                             recovered = true;
6810
6811                             // And now re-install the app.
6812                             ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6813                                     pkg.applicationInfo.seinfo);
6814                             if (ret == -1) {
6815                                 // Ack should not happen!
6816                                 msg = prefix + pkg.packageName
6817                                         + " could not have data directory re-created after delete.";
6818                                 reportSettingsProblem(Log.WARN, msg);
6819                                 throw new PackageManagerException(
6820                                         INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6821                             }
6822                         }
6823                         if (!recovered) {
6824                             mHasSystemUidErrors = true;
6825                         }
6826                     } else if (!recovered) {
6827                         // If we allow this install to proceed, we will be broken.
6828                         // Abort, abort!
6829                         throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6830                                 "scanPackageLI");
6831                     }
6832                     if (!recovered) {
6833                         pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6834                             + pkg.applicationInfo.uid + "/fs_"
6835                             + currentUid;
6836                         pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6837                         pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6838                         String msg = "Package " + pkg.packageName
6839                                 + " has mismatched uid: "
6840                                 + currentUid + " on disk, "
6841                                 + pkg.applicationInfo.uid + " in settings";
6842                         // writer
6843                         synchronized (mPackages) {
6844                             mSettings.mReadMessages.append(msg);
6845                             mSettings.mReadMessages.append('\n');
6846                             uidError = true;
6847                             if (!pkgSetting.uidError) {
6848                                 reportSettingsProblem(Log.ERROR, msg);
6849                             }
6850                         }
6851                     }
6852                 }
6853                 pkg.applicationInfo.dataDir = dataPath.getPath();
6854                 if (mShouldRestoreconData) {
6855                     Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6856                     mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6857                             pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6858                 }
6859             } else {
6860                 if (DEBUG_PACKAGE_SCANNING) {
6861                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6862                         Log.v(TAG, "Want this data dir: " + dataPath);
6863                 }
6864                 //invoke installer to do the actual installation
6865                 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6866                         pkg.applicationInfo.seinfo);
6867                 if (ret < 0) {
6868                     // Error from installer
6869                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6870                             "Unable to create data dirs [errorCode=" + ret + "]");
6871                 }
6872
6873                 if (dataPath.exists()) {
6874                     pkg.applicationInfo.dataDir = dataPath.getPath();
6875                 } else {
6876                     Slog.w(TAG, "Unable to create data directory: " + dataPath);
6877                     pkg.applicationInfo.dataDir = null;
6878                 }
6879             }
6880
6881             pkgSetting.uidError = uidError;
6882         }
6883
6884         final String path = scanFile.getPath();
6885         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6886
6887         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6888             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6889
6890             // Some system apps still use directory structure for native libraries
6891             // in which case we might end up not detecting abi solely based on apk
6892             // structure. Try to detect abi based on directory structure.
6893             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6894                     pkg.applicationInfo.primaryCpuAbi == null) {
6895                 setBundledAppAbisAndRoots(pkg, pkgSetting);
6896                 setNativeLibraryPaths(pkg);
6897             }
6898
6899         } else {
6900             if ((scanFlags & SCAN_MOVE) != 0) {
6901                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
6902                 // but we already have this packages package info in the PackageSetting. We just
6903                 // use that and derive the native library path based on the new codepath.
6904                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6905                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6906             }
6907
6908             // Set native library paths again. For moves, the path will be updated based on the
6909             // ABIs we've determined above. For non-moves, the path will be updated based on the
6910             // ABIs we determined during compilation, but the path will depend on the final
6911             // package path (after the rename away from the stage path).
6912             setNativeLibraryPaths(pkg);
6913         }
6914
6915         if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6916         final int[] userIds = sUserManager.getUserIds();
6917         synchronized (mInstallLock) {
6918             // Make sure all user data directories are ready to roll; we're okay
6919             // if they already exist
6920             if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6921                 for (int userId : userIds) {
6922                     if (userId != 0) {
6923                         mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6924                                 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6925                                 pkg.applicationInfo.seinfo);
6926                     }
6927                 }
6928             }
6929
6930             // Create a native library symlink only if we have native libraries
6931             // and if the native libraries are 32 bit libraries. We do not provide
6932             // this symlink for 64 bit libraries.
6933             if (pkg.applicationInfo.primaryCpuAbi != null &&
6934                     !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6935                 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6936                 for (int userId : userIds) {
6937                     if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6938                             nativeLibPath, userId) < 0) {
6939                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6940                                 "Failed linking native library dir (user=" + userId + ")");
6941                     }
6942                 }
6943             }
6944         }
6945
6946         // This is a special case for the "system" package, where the ABI is
6947         // dictated by the zygote configuration (and init.rc). We should keep track
6948         // of this ABI so that we can deal with "normal" applications that run under
6949         // the same UID correctly.
6950         if (mPlatformPackage == pkg) {
6951             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6952                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6953         }
6954
6955         // If there's a mismatch between the abi-override in the package setting
6956         // and the abiOverride specified for the install. Warn about this because we
6957         // would've already compiled the app without taking the package setting into
6958         // account.
6959         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6960             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6961                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6962                         " for package: " + pkg.packageName);
6963             }
6964         }
6965
6966         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6967         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6968         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6969
6970         // Copy the derived override back to the parsed package, so that we can
6971         // update the package settings accordingly.
6972         pkg.cpuAbiOverride = cpuAbiOverride;
6973
6974         if (DEBUG_ABI_SELECTION) {
6975             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6976                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6977                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6978         }
6979
6980         // Push the derived path down into PackageSettings so we know what to
6981         // clean up at uninstall time.
6982         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6983
6984         if (DEBUG_ABI_SELECTION) {
6985             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6986                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
6987                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6988         }
6989
6990         if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6991             // We don't do this here during boot because we can do it all
6992             // at once after scanning all existing packages.
6993             //
6994             // We also do this *before* we perform dexopt on this package, so that
6995             // we can avoid redundant dexopts, and also to make sure we've got the
6996             // code and package path correct.
6997             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6998                     pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6999         }
7000
7001         if ((scanFlags & SCAN_NO_DEX) == 0) {
7002             int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7003                     forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7004             if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7005                 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7006             }
7007         }
7008         if (mFactoryTest && pkg.requestedPermissions.contains(
7009                 android.Manifest.permission.FACTORY_TEST)) {
7010             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7011         }
7012
7013         ArrayList<PackageParser.Package> clientLibPkgs = null;
7014
7015         // writer
7016         synchronized (mPackages) {
7017             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7018                 // Only system apps can add new shared libraries.
7019                 if (pkg.libraryNames != null) {
7020                     for (int i=0; i<pkg.libraryNames.size(); i++) {
7021                         String name = pkg.libraryNames.get(i);
7022                         boolean allowed = false;
7023                         if (pkg.isUpdatedSystemApp()) {
7024                             // New library entries can only be added through the
7025                             // system image.  This is important to get rid of a lot
7026                             // of nasty edge cases: for example if we allowed a non-
7027                             // system update of the app to add a library, then uninstalling
7028                             // the update would make the library go away, and assumptions
7029                             // we made such as through app install filtering would now
7030                             // have allowed apps on the device which aren't compatible
7031                             // with it.  Better to just have the restriction here, be
7032                             // conservative, and create many fewer cases that can negatively
7033                             // impact the user experience.
7034                             final PackageSetting sysPs = mSettings
7035                                     .getDisabledSystemPkgLPr(pkg.packageName);
7036                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7037                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7038                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7039                                         allowed = true;
7040                                         allowed = true;
7041                                         break;
7042                                     }
7043                                 }
7044                             }
7045                         } else {
7046                             allowed = true;
7047                         }
7048                         if (allowed) {
7049                             if (!mSharedLibraries.containsKey(name)) {
7050                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7051                             } else if (!name.equals(pkg.packageName)) {
7052                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
7053                                         + name + " already exists; skipping");
7054                             }
7055                         } else {
7056                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7057                                     + name + " that is not declared on system image; skipping");
7058                         }
7059                     }
7060                     if ((scanFlags&SCAN_BOOTING) == 0) {
7061                         // If we are not booting, we need to update any applications
7062                         // that are clients of our shared library.  If we are booting,
7063                         // this will all be done once the scan is complete.
7064                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7065                     }
7066                 }
7067             }
7068         }
7069
7070         // We also need to dexopt any apps that are dependent on this library.  Note that
7071         // if these fail, we should abort the install since installing the library will
7072         // result in some apps being broken.
7073         if (clientLibPkgs != null) {
7074             if ((scanFlags & SCAN_NO_DEX) == 0) {
7075                 for (int i = 0; i < clientLibPkgs.size(); i++) {
7076                     PackageParser.Package clientPkg = clientLibPkgs.get(i);
7077                     int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7078                             null /* instruction sets */, forceDex,
7079                             (scanFlags & SCAN_DEFER_DEX) != 0, false);
7080                     if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7081                         throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7082                                 "scanPackageLI failed to dexopt clientLibPkgs");
7083                     }
7084                 }
7085             }
7086         }
7087
7088         // Also need to kill any apps that are dependent on the library.
7089         if (clientLibPkgs != null) {
7090             for (int i=0; i<clientLibPkgs.size(); i++) {
7091                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
7092                 killApplication(clientPkg.applicationInfo.packageName,
7093                         clientPkg.applicationInfo.uid, "update lib");
7094             }
7095         }
7096
7097         // Make sure we're not adding any bogus keyset info
7098         KeySetManagerService ksms = mSettings.mKeySetManagerService;
7099         ksms.assertScannedPackageValid(pkg);
7100
7101         // writer
7102         synchronized (mPackages) {
7103             // We don't expect installation to fail beyond this point
7104
7105             // Add the new setting to mSettings
7106             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7107             // Add the new setting to mPackages
7108             mPackages.put(pkg.applicationInfo.packageName, pkg);
7109             // Make sure we don't accidentally delete its data.
7110             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7111             while (iter.hasNext()) {
7112                 PackageCleanItem item = iter.next();
7113                 if (pkgName.equals(item.packageName)) {
7114                     iter.remove();
7115                 }
7116             }
7117
7118             // Take care of first install / last update times.
7119             if (currentTime != 0) {
7120                 if (pkgSetting.firstInstallTime == 0) {
7121                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7122                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7123                     pkgSetting.lastUpdateTime = currentTime;
7124                 }
7125             } else if (pkgSetting.firstInstallTime == 0) {
7126                 // We need *something*.  Take time time stamp of the file.
7127                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7128             } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7129                 if (scanFileTime != pkgSetting.timeStamp) {
7130                     // A package on the system image has changed; consider this
7131                     // to be an update.
7132                     pkgSetting.lastUpdateTime = scanFileTime;
7133                 }
7134             }
7135
7136             // Add the package's KeySets to the global KeySetManagerService
7137             ksms.addScannedPackageLPw(pkg);
7138
7139             int N = pkg.providers.size();
7140             StringBuilder r = null;
7141             int i;
7142             for (i=0; i<N; i++) {
7143                 PackageParser.Provider p = pkg.providers.get(i);
7144                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7145                         p.info.processName, pkg.applicationInfo.uid);
7146                 mProviders.addProvider(p);
7147                 p.syncable = p.info.isSyncable;
7148                 if (p.info.authority != null) {
7149                     String names[] = p.info.authority.split(";");
7150                     p.info.authority = null;
7151                     for (int j = 0; j < names.length; j++) {
7152                         if (j == 1 && p.syncable) {
7153                             // We only want the first authority for a provider to possibly be
7154                             // syncable, so if we already added this provider using a different
7155                             // authority clear the syncable flag. We copy the provider before
7156                             // changing it because the mProviders object contains a reference
7157                             // to a provider that we don't want to change.
7158                             // Only do this for the second authority since the resulting provider
7159                             // object can be the same for all future authorities for this provider.
7160                             p = new PackageParser.Provider(p);
7161                             p.syncable = false;
7162                         }
7163                         if (!mProvidersByAuthority.containsKey(names[j])) {
7164                             mProvidersByAuthority.put(names[j], p);
7165                             if (p.info.authority == null) {
7166                                 p.info.authority = names[j];
7167                             } else {
7168                                 p.info.authority = p.info.authority + ";" + names[j];
7169                             }
7170                             if (DEBUG_PACKAGE_SCANNING) {
7171                                 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7172                                     Log.d(TAG, "Registered content provider: " + names[j]
7173                                             + ", className = " + p.info.name + ", isSyncable = "
7174                                             + p.info.isSyncable);
7175                             }
7176                         } else {
7177                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7178                             Slog.w(TAG, "Skipping provider name " + names[j] +
7179                                     " (in package " + pkg.applicationInfo.packageName +
7180                                     "): name already used by "
7181                                     + ((other != null && other.getComponentName() != null)
7182                                             ? other.getComponentName().getPackageName() : "?"));
7183                         }
7184                     }
7185                 }
7186                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7187                     if (r == null) {
7188                         r = new StringBuilder(256);
7189                     } else {
7190                         r.append(' ');
7191                     }
7192                     r.append(p.info.name);
7193                 }
7194             }
7195             if (r != null) {
7196                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7197             }
7198
7199             N = pkg.services.size();
7200             r = null;
7201             for (i=0; i<N; i++) {
7202                 PackageParser.Service s = pkg.services.get(i);
7203                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7204                         s.info.processName, pkg.applicationInfo.uid);
7205                 mServices.addService(s);
7206                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7207                     if (r == null) {
7208                         r = new StringBuilder(256);
7209                     } else {
7210                         r.append(' ');
7211                     }
7212                     r.append(s.info.name);
7213                 }
7214             }
7215             if (r != null) {
7216                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7217             }
7218
7219             N = pkg.receivers.size();
7220             r = null;
7221             for (i=0; i<N; i++) {
7222                 PackageParser.Activity a = pkg.receivers.get(i);
7223                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7224                         a.info.processName, pkg.applicationInfo.uid);
7225                 mReceivers.addActivity(a, "receiver");
7226                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7227                     if (r == null) {
7228                         r = new StringBuilder(256);
7229                     } else {
7230                         r.append(' ');
7231                     }
7232                     r.append(a.info.name);
7233                 }
7234             }
7235             if (r != null) {
7236                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7237             }
7238
7239             N = pkg.activities.size();
7240             r = null;
7241             for (i=0; i<N; i++) {
7242                 PackageParser.Activity a = pkg.activities.get(i);
7243                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7244                         a.info.processName, pkg.applicationInfo.uid);
7245                 mActivities.addActivity(a, "activity");
7246                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7247                     if (r == null) {
7248                         r = new StringBuilder(256);
7249                     } else {
7250                         r.append(' ');
7251                     }
7252                     r.append(a.info.name);
7253                 }
7254             }
7255             if (r != null) {
7256                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7257             }
7258
7259             N = pkg.permissionGroups.size();
7260             r = null;
7261             for (i=0; i<N; i++) {
7262                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7263                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7264                 if (cur == null) {
7265                     mPermissionGroups.put(pg.info.name, pg);
7266                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7267                         if (r == null) {
7268                             r = new StringBuilder(256);
7269                         } else {
7270                             r.append(' ');
7271                         }
7272                         r.append(pg.info.name);
7273                     }
7274                 } else {
7275                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7276                             + pg.info.packageName + " ignored: original from "
7277                             + cur.info.packageName);
7278                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7279                         if (r == null) {
7280                             r = new StringBuilder(256);
7281                         } else {
7282                             r.append(' ');
7283                         }
7284                         r.append("DUP:");
7285                         r.append(pg.info.name);
7286                     }
7287                 }
7288             }
7289             if (r != null) {
7290                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7291             }
7292
7293             N = pkg.permissions.size();
7294             r = null;
7295             for (i=0; i<N; i++) {
7296                 PackageParser.Permission p = pkg.permissions.get(i);
7297
7298                 // Now that permission groups have a special meaning, we ignore permission
7299                 // groups for legacy apps to prevent unexpected behavior. In particular,
7300                 // permissions for one app being granted to someone just becuase they happen
7301                 // to be in a group defined by another app (before this had no implications).
7302                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7303                     p.group = mPermissionGroups.get(p.info.group);
7304                     // Warn for a permission in an unknown group.
7305                     if (p.info.group != null && p.group == null) {
7306                         Slog.w(TAG, "Permission " + p.info.name + " from package "
7307                                 + p.info.packageName + " in an unknown group " + p.info.group);
7308                     }
7309                 }
7310
7311                 ArrayMap<String, BasePermission> permissionMap =
7312                         p.tree ? mSettings.mPermissionTrees
7313                                 : mSettings.mPermissions;
7314                 BasePermission bp = permissionMap.get(p.info.name);
7315
7316                 // Allow system apps to redefine non-system permissions
7317                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7318                     final boolean currentOwnerIsSystem = (bp.perm != null
7319                             && isSystemApp(bp.perm.owner));
7320                     if (isSystemApp(p.owner)) {
7321                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7322                             // It's a built-in permission and no owner, take ownership now
7323                             bp.packageSetting = pkgSetting;
7324                             bp.perm = p;
7325                             bp.uid = pkg.applicationInfo.uid;
7326                             bp.sourcePackage = p.info.packageName;
7327                         } else if (!currentOwnerIsSystem) {
7328                             String msg = "New decl " + p.owner + " of permission  "
7329                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
7330                             reportSettingsProblem(Log.WARN, msg);
7331                             bp = null;
7332                         }
7333                     }
7334                 }
7335
7336                 if (bp == null) {
7337                     bp = new BasePermission(p.info.name, p.info.packageName,
7338                             BasePermission.TYPE_NORMAL);
7339                     permissionMap.put(p.info.name, bp);
7340                 }
7341
7342                 if (bp.perm == null) {
7343                     if (bp.sourcePackage == null
7344                             || bp.sourcePackage.equals(p.info.packageName)) {
7345                         BasePermission tree = findPermissionTreeLP(p.info.name);
7346                         if (tree == null
7347                                 || tree.sourcePackage.equals(p.info.packageName)) {
7348                             bp.packageSetting = pkgSetting;
7349                             bp.perm = p;
7350                             bp.uid = pkg.applicationInfo.uid;
7351                             bp.sourcePackage = p.info.packageName;
7352                             if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7353                                 if (r == null) {
7354                                     r = new StringBuilder(256);
7355                                 } else {
7356                                     r.append(' ');
7357                                 }
7358                                 r.append(p.info.name);
7359                             }
7360                         } else {
7361                             Slog.w(TAG, "Permission " + p.info.name + " from package "
7362                                     + p.info.packageName + " ignored: base tree "
7363                                     + tree.name + " is from package "
7364                                     + tree.sourcePackage);
7365                         }
7366                     } else {
7367                         Slog.w(TAG, "Permission " + p.info.name + " from package "
7368                                 + p.info.packageName + " ignored: original from "
7369                                 + bp.sourcePackage);
7370                     }
7371                 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7372                     if (r == null) {
7373                         r = new StringBuilder(256);
7374                     } else {
7375                         r.append(' ');
7376                     }
7377                     r.append("DUP:");
7378                     r.append(p.info.name);
7379                 }
7380                 if (bp.perm == p) {
7381                     bp.protectionLevel = p.info.protectionLevel;
7382                 }
7383             }
7384
7385             if (r != null) {
7386                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7387             }
7388
7389             N = pkg.instrumentation.size();
7390             r = null;
7391             for (i=0; i<N; i++) {
7392                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7393                 a.info.packageName = pkg.applicationInfo.packageName;
7394                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
7395                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7396                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7397                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7398                 a.info.dataDir = pkg.applicationInfo.dataDir;
7399
7400                 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7401                 // need other information about the application, like the ABI and what not ?
7402                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7403                 mInstrumentation.put(a.getComponentName(), a);
7404                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7405                     if (r == null) {
7406                         r = new StringBuilder(256);
7407                     } else {
7408                         r.append(' ');
7409                     }
7410                     r.append(a.info.name);
7411                 }
7412             }
7413             if (r != null) {
7414                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7415             }
7416
7417             if (pkg.protectedBroadcasts != null) {
7418                 N = pkg.protectedBroadcasts.size();
7419                 for (i=0; i<N; i++) {
7420                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7421                 }
7422             }
7423
7424             pkgSetting.setTimeStamp(scanFileTime);
7425
7426             // Create idmap files for pairs of (packages, overlay packages).
7427             // Note: "android", ie framework-res.apk, is handled by native layers.
7428             if (pkg.mOverlayTarget != null) {
7429                 // This is an overlay package.
7430                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7431                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7432                         mOverlays.put(pkg.mOverlayTarget,
7433                                 new ArrayMap<String, PackageParser.Package>());
7434                     }
7435                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7436                     map.put(pkg.packageName, pkg);
7437                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7438                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7439                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7440                                 "scanPackageLI failed to createIdmap");
7441                     }
7442                 }
7443             } else if (mOverlays.containsKey(pkg.packageName) &&
7444                     !pkg.packageName.equals("android")) {
7445                 // This is a regular package, with one or more known overlay packages.
7446                 createIdmapsForPackageLI(pkg);
7447             }
7448         }
7449
7450         return pkg;
7451     }
7452
7453     /**
7454      * Derive the ABI of a non-system package located at {@code scanFile}. This information
7455      * is derived purely on the basis of the contents of {@code scanFile} and
7456      * {@code cpuAbiOverride}.
7457      *
7458      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7459      */
7460     public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7461                                  String cpuAbiOverride, boolean extractLibs)
7462             throws PackageManagerException {
7463         // TODO: We can probably be smarter about this stuff. For installed apps,
7464         // we can calculate this information at install time once and for all. For
7465         // system apps, we can probably assume that this information doesn't change
7466         // after the first boot scan. As things stand, we do lots of unnecessary work.
7467
7468         // Give ourselves some initial paths; we'll come back for another
7469         // pass once we've determined ABI below.
7470         setNativeLibraryPaths(pkg);
7471
7472         // We would never need to extract libs for forward-locked and external packages,
7473         // since the container service will do it for us. We shouldn't attempt to
7474         // extract libs from system app when it was not updated.
7475         if (pkg.isForwardLocked() || isExternal(pkg) ||
7476             (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7477             extractLibs = false;
7478         }
7479
7480         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7481         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7482
7483         NativeLibraryHelper.Handle handle = null;
7484         try {
7485             handle = NativeLibraryHelper.Handle.create(scanFile);
7486             // TODO(multiArch): This can be null for apps that didn't go through the
7487             // usual installation process. We can calculate it again, like we
7488             // do during install time.
7489             //
7490             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7491             // unnecessary.
7492             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7493
7494             // Null out the abis so that they can be recalculated.
7495             pkg.applicationInfo.primaryCpuAbi = null;
7496             pkg.applicationInfo.secondaryCpuAbi = null;
7497             if (isMultiArch(pkg.applicationInfo)) {
7498                 // Warn if we've set an abiOverride for multi-lib packages..
7499                 // By definition, we need to copy both 32 and 64 bit libraries for
7500                 // such packages.
7501                 if (pkg.cpuAbiOverride != null
7502                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7503                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7504                 }
7505
7506                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7507                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7508                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7509                     if (extractLibs) {
7510                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7511                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7512                                 useIsaSpecificSubdirs);
7513                     } else {
7514                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7515                     }
7516                 }
7517
7518                 maybeThrowExceptionForMultiArchCopy(
7519                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7520
7521                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7522                     if (extractLibs) {
7523                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7524                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7525                                 useIsaSpecificSubdirs);
7526                     } else {
7527                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7528                     }
7529                 }
7530
7531                 maybeThrowExceptionForMultiArchCopy(
7532                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7533
7534                 if (abi64 >= 0) {
7535                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7536                 }
7537
7538                 if (abi32 >= 0) {
7539                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7540                     if (abi64 >= 0) {
7541                         pkg.applicationInfo.secondaryCpuAbi = abi;
7542                     } else {
7543                         pkg.applicationInfo.primaryCpuAbi = abi;
7544                     }
7545                 }
7546             } else {
7547                 String[] abiList = (cpuAbiOverride != null) ?
7548                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7549
7550                 // Enable gross and lame hacks for apps that are built with old
7551                 // SDK tools. We must scan their APKs for renderscript bitcode and
7552                 // not launch them if it's present. Don't bother checking on devices
7553                 // that don't have 64 bit support.
7554                 boolean needsRenderScriptOverride = false;
7555                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7556                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7557                     abiList = Build.SUPPORTED_32_BIT_ABIS;
7558                     needsRenderScriptOverride = true;
7559                 }
7560
7561                 final int copyRet;
7562                 if (extractLibs) {
7563                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7564                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7565                 } else {
7566                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7567                 }
7568
7569                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7570                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7571                             "Error unpackaging native libs for app, errorCode=" + copyRet);
7572                 }
7573
7574                 if (copyRet >= 0) {
7575                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7576                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7577                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7578                 } else if (needsRenderScriptOverride) {
7579                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
7580                 }
7581             }
7582         } catch (IOException ioe) {
7583             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7584         } finally {
7585             IoUtils.closeQuietly(handle);
7586         }
7587
7588         // Now that we've calculated the ABIs and determined if it's an internal app,
7589         // we will go ahead and populate the nativeLibraryPath.
7590         setNativeLibraryPaths(pkg);
7591     }
7592
7593     /**
7594      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7595      * i.e, so that all packages can be run inside a single process if required.
7596      *
7597      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7598      * this function will either try and make the ABI for all packages in {@code packagesForUser}
7599      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7600      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7601      * updating a package that belongs to a shared user.
7602      *
7603      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7604      * adds unnecessary complexity.
7605      */
7606     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7607             PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7608         String requiredInstructionSet = null;
7609         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7610             requiredInstructionSet = VMRuntime.getInstructionSet(
7611                      scannedPackage.applicationInfo.primaryCpuAbi);
7612         }
7613
7614         PackageSetting requirer = null;
7615         for (PackageSetting ps : packagesForUser) {
7616             // If packagesForUser contains scannedPackage, we skip it. This will happen
7617             // when scannedPackage is an update of an existing package. Without this check,
7618             // we will never be able to change the ABI of any package belonging to a shared
7619             // user, even if it's compatible with other packages.
7620             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7621                 if (ps.primaryCpuAbiString == null) {
7622                     continue;
7623                 }
7624
7625                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7626                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7627                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
7628                     // this but there's not much we can do.
7629                     String errorMessage = "Instruction set mismatch, "
7630                             + ((requirer == null) ? "[caller]" : requirer)
7631                             + " requires " + requiredInstructionSet + " whereas " + ps
7632                             + " requires " + instructionSet;
7633                     Slog.w(TAG, errorMessage);
7634                 }
7635
7636                 if (requiredInstructionSet == null) {
7637                     requiredInstructionSet = instructionSet;
7638                     requirer = ps;
7639                 }
7640             }
7641         }
7642
7643         if (requiredInstructionSet != null) {
7644             String adjustedAbi;
7645             if (requirer != null) {
7646                 // requirer != null implies that either scannedPackage was null or that scannedPackage
7647                 // did not require an ABI, in which case we have to adjust scannedPackage to match
7648                 // the ABI of the set (which is the same as requirer's ABI)
7649                 adjustedAbi = requirer.primaryCpuAbiString;
7650                 if (scannedPackage != null) {
7651                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7652                 }
7653             } else {
7654                 // requirer == null implies that we're updating all ABIs in the set to
7655                 // match scannedPackage.
7656                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7657             }
7658
7659             for (PackageSetting ps : packagesForUser) {
7660                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7661                     if (ps.primaryCpuAbiString != null) {
7662                         continue;
7663                     }
7664
7665                     ps.primaryCpuAbiString = adjustedAbi;
7666                     if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7667                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7668                         Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7669
7670                         int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7671                                 null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7672                         if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7673                             ps.primaryCpuAbiString = null;
7674                             ps.pkg.applicationInfo.primaryCpuAbi = null;
7675                             return;
7676                         } else {
7677                             mInstaller.rmdex(ps.codePathString,
7678                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
7679                         }
7680                     }
7681                 }
7682             }
7683         }
7684     }
7685
7686     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7687         synchronized (mPackages) {
7688             mResolverReplaced = true;
7689             // Set up information for custom user intent resolution activity.
7690             mResolveActivity.applicationInfo = pkg.applicationInfo;
7691             mResolveActivity.name = mCustomResolverComponentName.getClassName();
7692             mResolveActivity.packageName = pkg.applicationInfo.packageName;
7693             mResolveActivity.processName = pkg.applicationInfo.packageName;
7694             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7695             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7696                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7697             mResolveActivity.theme = 0;
7698             mResolveActivity.exported = true;
7699             mResolveActivity.enabled = true;
7700             mResolveInfo.activityInfo = mResolveActivity;
7701             mResolveInfo.priority = 0;
7702             mResolveInfo.preferredOrder = 0;
7703             mResolveInfo.match = 0;
7704             mResolveComponentName = mCustomResolverComponentName;
7705             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7706                     mResolveComponentName);
7707         }
7708     }
7709
7710     private static String calculateBundledApkRoot(final String codePathString) {
7711         final File codePath = new File(codePathString);
7712         final File codeRoot;
7713         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7714             codeRoot = Environment.getRootDirectory();
7715         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7716             codeRoot = Environment.getOemDirectory();
7717         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7718             codeRoot = Environment.getVendorDirectory();
7719         } else {
7720             // Unrecognized code path; take its top real segment as the apk root:
7721             // e.g. /something/app/blah.apk => /something
7722             try {
7723                 File f = codePath.getCanonicalFile();
7724                 File parent = f.getParentFile();    // non-null because codePath is a file
7725                 File tmp;
7726                 while ((tmp = parent.getParentFile()) != null) {
7727                     f = parent;
7728                     parent = tmp;
7729                 }
7730                 codeRoot = f;
7731                 Slog.w(TAG, "Unrecognized code path "
7732                         + codePath + " - using " + codeRoot);
7733             } catch (IOException e) {
7734                 // Can't canonicalize the code path -- shenanigans?
7735                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
7736                 return Environment.getRootDirectory().getPath();
7737             }
7738         }
7739         return codeRoot.getPath();
7740     }
7741
7742     /**
7743      * Derive and set the location of native libraries for the given package,
7744      * which varies depending on where and how the package was installed.
7745      */
7746     private void setNativeLibraryPaths(PackageParser.Package pkg) {
7747         final ApplicationInfo info = pkg.applicationInfo;
7748         final String codePath = pkg.codePath;
7749         final File codeFile = new File(codePath);
7750         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7751         final boolean asecApp = info.isForwardLocked() || isExternal(info);
7752
7753         info.nativeLibraryRootDir = null;
7754         info.nativeLibraryRootRequiresIsa = false;
7755         info.nativeLibraryDir = null;
7756         info.secondaryNativeLibraryDir = null;
7757
7758         if (isApkFile(codeFile)) {
7759             // Monolithic install
7760             if (bundledApp) {
7761                 // If "/system/lib64/apkname" exists, assume that is the per-package
7762                 // native library directory to use; otherwise use "/system/lib/apkname".
7763                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7764                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7765                         getPrimaryInstructionSet(info));
7766
7767                 // This is a bundled system app so choose the path based on the ABI.
7768                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7769                 // is just the default path.
7770                 final String apkName = deriveCodePathName(codePath);
7771                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7772                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7773                         apkName).getAbsolutePath();
7774
7775                 if (info.secondaryCpuAbi != null) {
7776                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7777                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7778                             secondaryLibDir, apkName).getAbsolutePath();
7779                 }
7780             } else if (asecApp) {
7781                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7782                         .getAbsolutePath();
7783             } else {
7784                 final String apkName = deriveCodePathName(codePath);
7785                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7786                         .getAbsolutePath();
7787             }
7788
7789             info.nativeLibraryRootRequiresIsa = false;
7790             info.nativeLibraryDir = info.nativeLibraryRootDir;
7791         } else {
7792             // Cluster install
7793             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7794             info.nativeLibraryRootRequiresIsa = true;
7795
7796             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7797                     getPrimaryInstructionSet(info)).getAbsolutePath();
7798
7799             if (info.secondaryCpuAbi != null) {
7800                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7801                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7802             }
7803         }
7804     }
7805
7806     /**
7807      * Calculate the abis and roots for a bundled app. These can uniquely
7808      * be determined from the contents of the system partition, i.e whether
7809      * it contains 64 or 32 bit shared libraries etc. We do not validate any
7810      * of this information, and instead assume that the system was built
7811      * sensibly.
7812      */
7813     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7814                                            PackageSetting pkgSetting) {
7815         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7816
7817         // If "/system/lib64/apkname" exists, assume that is the per-package
7818         // native library directory to use; otherwise use "/system/lib/apkname".
7819         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7820         setBundledAppAbi(pkg, apkRoot, apkName);
7821         // pkgSetting might be null during rescan following uninstall of updates
7822         // to a bundled app, so accommodate that possibility.  The settings in
7823         // that case will be established later from the parsed package.
7824         //
7825         // If the settings aren't null, sync them up with what we've just derived.
7826         // note that apkRoot isn't stored in the package settings.
7827         if (pkgSetting != null) {
7828             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7829             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7830         }
7831     }
7832
7833     /**
7834      * Deduces the ABI of a bundled app and sets the relevant fields on the
7835      * parsed pkg object.
7836      *
7837      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7838      *        under which system libraries are installed.
7839      * @param apkName the name of the installed package.
7840      */
7841     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7842         final File codeFile = new File(pkg.codePath);
7843
7844         final boolean has64BitLibs;
7845         final boolean has32BitLibs;
7846         if (isApkFile(codeFile)) {
7847             // Monolithic install
7848             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7849             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7850         } else {
7851             // Cluster install
7852             final File rootDir = new File(codeFile, LIB_DIR_NAME);
7853             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7854                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7855                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7856                 has64BitLibs = (new File(rootDir, isa)).exists();
7857             } else {
7858                 has64BitLibs = false;
7859             }
7860             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7861                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7862                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7863                 has32BitLibs = (new File(rootDir, isa)).exists();
7864             } else {
7865                 has32BitLibs = false;
7866             }
7867         }
7868
7869         if (has64BitLibs && !has32BitLibs) {
7870             // The package has 64 bit libs, but not 32 bit libs. Its primary
7871             // ABI should be 64 bit. We can safely assume here that the bundled
7872             // native libraries correspond to the most preferred ABI in the list.
7873
7874             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7875             pkg.applicationInfo.secondaryCpuAbi = null;
7876         } else if (has32BitLibs && !has64BitLibs) {
7877             // The package has 32 bit libs but not 64 bit libs. Its primary
7878             // ABI should be 32 bit.
7879
7880             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7881             pkg.applicationInfo.secondaryCpuAbi = null;
7882         } else if (has32BitLibs && has64BitLibs) {
7883             // The application has both 64 and 32 bit bundled libraries. We check
7884             // here that the app declares multiArch support, and warn if it doesn't.
7885             //
7886             // We will be lenient here and record both ABIs. The primary will be the
7887             // ABI that's higher on the list, i.e, a device that's configured to prefer
7888             // 64 bit apps will see a 64 bit primary ABI,
7889
7890             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7891                 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7892             }
7893
7894             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7895                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7896                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7897             } else {
7898                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7899                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7900             }
7901         } else {
7902             pkg.applicationInfo.primaryCpuAbi = null;
7903             pkg.applicationInfo.secondaryCpuAbi = null;
7904         }
7905     }
7906
7907     private void killApplication(String pkgName, int appId, String reason) {
7908         // Request the ActivityManager to kill the process(only for existing packages)
7909         // so that we do not end up in a confused state while the user is still using the older
7910         // version of the application while the new one gets installed.
7911         IActivityManager am = ActivityManagerNative.getDefault();
7912         if (am != null) {
7913             try {
7914                 am.killApplicationWithAppId(pkgName, appId, reason);
7915             } catch (RemoteException e) {
7916             }
7917         }
7918     }
7919
7920     void removePackageLI(PackageSetting ps, boolean chatty) {
7921         if (DEBUG_INSTALL) {
7922             if (chatty)
7923                 Log.d(TAG, "Removing package " + ps.name);
7924         }
7925
7926         // writer
7927         synchronized (mPackages) {
7928             mPackages.remove(ps.name);
7929             final PackageParser.Package pkg = ps.pkg;
7930             if (pkg != null) {
7931                 cleanPackageDataStructuresLILPw(pkg, chatty);
7932             }
7933         }
7934     }
7935
7936     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7937         if (DEBUG_INSTALL) {
7938             if (chatty)
7939                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7940         }
7941
7942         // writer
7943         synchronized (mPackages) {
7944             mPackages.remove(pkg.applicationInfo.packageName);
7945             cleanPackageDataStructuresLILPw(pkg, chatty);
7946         }
7947     }
7948
7949     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7950         int N = pkg.providers.size();
7951         StringBuilder r = null;
7952         int i;
7953         for (i=0; i<N; i++) {
7954             PackageParser.Provider p = pkg.providers.get(i);
7955             mProviders.removeProvider(p);
7956             if (p.info.authority == null) {
7957
7958                 /* There was another ContentProvider with this authority when
7959                  * this app was installed so this authority is null,
7960                  * Ignore it as we don't have to unregister the provider.
7961                  */
7962                 continue;
7963             }
7964             String names[] = p.info.authority.split(";");
7965             for (int j = 0; j < names.length; j++) {
7966                 if (mProvidersByAuthority.get(names[j]) == p) {
7967                     mProvidersByAuthority.remove(names[j]);
7968                     if (DEBUG_REMOVE) {
7969                         if (chatty)
7970                             Log.d(TAG, "Unregistered content provider: " + names[j]
7971                                     + ", className = " + p.info.name + ", isSyncable = "
7972                                     + p.info.isSyncable);
7973                     }
7974                 }
7975             }
7976             if (DEBUG_REMOVE && chatty) {
7977                 if (r == null) {
7978                     r = new StringBuilder(256);
7979                 } else {
7980                     r.append(' ');
7981                 }
7982                 r.append(p.info.name);
7983             }
7984         }
7985         if (r != null) {
7986             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7987         }
7988
7989         N = pkg.services.size();
7990         r = null;
7991         for (i=0; i<N; i++) {
7992             PackageParser.Service s = pkg.services.get(i);
7993             mServices.removeService(s);
7994             if (chatty) {
7995                 if (r == null) {
7996                     r = new StringBuilder(256);
7997                 } else {
7998                     r.append(' ');
7999                 }
8000                 r.append(s.info.name);
8001             }
8002         }
8003         if (r != null) {
8004             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8005         }
8006
8007         N = pkg.receivers.size();
8008         r = null;
8009         for (i=0; i<N; i++) {
8010             PackageParser.Activity a = pkg.receivers.get(i);
8011             mReceivers.removeActivity(a, "receiver");
8012             if (DEBUG_REMOVE && chatty) {
8013                 if (r == null) {
8014                     r = new StringBuilder(256);
8015                 } else {
8016                     r.append(' ');
8017                 }
8018                 r.append(a.info.name);
8019             }
8020         }
8021         if (r != null) {
8022             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8023         }
8024
8025         N = pkg.activities.size();
8026         r = null;
8027         for (i=0; i<N; i++) {
8028             PackageParser.Activity a = pkg.activities.get(i);
8029             mActivities.removeActivity(a, "activity");
8030             if (DEBUG_REMOVE && chatty) {
8031                 if (r == null) {
8032                     r = new StringBuilder(256);
8033                 } else {
8034                     r.append(' ');
8035                 }
8036                 r.append(a.info.name);
8037             }
8038         }
8039         if (r != null) {
8040             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8041         }
8042
8043         N = pkg.permissions.size();
8044         r = null;
8045         for (i=0; i<N; i++) {
8046             PackageParser.Permission p = pkg.permissions.get(i);
8047             BasePermission bp = mSettings.mPermissions.get(p.info.name);
8048             if (bp == null) {
8049                 bp = mSettings.mPermissionTrees.get(p.info.name);
8050             }
8051             if (bp != null && bp.perm == p) {
8052                 bp.perm = null;
8053                 if (DEBUG_REMOVE && chatty) {
8054                     if (r == null) {
8055                         r = new StringBuilder(256);
8056                     } else {
8057                         r.append(' ');
8058                     }
8059                     r.append(p.info.name);
8060                 }
8061             }
8062             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8063                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8064                 if (appOpPerms != null) {
8065                     appOpPerms.remove(pkg.packageName);
8066                 }
8067             }
8068         }
8069         if (r != null) {
8070             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8071         }
8072
8073         N = pkg.requestedPermissions.size();
8074         r = null;
8075         for (i=0; i<N; i++) {
8076             String perm = pkg.requestedPermissions.get(i);
8077             BasePermission bp = mSettings.mPermissions.get(perm);
8078             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8079                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8080                 if (appOpPerms != null) {
8081                     appOpPerms.remove(pkg.packageName);
8082                     if (appOpPerms.isEmpty()) {
8083                         mAppOpPermissionPackages.remove(perm);
8084                     }
8085                 }
8086             }
8087         }
8088         if (r != null) {
8089             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8090         }
8091
8092         N = pkg.instrumentation.size();
8093         r = null;
8094         for (i=0; i<N; i++) {
8095             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8096             mInstrumentation.remove(a.getComponentName());
8097             if (DEBUG_REMOVE && chatty) {
8098                 if (r == null) {
8099                     r = new StringBuilder(256);
8100                 } else {
8101                     r.append(' ');
8102                 }
8103                 r.append(a.info.name);
8104             }
8105         }
8106         if (r != null) {
8107             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8108         }
8109
8110         r = null;
8111         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8112             // Only system apps can hold shared libraries.
8113             if (pkg.libraryNames != null) {
8114                 for (i=0; i<pkg.libraryNames.size(); i++) {
8115                     String name = pkg.libraryNames.get(i);
8116                     SharedLibraryEntry cur = mSharedLibraries.get(name);
8117                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8118                         mSharedLibraries.remove(name);
8119                         if (DEBUG_REMOVE && chatty) {
8120                             if (r == null) {
8121                                 r = new StringBuilder(256);
8122                             } else {
8123                                 r.append(' ');
8124                             }
8125                             r.append(name);
8126                         }
8127                     }
8128                 }
8129             }
8130         }
8131         if (r != null) {
8132             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8133         }
8134     }
8135
8136     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8137         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8138             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8139                 return true;
8140             }
8141         }
8142         return false;
8143     }
8144
8145     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8146     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8147     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8148
8149     private void updatePermissionsLPw(String changingPkg,
8150             PackageParser.Package pkgInfo, int flags) {
8151         // Make sure there are no dangling permission trees.
8152         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8153         while (it.hasNext()) {
8154             final BasePermission bp = it.next();
8155             if (bp.packageSetting == null) {
8156                 // We may not yet have parsed the package, so just see if
8157                 // we still know about its settings.
8158                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8159             }
8160             if (bp.packageSetting == null) {
8161                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8162                         + " from package " + bp.sourcePackage);
8163                 it.remove();
8164             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8165                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8166                     Slog.i(TAG, "Removing old permission tree: " + bp.name
8167                             + " from package " + bp.sourcePackage);
8168                     flags |= UPDATE_PERMISSIONS_ALL;
8169                     it.remove();
8170                 }
8171             }
8172         }
8173
8174         // Make sure all dynamic permissions have been assigned to a package,
8175         // and make sure there are no dangling permissions.
8176         it = mSettings.mPermissions.values().iterator();
8177         while (it.hasNext()) {
8178             final BasePermission bp = it.next();
8179             if (bp.type == BasePermission.TYPE_DYNAMIC) {
8180                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8181                         + bp.name + " pkg=" + bp.sourcePackage
8182                         + " info=" + bp.pendingInfo);
8183                 if (bp.packageSetting == null && bp.pendingInfo != null) {
8184                     final BasePermission tree = findPermissionTreeLP(bp.name);
8185                     if (tree != null && tree.perm != null) {
8186                         bp.packageSetting = tree.packageSetting;
8187                         bp.perm = new PackageParser.Permission(tree.perm.owner,
8188                                 new PermissionInfo(bp.pendingInfo));
8189                         bp.perm.info.packageName = tree.perm.info.packageName;
8190                         bp.perm.info.name = bp.name;
8191                         bp.uid = tree.uid;
8192                     }
8193                 }
8194             }
8195             if (bp.packageSetting == null) {
8196                 // We may not yet have parsed the package, so just see if
8197                 // we still know about its settings.
8198                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8199             }
8200             if (bp.packageSetting == null) {
8201                 Slog.w(TAG, "Removing dangling permission: " + bp.name
8202                         + " from package " + bp.sourcePackage);
8203                 it.remove();
8204             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8205                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8206                     Slog.i(TAG, "Removing old permission: " + bp.name
8207                             + " from package " + bp.sourcePackage);
8208                     flags |= UPDATE_PERMISSIONS_ALL;
8209                     it.remove();
8210                 }
8211             }
8212         }
8213
8214         // Now update the permissions for all packages, in particular
8215         // replace the granted permissions of the system packages.
8216         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8217             for (PackageParser.Package pkg : mPackages.values()) {
8218                 if (pkg != pkgInfo) {
8219                     grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8220                             changingPkg);
8221                 }
8222             }
8223         }
8224
8225         if (pkgInfo != null) {
8226             grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8227         }
8228     }
8229
8230     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8231             String packageOfInterest) {
8232         // IMPORTANT: There are two types of permissions: install and runtime.
8233         // Install time permissions are granted when the app is installed to
8234         // all device users and users added in the future. Runtime permissions
8235         // are granted at runtime explicitly to specific users. Normal and signature
8236         // protected permissions are install time permissions. Dangerous permissions
8237         // are install permissions if the app's target SDK is Lollipop MR1 or older,
8238         // otherwise they are runtime permissions. This function does not manage
8239         // runtime permissions except for the case an app targeting Lollipop MR1
8240         // being upgraded to target a newer SDK, in which case dangerous permissions
8241         // are transformed from install time to runtime ones.
8242
8243         final PackageSetting ps = (PackageSetting) pkg.mExtras;
8244         if (ps == null) {
8245             return;
8246         }
8247
8248         PermissionsState permissionsState = ps.getPermissionsState();
8249         PermissionsState origPermissions = permissionsState;
8250
8251         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8252
8253         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8254
8255         boolean changedInstallPermission = false;
8256
8257         if (replace) {
8258             ps.installPermissionsFixed = false;
8259             if (!ps.isSharedUser()) {
8260                 origPermissions = new PermissionsState(permissionsState);
8261                 permissionsState.reset();
8262             }
8263         }
8264
8265         permissionsState.setGlobalGids(mGlobalGids);
8266
8267         final int N = pkg.requestedPermissions.size();
8268         for (int i=0; i<N; i++) {
8269             final String name = pkg.requestedPermissions.get(i);
8270             final BasePermission bp = mSettings.mPermissions.get(name);
8271
8272             if (DEBUG_INSTALL) {
8273                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8274             }
8275
8276             if (bp == null || bp.packageSetting == null) {
8277                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8278                     Slog.w(TAG, "Unknown permission " + name
8279                             + " in package " + pkg.packageName);
8280                 }
8281                 continue;
8282             }
8283
8284             final String perm = bp.name;
8285             boolean allowedSig = false;
8286             int grant = GRANT_DENIED;
8287
8288             // Keep track of app op permissions.
8289             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8290                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8291                 if (pkgs == null) {
8292                     pkgs = new ArraySet<>();
8293                     mAppOpPermissionPackages.put(bp.name, pkgs);
8294                 }
8295                 pkgs.add(pkg.packageName);
8296             }
8297
8298             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8299             switch (level) {
8300                 case PermissionInfo.PROTECTION_NORMAL: {
8301                     // For all apps normal permissions are install time ones.
8302                     grant = GRANT_INSTALL;
8303                 } break;
8304
8305                 case PermissionInfo.PROTECTION_DANGEROUS: {
8306                     if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8307                         // For legacy apps dangerous permissions are install time ones.
8308                         grant = GRANT_INSTALL_LEGACY;
8309                     } else if (origPermissions.hasInstallPermission(bp.name)) {
8310                         // For legacy apps that became modern, install becomes runtime.
8311                         grant = GRANT_UPGRADE;
8312                     } else {
8313                         // For modern apps keep runtime permissions unchanged.
8314                         grant = GRANT_RUNTIME;
8315                     }
8316                 } break;
8317
8318                 case PermissionInfo.PROTECTION_SIGNATURE: {
8319                     // For all apps signature permissions are install time ones.
8320                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8321                     if (allowedSig) {
8322                         grant = GRANT_INSTALL;
8323                     }
8324                 } break;
8325             }
8326
8327             if (DEBUG_INSTALL) {
8328                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8329             }
8330
8331             if (grant != GRANT_DENIED) {
8332                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8333                     // If this is an existing, non-system package, then
8334                     // we can't add any new permissions to it.
8335                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8336                         // Except...  if this is a permission that was added
8337                         // to the platform (note: need to only do this when
8338                         // updating the platform).
8339                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8340                             grant = GRANT_DENIED;
8341                         }
8342                     }
8343                 }
8344
8345                 switch (grant) {
8346                     case GRANT_INSTALL: {
8347                         // Revoke this as runtime permission to handle the case of
8348                         // a runtime permission being downgraded to an install one.
8349                         for (int userId : UserManagerService.getInstance().getUserIds()) {
8350                             if (origPermissions.getRuntimePermissionState(
8351                                     bp.name, userId) != null) {
8352                                 // Revoke the runtime permission and clear the flags.
8353                                 origPermissions.revokeRuntimePermission(bp, userId);
8354                                 origPermissions.updatePermissionFlags(bp, userId,
8355                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
8356                                 // If we revoked a permission permission, we have to write.
8357                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8358                                         changedRuntimePermissionUserIds, userId);
8359                             }
8360                         }
8361                         // Grant an install permission.
8362                         if (permissionsState.grantInstallPermission(bp) !=
8363                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8364                             changedInstallPermission = true;
8365                         }
8366                     } break;
8367
8368                     case GRANT_INSTALL_LEGACY: {
8369                         // Grant an install permission.
8370                         if (permissionsState.grantInstallPermission(bp) !=
8371                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8372                             changedInstallPermission = true;
8373                         }
8374                     } break;
8375
8376                     case GRANT_RUNTIME: {
8377                         // Grant previously granted runtime permissions.
8378                         for (int userId : UserManagerService.getInstance().getUserIds()) {
8379                             PermissionState permissionState = origPermissions
8380                                     .getRuntimePermissionState(bp.name, userId);
8381                             final int flags = permissionState != null
8382                                     ? permissionState.getFlags() : 0;
8383                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8384                                 if (permissionsState.grantRuntimePermission(bp, userId) ==
8385                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8386                                     // If we cannot put the permission as it was, we have to write.
8387                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8388                                             changedRuntimePermissionUserIds, userId);
8389                                 }
8390                             }
8391                             // Propagate the permission flags.
8392                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8393                         }
8394                     } break;
8395
8396                     case GRANT_UPGRADE: {
8397                         // Grant runtime permissions for a previously held install permission.
8398                         PermissionState permissionState = origPermissions
8399                                 .getInstallPermissionState(bp.name);
8400                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
8401
8402                         if (origPermissions.revokeInstallPermission(bp)
8403                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8404                             // We will be transferring the permission flags, so clear them.
8405                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8406                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
8407                             changedInstallPermission = true;
8408                         }
8409
8410                         // If the permission is not to be promoted to runtime we ignore it and
8411                         // also its other flags as they are not applicable to install permissions.
8412                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8413                             for (int userId : currentUserIds) {
8414                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
8415                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8416                                     // Transfer the permission flags.
8417                                     permissionsState.updatePermissionFlags(bp, userId,
8418                                             flags, flags);
8419                                     // If we granted the permission, we have to write.
8420                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8421                                             changedRuntimePermissionUserIds, userId);
8422                                 }
8423                             }
8424                         }
8425                     } break;
8426
8427                     default: {
8428                         if (packageOfInterest == null
8429                                 || packageOfInterest.equals(pkg.packageName)) {
8430                             Slog.w(TAG, "Not granting permission " + perm
8431                                     + " to package " + pkg.packageName
8432                                     + " because it was previously installed without");
8433                         }
8434                     } break;
8435                 }
8436             } else {
8437                 if (permissionsState.revokeInstallPermission(bp) !=
8438                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8439                     // Also drop the permission flags.
8440                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8441                             PackageManager.MASK_PERMISSION_FLAGS, 0);
8442                     changedInstallPermission = true;
8443                     Slog.i(TAG, "Un-granting permission " + perm
8444                             + " from package " + pkg.packageName
8445                             + " (protectionLevel=" + bp.protectionLevel
8446                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8447                             + ")");
8448                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8449                     // Don't print warning for app op permissions, since it is fine for them
8450                     // not to be granted, there is a UI for the user to decide.
8451                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8452                         Slog.w(TAG, "Not granting permission " + perm
8453                                 + " to package " + pkg.packageName
8454                                 + " (protectionLevel=" + bp.protectionLevel
8455                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8456                                 + ")");
8457                     }
8458                 }
8459             }
8460         }
8461
8462         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8463                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8464             // This is the first that we have heard about this package, so the
8465             // permissions we have now selected are fixed until explicitly
8466             // changed.
8467             ps.installPermissionsFixed = true;
8468         }
8469
8470         // Persist the runtime permissions state for users with changes.
8471         for (int userId : changedRuntimePermissionUserIds) {
8472             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8473         }
8474     }
8475
8476     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8477         boolean allowed = false;
8478         final int NP = PackageParser.NEW_PERMISSIONS.length;
8479         for (int ip=0; ip<NP; ip++) {
8480             final PackageParser.NewPermissionInfo npi
8481                     = PackageParser.NEW_PERMISSIONS[ip];
8482             if (npi.name.equals(perm)
8483                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8484                 allowed = true;
8485                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8486                         + pkg.packageName);
8487                 break;
8488             }
8489         }
8490         return allowed;
8491     }
8492
8493     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8494             BasePermission bp, PermissionsState origPermissions) {
8495         boolean allowed;
8496         allowed = (compareSignatures(
8497                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8498                         == PackageManager.SIGNATURE_MATCH)
8499                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8500                         == PackageManager.SIGNATURE_MATCH);
8501         if (!allowed && (bp.protectionLevel
8502                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8503             if (isSystemApp(pkg)) {
8504                 // For updated system applications, a system permission
8505                 // is granted only if it had been defined by the original application.
8506                 if (pkg.isUpdatedSystemApp()) {
8507                     final PackageSetting sysPs = mSettings
8508                             .getDisabledSystemPkgLPr(pkg.packageName);
8509                     if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8510                         // If the original was granted this permission, we take
8511                         // that grant decision as read and propagate it to the
8512                         // update.
8513                         if (sysPs.isPrivileged()) {
8514                             allowed = true;
8515                         }
8516                     } else {
8517                         // The system apk may have been updated with an older
8518                         // version of the one on the data partition, but which
8519                         // granted a new system permission that it didn't have
8520                         // before.  In this case we do want to allow the app to
8521                         // now get the new permission if the ancestral apk is
8522                         // privileged to get it.
8523                         if (sysPs.pkg != null && sysPs.isPrivileged()) {
8524                             for (int j=0;
8525                                     j<sysPs.pkg.requestedPermissions.size(); j++) {
8526                                 if (perm.equals(
8527                                         sysPs.pkg.requestedPermissions.get(j))) {
8528                                     allowed = true;
8529                                     break;
8530                                 }
8531                             }
8532                         }
8533                     }
8534                 } else {
8535                     allowed = isPrivilegedApp(pkg);
8536                 }
8537             }
8538         }
8539         if (!allowed) {
8540             if (!allowed && (bp.protectionLevel
8541                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8542                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8543                 // If this was a previously normal/dangerous permission that got moved
8544                 // to a system permission as part of the runtime permission redesign, then
8545                 // we still want to blindly grant it to old apps.
8546                 allowed = true;
8547             }
8548             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8549                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
8550                 // If this permission is to be granted to the system installer and
8551                 // this app is an installer, then it gets the permission.
8552                 allowed = true;
8553             }
8554             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8555                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
8556                 // If this permission is to be granted to the system verifier and
8557                 // this app is a verifier, then it gets the permission.
8558                 allowed = true;
8559             }
8560             if (!allowed && (bp.protectionLevel
8561                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8562                     && isSystemApp(pkg)) {
8563                 // Any pre-installed system app is allowed to get this permission.
8564                 allowed = true;
8565             }
8566             if (!allowed && (bp.protectionLevel
8567                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8568                 // For development permissions, a development permission
8569                 // is granted only if it was already granted.
8570                 allowed = origPermissions.hasInstallPermission(perm);
8571             }
8572         }
8573         return allowed;
8574     }
8575
8576     final class ActivityIntentResolver
8577             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8578         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8579                 boolean defaultOnly, int userId) {
8580             if (!sUserManager.exists(userId)) return null;
8581             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8582             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8583         }
8584
8585         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8586                 int userId) {
8587             if (!sUserManager.exists(userId)) return null;
8588             mFlags = flags;
8589             return super.queryIntent(intent, resolvedType,
8590                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8591         }
8592
8593         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8594                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8595             if (!sUserManager.exists(userId)) return null;
8596             if (packageActivities == null) {
8597                 return null;
8598             }
8599             mFlags = flags;
8600             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8601             final int N = packageActivities.size();
8602             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8603                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8604
8605             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8606             for (int i = 0; i < N; ++i) {
8607                 intentFilters = packageActivities.get(i).intents;
8608                 if (intentFilters != null && intentFilters.size() > 0) {
8609                     PackageParser.ActivityIntentInfo[] array =
8610                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
8611                     intentFilters.toArray(array);
8612                     listCut.add(array);
8613                 }
8614             }
8615             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8616         }
8617
8618         public final void addActivity(PackageParser.Activity a, String type) {
8619             final boolean systemApp = a.info.applicationInfo.isSystemApp();
8620             mActivities.put(a.getComponentName(), a);
8621             if (DEBUG_SHOW_INFO)
8622                 Log.v(
8623                 TAG, "  " + type + " " +
8624                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8625             if (DEBUG_SHOW_INFO)
8626                 Log.v(TAG, "    Class=" + a.info.name);
8627             final int NI = a.intents.size();
8628             for (int j=0; j<NI; j++) {
8629                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8630                 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8631                     intent.setPriority(0);
8632                     Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8633                             + a.className + " with priority > 0, forcing to 0");
8634                 }
8635                 if (DEBUG_SHOW_INFO) {
8636                     Log.v(TAG, "    IntentFilter:");
8637                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8638                 }
8639                 if (!intent.debugCheck()) {
8640                     Log.w(TAG, "==> For Activity " + a.info.name);
8641                 }
8642                 addFilter(intent);
8643             }
8644         }
8645
8646         public final void removeActivity(PackageParser.Activity a, String type) {
8647             mActivities.remove(a.getComponentName());
8648             if (DEBUG_SHOW_INFO) {
8649                 Log.v(TAG, "  " + type + " "
8650                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8651                                 : a.info.name) + ":");
8652                 Log.v(TAG, "    Class=" + a.info.name);
8653             }
8654             final int NI = a.intents.size();
8655             for (int j=0; j<NI; j++) {
8656                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8657                 if (DEBUG_SHOW_INFO) {
8658                     Log.v(TAG, "    IntentFilter:");
8659                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8660                 }
8661                 removeFilter(intent);
8662             }
8663         }
8664
8665         @Override
8666         protected boolean allowFilterResult(
8667                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8668             ActivityInfo filterAi = filter.activity.info;
8669             for (int i=dest.size()-1; i>=0; i--) {
8670                 ActivityInfo destAi = dest.get(i).activityInfo;
8671                 if (destAi.name == filterAi.name
8672                         && destAi.packageName == filterAi.packageName) {
8673                     return false;
8674                 }
8675             }
8676             return true;
8677         }
8678
8679         @Override
8680         protected ActivityIntentInfo[] newArray(int size) {
8681             return new ActivityIntentInfo[size];
8682         }
8683
8684         @Override
8685         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8686             if (!sUserManager.exists(userId)) return true;
8687             PackageParser.Package p = filter.activity.owner;
8688             if (p != null) {
8689                 PackageSetting ps = (PackageSetting)p.mExtras;
8690                 if (ps != null) {
8691                     // System apps are never considered stopped for purposes of
8692                     // filtering, because there may be no way for the user to
8693                     // actually re-launch them.
8694                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8695                             && ps.getStopped(userId);
8696                 }
8697             }
8698             return false;
8699         }
8700
8701         @Override
8702         protected boolean isPackageForFilter(String packageName,
8703                 PackageParser.ActivityIntentInfo info) {
8704             return packageName.equals(info.activity.owner.packageName);
8705         }
8706
8707         @Override
8708         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8709                 int match, int userId) {
8710             if (!sUserManager.exists(userId)) return null;
8711             if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8712                 return null;
8713             }
8714             final PackageParser.Activity activity = info.activity;
8715             if (mSafeMode && (activity.info.applicationInfo.flags
8716                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
8717                 return null;
8718             }
8719             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8720             if (ps == null) {
8721                 return null;
8722             }
8723             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8724                     ps.readUserState(userId), userId);
8725             if (ai == null) {
8726                 return null;
8727             }
8728             final ResolveInfo res = new ResolveInfo();
8729             res.activityInfo = ai;
8730             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8731                 res.filter = info;
8732             }
8733             if (info != null) {
8734                 res.handleAllWebDataURI = info.handleAllWebDataURI();
8735             }
8736             res.priority = info.getPriority();
8737             res.preferredOrder = activity.owner.mPreferredOrder;
8738             //System.out.println("Result: " + res.activityInfo.className +
8739             //                   " = " + res.priority);
8740             res.match = match;
8741             res.isDefault = info.hasDefault;
8742             res.labelRes = info.labelRes;
8743             res.nonLocalizedLabel = info.nonLocalizedLabel;
8744             if (userNeedsBadging(userId)) {
8745                 res.noResourceId = true;
8746             } else {
8747                 res.icon = info.icon;
8748             }
8749             res.iconResourceId = info.icon;
8750             res.system = res.activityInfo.applicationInfo.isSystemApp();
8751             return res;
8752         }
8753
8754         @Override
8755         protected void sortResults(List<ResolveInfo> results) {
8756             Collections.sort(results, mResolvePrioritySorter);
8757         }
8758
8759         @Override
8760         protected void dumpFilter(PrintWriter out, String prefix,
8761                 PackageParser.ActivityIntentInfo filter) {
8762             out.print(prefix); out.print(
8763                     Integer.toHexString(System.identityHashCode(filter.activity)));
8764                     out.print(' ');
8765                     filter.activity.printComponentShortName(out);
8766                     out.print(" filter ");
8767                     out.println(Integer.toHexString(System.identityHashCode(filter)));
8768         }
8769
8770         @Override
8771         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8772             return filter.activity;
8773         }
8774
8775         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8776             PackageParser.Activity activity = (PackageParser.Activity)label;
8777             out.print(prefix); out.print(
8778                     Integer.toHexString(System.identityHashCode(activity)));
8779                     out.print(' ');
8780                     activity.printComponentShortName(out);
8781             if (count > 1) {
8782                 out.print(" ("); out.print(count); out.print(" filters)");
8783             }
8784             out.println();
8785         }
8786
8787 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8788 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8789 //            final List<ResolveInfo> retList = Lists.newArrayList();
8790 //            while (i.hasNext()) {
8791 //                final ResolveInfo resolveInfo = i.next();
8792 //                if (isEnabledLP(resolveInfo.activityInfo)) {
8793 //                    retList.add(resolveInfo);
8794 //                }
8795 //            }
8796 //            return retList;
8797 //        }
8798
8799         // Keys are String (activity class name), values are Activity.
8800         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8801                 = new ArrayMap<ComponentName, PackageParser.Activity>();
8802         private int mFlags;
8803     }
8804
8805     private final class ServiceIntentResolver
8806             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8807         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8808                 boolean defaultOnly, int userId) {
8809             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8810             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8811         }
8812
8813         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8814                 int userId) {
8815             if (!sUserManager.exists(userId)) return null;
8816             mFlags = flags;
8817             return super.queryIntent(intent, resolvedType,
8818                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8819         }
8820
8821         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8822                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8823             if (!sUserManager.exists(userId)) return null;
8824             if (packageServices == null) {
8825                 return null;
8826             }
8827             mFlags = flags;
8828             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8829             final int N = packageServices.size();
8830             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8831                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8832
8833             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8834             for (int i = 0; i < N; ++i) {
8835                 intentFilters = packageServices.get(i).intents;
8836                 if (intentFilters != null && intentFilters.size() > 0) {
8837                     PackageParser.ServiceIntentInfo[] array =
8838                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
8839                     intentFilters.toArray(array);
8840                     listCut.add(array);
8841                 }
8842             }
8843             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8844         }
8845
8846         public final void addService(PackageParser.Service s) {
8847             mServices.put(s.getComponentName(), s);
8848             if (DEBUG_SHOW_INFO) {
8849                 Log.v(TAG, "  "
8850                         + (s.info.nonLocalizedLabel != null
8851                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
8852                 Log.v(TAG, "    Class=" + s.info.name);
8853             }
8854             final int NI = s.intents.size();
8855             int j;
8856             for (j=0; j<NI; j++) {
8857                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8858                 if (DEBUG_SHOW_INFO) {
8859                     Log.v(TAG, "    IntentFilter:");
8860                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8861                 }
8862                 if (!intent.debugCheck()) {
8863                     Log.w(TAG, "==> For Service " + s.info.name);
8864                 }
8865                 addFilter(intent);
8866             }
8867         }
8868
8869         public final void removeService(PackageParser.Service s) {
8870             mServices.remove(s.getComponentName());
8871             if (DEBUG_SHOW_INFO) {
8872                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8873                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
8874                 Log.v(TAG, "    Class=" + s.info.name);
8875             }
8876             final int NI = s.intents.size();
8877             int j;
8878             for (j=0; j<NI; j++) {
8879                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8880                 if (DEBUG_SHOW_INFO) {
8881                     Log.v(TAG, "    IntentFilter:");
8882                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8883                 }
8884                 removeFilter(intent);
8885             }
8886         }
8887
8888         @Override
8889         protected boolean allowFilterResult(
8890                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8891             ServiceInfo filterSi = filter.service.info;
8892             for (int i=dest.size()-1; i>=0; i--) {
8893                 ServiceInfo destAi = dest.get(i).serviceInfo;
8894                 if (destAi.name == filterSi.name
8895                         && destAi.packageName == filterSi.packageName) {
8896                     return false;
8897                 }
8898             }
8899             return true;
8900         }
8901
8902         @Override
8903         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8904             return new PackageParser.ServiceIntentInfo[size];
8905         }
8906
8907         @Override
8908         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8909             if (!sUserManager.exists(userId)) return true;
8910             PackageParser.Package p = filter.service.owner;
8911             if (p != null) {
8912                 PackageSetting ps = (PackageSetting)p.mExtras;
8913                 if (ps != null) {
8914                     // System apps are never considered stopped for purposes of
8915                     // filtering, because there may be no way for the user to
8916                     // actually re-launch them.
8917                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8918                             && ps.getStopped(userId);
8919                 }
8920             }
8921             return false;
8922         }
8923
8924         @Override
8925         protected boolean isPackageForFilter(String packageName,
8926                 PackageParser.ServiceIntentInfo info) {
8927             return packageName.equals(info.service.owner.packageName);
8928         }
8929
8930         @Override
8931         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8932                 int match, int userId) {
8933             if (!sUserManager.exists(userId)) return null;
8934             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8935             if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8936                 return null;
8937             }
8938             final PackageParser.Service service = info.service;
8939             if (mSafeMode && (service.info.applicationInfo.flags
8940                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
8941                 return null;
8942             }
8943             PackageSetting ps = (PackageSetting) service.owner.mExtras;
8944             if (ps == null) {
8945                 return null;
8946             }
8947             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8948                     ps.readUserState(userId), userId);
8949             if (si == null) {
8950                 return null;
8951             }
8952             final ResolveInfo res = new ResolveInfo();
8953             res.serviceInfo = si;
8954             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8955                 res.filter = filter;
8956             }
8957             res.priority = info.getPriority();
8958             res.preferredOrder = service.owner.mPreferredOrder;
8959             res.match = match;
8960             res.isDefault = info.hasDefault;
8961             res.labelRes = info.labelRes;
8962             res.nonLocalizedLabel = info.nonLocalizedLabel;
8963             res.icon = info.icon;
8964             res.system = res.serviceInfo.applicationInfo.isSystemApp();
8965             return res;
8966         }
8967
8968         @Override
8969         protected void sortResults(List<ResolveInfo> results) {
8970             Collections.sort(results, mResolvePrioritySorter);
8971         }
8972
8973         @Override
8974         protected void dumpFilter(PrintWriter out, String prefix,
8975                 PackageParser.ServiceIntentInfo filter) {
8976             out.print(prefix); out.print(
8977                     Integer.toHexString(System.identityHashCode(filter.service)));
8978                     out.print(' ');
8979                     filter.service.printComponentShortName(out);
8980                     out.print(" filter ");
8981                     out.println(Integer.toHexString(System.identityHashCode(filter)));
8982         }
8983
8984         @Override
8985         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8986             return filter.service;
8987         }
8988
8989         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8990             PackageParser.Service service = (PackageParser.Service)label;
8991             out.print(prefix); out.print(
8992                     Integer.toHexString(System.identityHashCode(service)));
8993                     out.print(' ');
8994                     service.printComponentShortName(out);
8995             if (count > 1) {
8996                 out.print(" ("); out.print(count); out.print(" filters)");
8997             }
8998             out.println();
8999         }
9000
9001 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9002 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9003 //            final List<ResolveInfo> retList = Lists.newArrayList();
9004 //            while (i.hasNext()) {
9005 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
9006 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
9007 //                    retList.add(resolveInfo);
9008 //                }
9009 //            }
9010 //            return retList;
9011 //        }
9012
9013         // Keys are String (activity class name), values are Activity.
9014         private final ArrayMap<ComponentName, PackageParser.Service> mServices
9015                 = new ArrayMap<ComponentName, PackageParser.Service>();
9016         private int mFlags;
9017     };
9018
9019     private final class ProviderIntentResolver
9020             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9021         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9022                 boolean defaultOnly, int userId) {
9023             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9024             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9025         }
9026
9027         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9028                 int userId) {
9029             if (!sUserManager.exists(userId))
9030                 return null;
9031             mFlags = flags;
9032             return super.queryIntent(intent, resolvedType,
9033                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9034         }
9035
9036         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9037                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9038             if (!sUserManager.exists(userId))
9039                 return null;
9040             if (packageProviders == null) {
9041                 return null;
9042             }
9043             mFlags = flags;
9044             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9045             final int N = packageProviders.size();
9046             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9047                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9048
9049             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9050             for (int i = 0; i < N; ++i) {
9051                 intentFilters = packageProviders.get(i).intents;
9052                 if (intentFilters != null && intentFilters.size() > 0) {
9053                     PackageParser.ProviderIntentInfo[] array =
9054                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
9055                     intentFilters.toArray(array);
9056                     listCut.add(array);
9057                 }
9058             }
9059             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9060         }
9061
9062         public final void addProvider(PackageParser.Provider p) {
9063             if (mProviders.containsKey(p.getComponentName())) {
9064                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9065                 return;
9066             }
9067
9068             mProviders.put(p.getComponentName(), p);
9069             if (DEBUG_SHOW_INFO) {
9070                 Log.v(TAG, "  "
9071                         + (p.info.nonLocalizedLabel != null
9072                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
9073                 Log.v(TAG, "    Class=" + p.info.name);
9074             }
9075             final int NI = p.intents.size();
9076             int j;
9077             for (j = 0; j < NI; j++) {
9078                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9079                 if (DEBUG_SHOW_INFO) {
9080                     Log.v(TAG, "    IntentFilter:");
9081                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9082                 }
9083                 if (!intent.debugCheck()) {
9084                     Log.w(TAG, "==> For Provider " + p.info.name);
9085                 }
9086                 addFilter(intent);
9087             }
9088         }
9089
9090         public final void removeProvider(PackageParser.Provider p) {
9091             mProviders.remove(p.getComponentName());
9092             if (DEBUG_SHOW_INFO) {
9093                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9094                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
9095                 Log.v(TAG, "    Class=" + p.info.name);
9096             }
9097             final int NI = p.intents.size();
9098             int j;
9099             for (j = 0; j < NI; j++) {
9100                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9101                 if (DEBUG_SHOW_INFO) {
9102                     Log.v(TAG, "    IntentFilter:");
9103                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9104                 }
9105                 removeFilter(intent);
9106             }
9107         }
9108
9109         @Override
9110         protected boolean allowFilterResult(
9111                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9112             ProviderInfo filterPi = filter.provider.info;
9113             for (int i = dest.size() - 1; i >= 0; i--) {
9114                 ProviderInfo destPi = dest.get(i).providerInfo;
9115                 if (destPi.name == filterPi.name
9116                         && destPi.packageName == filterPi.packageName) {
9117                     return false;
9118                 }
9119             }
9120             return true;
9121         }
9122
9123         @Override
9124         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9125             return new PackageParser.ProviderIntentInfo[size];
9126         }
9127
9128         @Override
9129         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9130             if (!sUserManager.exists(userId))
9131                 return true;
9132             PackageParser.Package p = filter.provider.owner;
9133             if (p != null) {
9134                 PackageSetting ps = (PackageSetting) p.mExtras;
9135                 if (ps != null) {
9136                     // System apps are never considered stopped for purposes of
9137                     // filtering, because there may be no way for the user to
9138                     // actually re-launch them.
9139                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9140                             && ps.getStopped(userId);
9141                 }
9142             }
9143             return false;
9144         }
9145
9146         @Override
9147         protected boolean isPackageForFilter(String packageName,
9148                 PackageParser.ProviderIntentInfo info) {
9149             return packageName.equals(info.provider.owner.packageName);
9150         }
9151
9152         @Override
9153         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9154                 int match, int userId) {
9155             if (!sUserManager.exists(userId))
9156                 return null;
9157             final PackageParser.ProviderIntentInfo info = filter;
9158             if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9159                 return null;
9160             }
9161             final PackageParser.Provider provider = info.provider;
9162             if (mSafeMode && (provider.info.applicationInfo.flags
9163                     & ApplicationInfo.FLAG_SYSTEM) == 0) {
9164                 return null;
9165             }
9166             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9167             if (ps == null) {
9168                 return null;
9169             }
9170             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9171                     ps.readUserState(userId), userId);
9172             if (pi == null) {
9173                 return null;
9174             }
9175             final ResolveInfo res = new ResolveInfo();
9176             res.providerInfo = pi;
9177             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9178                 res.filter = filter;
9179             }
9180             res.priority = info.getPriority();
9181             res.preferredOrder = provider.owner.mPreferredOrder;
9182             res.match = match;
9183             res.isDefault = info.hasDefault;
9184             res.labelRes = info.labelRes;
9185             res.nonLocalizedLabel = info.nonLocalizedLabel;
9186             res.icon = info.icon;
9187             res.system = res.providerInfo.applicationInfo.isSystemApp();
9188             return res;
9189         }
9190
9191         @Override
9192         protected void sortResults(List<ResolveInfo> results) {
9193             Collections.sort(results, mResolvePrioritySorter);
9194         }
9195
9196         @Override
9197         protected void dumpFilter(PrintWriter out, String prefix,
9198                 PackageParser.ProviderIntentInfo filter) {
9199             out.print(prefix);
9200             out.print(
9201                     Integer.toHexString(System.identityHashCode(filter.provider)));
9202             out.print(' ');
9203             filter.provider.printComponentShortName(out);
9204             out.print(" filter ");
9205             out.println(Integer.toHexString(System.identityHashCode(filter)));
9206         }
9207
9208         @Override
9209         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9210             return filter.provider;
9211         }
9212
9213         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9214             PackageParser.Provider provider = (PackageParser.Provider)label;
9215             out.print(prefix); out.print(
9216                     Integer.toHexString(System.identityHashCode(provider)));
9217                     out.print(' ');
9218                     provider.printComponentShortName(out);
9219             if (count > 1) {
9220                 out.print(" ("); out.print(count); out.print(" filters)");
9221             }
9222             out.println();
9223         }
9224
9225         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9226                 = new ArrayMap<ComponentName, PackageParser.Provider>();
9227         private int mFlags;
9228     };
9229
9230     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9231             new Comparator<ResolveInfo>() {
9232         public int compare(ResolveInfo r1, ResolveInfo r2) {
9233             int v1 = r1.priority;
9234             int v2 = r2.priority;
9235             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9236             if (v1 != v2) {
9237                 return (v1 > v2) ? -1 : 1;
9238             }
9239             v1 = r1.preferredOrder;
9240             v2 = r2.preferredOrder;
9241             if (v1 != v2) {
9242                 return (v1 > v2) ? -1 : 1;
9243             }
9244             if (r1.isDefault != r2.isDefault) {
9245                 return r1.isDefault ? -1 : 1;
9246             }
9247             v1 = r1.match;
9248             v2 = r2.match;
9249             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9250             if (v1 != v2) {
9251                 return (v1 > v2) ? -1 : 1;
9252             }
9253             if (r1.system != r2.system) {
9254                 return r1.system ? -1 : 1;
9255             }
9256             return 0;
9257         }
9258     };
9259
9260     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9261             new Comparator<ProviderInfo>() {
9262         public int compare(ProviderInfo p1, ProviderInfo p2) {
9263             final int v1 = p1.initOrder;
9264             final int v2 = p2.initOrder;
9265             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9266         }
9267     };
9268
9269     final void sendPackageBroadcast(final String action, final String pkg,
9270             final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9271             final int[] userIds) {
9272         mHandler.post(new Runnable() {
9273             @Override
9274             public void run() {
9275                 try {
9276                     final IActivityManager am = ActivityManagerNative.getDefault();
9277                     if (am == null) return;
9278                     final int[] resolvedUserIds;
9279                     if (userIds == null) {
9280                         resolvedUserIds = am.getRunningUserIds();
9281                     } else {
9282                         resolvedUserIds = userIds;
9283                     }
9284                     for (int id : resolvedUserIds) {
9285                         final Intent intent = new Intent(action,
9286                                 pkg != null ? Uri.fromParts("package", pkg, null) : null);
9287                         if (extras != null) {
9288                             intent.putExtras(extras);
9289                         }
9290                         if (targetPkg != null) {
9291                             intent.setPackage(targetPkg);
9292                         }
9293                         // Modify the UID when posting to other users
9294                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9295                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
9296                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9297                             intent.putExtra(Intent.EXTRA_UID, uid);
9298                         }
9299                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9300                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9301                         if (DEBUG_BROADCASTS) {
9302                             RuntimeException here = new RuntimeException("here");
9303                             here.fillInStackTrace();
9304                             Slog.d(TAG, "Sending to user " + id + ": "
9305                                     + intent.toShortString(false, true, false, false)
9306                                     + " " + intent.getExtras(), here);
9307                         }
9308                         am.broadcastIntent(null, intent, null, finishedReceiver,
9309                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
9310                                 null, finishedReceiver != null, false, id);
9311                     }
9312                 } catch (RemoteException ex) {
9313                 }
9314             }
9315         });
9316     }
9317
9318     /**
9319      * Check if the external storage media is available. This is true if there
9320      * is a mounted external storage medium or if the external storage is
9321      * emulated.
9322      */
9323     private boolean isExternalMediaAvailable() {
9324         return mMediaMounted || Environment.isExternalStorageEmulated();
9325     }
9326
9327     @Override
9328     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9329         // writer
9330         synchronized (mPackages) {
9331             if (!isExternalMediaAvailable()) {
9332                 // If the external storage is no longer mounted at this point,
9333                 // the caller may not have been able to delete all of this
9334                 // packages files and can not delete any more.  Bail.
9335                 return null;
9336             }
9337             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9338             if (lastPackage != null) {
9339                 pkgs.remove(lastPackage);
9340             }
9341             if (pkgs.size() > 0) {
9342                 return pkgs.get(0);
9343             }
9344         }
9345         return null;
9346     }
9347
9348     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9349         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9350                 userId, andCode ? 1 : 0, packageName);
9351         if (mSystemReady) {
9352             msg.sendToTarget();
9353         } else {
9354             if (mPostSystemReadyMessages == null) {
9355                 mPostSystemReadyMessages = new ArrayList<>();
9356             }
9357             mPostSystemReadyMessages.add(msg);
9358         }
9359     }
9360
9361     void startCleaningPackages() {
9362         // reader
9363         synchronized (mPackages) {
9364             if (!isExternalMediaAvailable()) {
9365                 return;
9366             }
9367             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9368                 return;
9369             }
9370         }
9371         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9372         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9373         IActivityManager am = ActivityManagerNative.getDefault();
9374         if (am != null) {
9375             try {
9376                 am.startService(null, intent, null, mContext.getOpPackageName(),
9377                         UserHandle.USER_OWNER);
9378             } catch (RemoteException e) {
9379             }
9380         }
9381     }
9382
9383     @Override
9384     public void installPackage(String originPath, IPackageInstallObserver2 observer,
9385             int installFlags, String installerPackageName, VerificationParams verificationParams,
9386             String packageAbiOverride) {
9387         installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9388                 verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9389     }
9390
9391     @Override
9392     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9393             int installFlags, String installerPackageName, VerificationParams verificationParams,
9394             String packageAbiOverride, int userId) {
9395         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9396
9397         final int callingUid = Binder.getCallingUid();
9398         enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9399
9400         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9401             try {
9402                 if (observer != null) {
9403                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9404                 }
9405             } catch (RemoteException re) {
9406             }
9407             return;
9408         }
9409
9410         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9411             installFlags |= PackageManager.INSTALL_FROM_ADB;
9412
9413         } else {
9414             // Caller holds INSTALL_PACKAGES permission, so we're less strict
9415             // about installerPackageName.
9416
9417             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9418             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9419         }
9420
9421         UserHandle user;
9422         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9423             user = UserHandle.ALL;
9424         } else {
9425             user = new UserHandle(userId);
9426         }
9427
9428         // Only system components can circumvent runtime permissions when installing.
9429         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9430                 && mContext.checkCallingOrSelfPermission(Manifest.permission
9431                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9432             throw new SecurityException("You need the "
9433                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9434                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9435         }
9436
9437         verificationParams.setInstallerUid(callingUid);
9438
9439         final File originFile = new File(originPath);
9440         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9441
9442         final Message msg = mHandler.obtainMessage(INIT_COPY);
9443         msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9444                 null, verificationParams, user, packageAbiOverride);
9445         mHandler.sendMessage(msg);
9446     }
9447
9448     void installStage(String packageName, File stagedDir, String stagedCid,
9449             IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9450             String installerPackageName, int installerUid, UserHandle user) {
9451         final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9452                 params.referrerUri, installerUid, null);
9453         verifParams.setInstallerUid(installerUid);
9454
9455         final OriginInfo origin;
9456         if (stagedDir != null) {
9457             origin = OriginInfo.fromStagedFile(stagedDir);
9458         } else {
9459             origin = OriginInfo.fromStagedContainer(stagedCid);
9460         }
9461
9462         final Message msg = mHandler.obtainMessage(INIT_COPY);
9463         msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9464                 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9465         mHandler.sendMessage(msg);
9466     }
9467
9468     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9469         Bundle extras = new Bundle(1);
9470         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9471
9472         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9473                 packageName, extras, null, null, new int[] {userId});
9474         try {
9475             IActivityManager am = ActivityManagerNative.getDefault();
9476             final boolean isSystem =
9477                     isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9478             if (isSystem && am.isUserRunning(userId, false)) {
9479                 // The just-installed/enabled app is bundled on the system, so presumed
9480                 // to be able to run automatically without needing an explicit launch.
9481                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9482                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9483                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9484                         .setPackage(packageName);
9485                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9486                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9487             }
9488         } catch (RemoteException e) {
9489             // shouldn't happen
9490             Slog.w(TAG, "Unable to bootstrap installed package", e);
9491         }
9492     }
9493
9494     @Override
9495     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9496             int userId) {
9497         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9498         PackageSetting pkgSetting;
9499         final int uid = Binder.getCallingUid();
9500         enforceCrossUserPermission(uid, userId, true, true,
9501                 "setApplicationHiddenSetting for user " + userId);
9502
9503         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9504             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9505             return false;
9506         }
9507
9508         long callingId = Binder.clearCallingIdentity();
9509         try {
9510             boolean sendAdded = false;
9511             boolean sendRemoved = false;
9512             // writer
9513             synchronized (mPackages) {
9514                 pkgSetting = mSettings.mPackages.get(packageName);
9515                 if (pkgSetting == null) {
9516                     return false;
9517                 }
9518                 if (pkgSetting.getHidden(userId) != hidden) {
9519                     pkgSetting.setHidden(hidden, userId);
9520                     mSettings.writePackageRestrictionsLPr(userId);
9521                     if (hidden) {
9522                         sendRemoved = true;
9523                     } else {
9524                         sendAdded = true;
9525                     }
9526                 }
9527             }
9528             if (sendAdded) {
9529                 sendPackageAddedForUser(packageName, pkgSetting, userId);
9530                 return true;
9531             }
9532             if (sendRemoved) {
9533                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9534                         "hiding pkg");
9535                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9536             }
9537         } finally {
9538             Binder.restoreCallingIdentity(callingId);
9539         }
9540         return false;
9541     }
9542
9543     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9544             int userId) {
9545         final PackageRemovedInfo info = new PackageRemovedInfo();
9546         info.removedPackage = packageName;
9547         info.removedUsers = new int[] {userId};
9548         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9549         info.sendBroadcast(false, false, false);
9550     }
9551
9552     /**
9553      * Returns true if application is not found or there was an error. Otherwise it returns
9554      * the hidden state of the package for the given user.
9555      */
9556     @Override
9557     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9558         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9559         enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9560                 false, "getApplicationHidden for user " + userId);
9561         PackageSetting pkgSetting;
9562         long callingId = Binder.clearCallingIdentity();
9563         try {
9564             // writer
9565             synchronized (mPackages) {
9566                 pkgSetting = mSettings.mPackages.get(packageName);
9567                 if (pkgSetting == null) {
9568                     return true;
9569                 }
9570                 return pkgSetting.getHidden(userId);
9571             }
9572         } finally {
9573             Binder.restoreCallingIdentity(callingId);
9574         }
9575     }
9576
9577     /**
9578      * @hide
9579      */
9580     @Override
9581     public int installExistingPackageAsUser(String packageName, int userId) {
9582         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9583                 null);
9584         PackageSetting pkgSetting;
9585         final int uid = Binder.getCallingUid();
9586         enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9587                 + userId);
9588         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9589             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9590         }
9591
9592         long callingId = Binder.clearCallingIdentity();
9593         try {
9594             boolean sendAdded = false;
9595
9596             // writer
9597             synchronized (mPackages) {
9598                 pkgSetting = mSettings.mPackages.get(packageName);
9599                 if (pkgSetting == null) {
9600                     return PackageManager.INSTALL_FAILED_INVALID_URI;
9601                 }
9602                 if (!pkgSetting.getInstalled(userId)) {
9603                     pkgSetting.setInstalled(true, userId);
9604                     pkgSetting.setHidden(false, userId);
9605                     mSettings.writePackageRestrictionsLPr(userId);
9606                     sendAdded = true;
9607                 }
9608             }
9609
9610             if (sendAdded) {
9611                 sendPackageAddedForUser(packageName, pkgSetting, userId);
9612             }
9613         } finally {
9614             Binder.restoreCallingIdentity(callingId);
9615         }
9616
9617         return PackageManager.INSTALL_SUCCEEDED;
9618     }
9619
9620     boolean isUserRestricted(int userId, String restrictionKey) {
9621         Bundle restrictions = sUserManager.getUserRestrictions(userId);
9622         if (restrictions.getBoolean(restrictionKey, false)) {
9623             Log.w(TAG, "User is restricted: " + restrictionKey);
9624             return true;
9625         }
9626         return false;
9627     }
9628
9629     @Override
9630     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9631         mContext.enforceCallingOrSelfPermission(
9632                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9633                 "Only package verification agents can verify applications");
9634
9635         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9636         final PackageVerificationResponse response = new PackageVerificationResponse(
9637                 verificationCode, Binder.getCallingUid());
9638         msg.arg1 = id;
9639         msg.obj = response;
9640         mHandler.sendMessage(msg);
9641     }
9642
9643     @Override
9644     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9645             long millisecondsToDelay) {
9646         mContext.enforceCallingOrSelfPermission(
9647                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9648                 "Only package verification agents can extend verification timeouts");
9649
9650         final PackageVerificationState state = mPendingVerification.get(id);
9651         final PackageVerificationResponse response = new PackageVerificationResponse(
9652                 verificationCodeAtTimeout, Binder.getCallingUid());
9653
9654         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9655             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9656         }
9657         if (millisecondsToDelay < 0) {
9658             millisecondsToDelay = 0;
9659         }
9660         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9661                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9662             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9663         }
9664
9665         if ((state != null) && !state.timeoutExtended()) {
9666             state.extendTimeout();
9667
9668             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9669             msg.arg1 = id;
9670             msg.obj = response;
9671             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9672         }
9673     }
9674
9675     private void broadcastPackageVerified(int verificationId, Uri packageUri,
9676             int verificationCode, UserHandle user) {
9677         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9678         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9679         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9680         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9681         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9682
9683         mContext.sendBroadcastAsUser(intent, user,
9684                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9685     }
9686
9687     private ComponentName matchComponentForVerifier(String packageName,
9688             List<ResolveInfo> receivers) {
9689         ActivityInfo targetReceiver = null;
9690
9691         final int NR = receivers.size();
9692         for (int i = 0; i < NR; i++) {
9693             final ResolveInfo info = receivers.get(i);
9694             if (info.activityInfo == null) {
9695                 continue;
9696             }
9697
9698             if (packageName.equals(info.activityInfo.packageName)) {
9699                 targetReceiver = info.activityInfo;
9700                 break;
9701             }
9702         }
9703
9704         if (targetReceiver == null) {
9705             return null;
9706         }
9707
9708         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9709     }
9710
9711     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9712             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9713         if (pkgInfo.verifiers.length == 0) {
9714             return null;
9715         }
9716
9717         final int N = pkgInfo.verifiers.length;
9718         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9719         for (int i = 0; i < N; i++) {
9720             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9721
9722             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9723                     receivers);
9724             if (comp == null) {
9725                 continue;
9726             }
9727
9728             final int verifierUid = getUidForVerifier(verifierInfo);
9729             if (verifierUid == -1) {
9730                 continue;
9731             }
9732
9733             if (DEBUG_VERIFY) {
9734                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9735                         + " with the correct signature");
9736             }
9737             sufficientVerifiers.add(comp);
9738             verificationState.addSufficientVerifier(verifierUid);
9739         }
9740
9741         return sufficientVerifiers;
9742     }
9743
9744     private int getUidForVerifier(VerifierInfo verifierInfo) {
9745         synchronized (mPackages) {
9746             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9747             if (pkg == null) {
9748                 return -1;
9749             } else if (pkg.mSignatures.length != 1) {
9750                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9751                         + " has more than one signature; ignoring");
9752                 return -1;
9753             }
9754
9755             /*
9756              * If the public key of the package's signature does not match
9757              * our expected public key, then this is a different package and
9758              * we should skip.
9759              */
9760
9761             final byte[] expectedPublicKey;
9762             try {
9763                 final Signature verifierSig = pkg.mSignatures[0];
9764                 final PublicKey publicKey = verifierSig.getPublicKey();
9765                 expectedPublicKey = publicKey.getEncoded();
9766             } catch (CertificateException e) {
9767                 return -1;
9768             }
9769
9770             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9771
9772             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9773                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9774                         + " does not have the expected public key; ignoring");
9775                 return -1;
9776             }
9777
9778             return pkg.applicationInfo.uid;
9779         }
9780     }
9781
9782     @Override
9783     public void finishPackageInstall(int token) {
9784         enforceSystemOrRoot("Only the system is allowed to finish installs");
9785
9786         if (DEBUG_INSTALL) {
9787             Slog.v(TAG, "BM finishing package install for " + token);
9788         }
9789
9790         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9791         mHandler.sendMessage(msg);
9792     }
9793
9794     /**
9795      * Get the verification agent timeout.
9796      *
9797      * @return verification timeout in milliseconds
9798      */
9799     private long getVerificationTimeout() {
9800         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9801                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9802                 DEFAULT_VERIFICATION_TIMEOUT);
9803     }
9804
9805     /**
9806      * Get the default verification agent response code.
9807      *
9808      * @return default verification response code
9809      */
9810     private int getDefaultVerificationResponse() {
9811         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9812                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9813                 DEFAULT_VERIFICATION_RESPONSE);
9814     }
9815
9816     /**
9817      * Check whether or not package verification has been enabled.
9818      *
9819      * @return true if verification should be performed
9820      */
9821     private boolean isVerificationEnabled(int userId, int installFlags) {
9822         if (!DEFAULT_VERIFY_ENABLE) {
9823             return false;
9824         }
9825
9826         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9827
9828         // Check if installing from ADB
9829         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9830             // Do not run verification in a test harness environment
9831             if (ActivityManager.isRunningInTestHarness()) {
9832                 return false;
9833             }
9834             if (ensureVerifyAppsEnabled) {
9835                 return true;
9836             }
9837             // Check if the developer does not want package verification for ADB installs
9838             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9839                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9840                 return false;
9841             }
9842         }
9843
9844         if (ensureVerifyAppsEnabled) {
9845             return true;
9846         }
9847
9848         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9849                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9850     }
9851
9852     @Override
9853     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9854             throws RemoteException {
9855         mContext.enforceCallingOrSelfPermission(
9856                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9857                 "Only intentfilter verification agents can verify applications");
9858
9859         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9860         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9861                 Binder.getCallingUid(), verificationCode, failedDomains);
9862         msg.arg1 = id;
9863         msg.obj = response;
9864         mHandler.sendMessage(msg);
9865     }
9866
9867     @Override
9868     public int getIntentVerificationStatus(String packageName, int userId) {
9869         synchronized (mPackages) {
9870             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9871         }
9872     }
9873
9874     @Override
9875     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9876         mContext.enforceCallingOrSelfPermission(
9877                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9878
9879         boolean result = false;
9880         synchronized (mPackages) {
9881             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9882         }
9883         if (result) {
9884             scheduleWritePackageRestrictionsLocked(userId);
9885         }
9886         return result;
9887     }
9888
9889     @Override
9890     public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9891         synchronized (mPackages) {
9892             return mSettings.getIntentFilterVerificationsLPr(packageName);
9893         }
9894     }
9895
9896     @Override
9897     public List<IntentFilter> getAllIntentFilters(String packageName) {
9898         if (TextUtils.isEmpty(packageName)) {
9899             return Collections.<IntentFilter>emptyList();
9900         }
9901         synchronized (mPackages) {
9902             PackageParser.Package pkg = mPackages.get(packageName);
9903             if (pkg == null || pkg.activities == null) {
9904                 return Collections.<IntentFilter>emptyList();
9905             }
9906             final int count = pkg.activities.size();
9907             ArrayList<IntentFilter> result = new ArrayList<>();
9908             for (int n=0; n<count; n++) {
9909                 PackageParser.Activity activity = pkg.activities.get(n);
9910                 if (activity.intents != null || activity.intents.size() > 0) {
9911                     result.addAll(activity.intents);
9912                 }
9913             }
9914             return result;
9915         }
9916     }
9917
9918     @Override
9919     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9920         mContext.enforceCallingOrSelfPermission(
9921                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9922
9923         synchronized (mPackages) {
9924             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9925             if (packageName != null) {
9926                 result |= updateIntentVerificationStatus(packageName,
9927                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9928                         UserHandle.myUserId());
9929                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9930                         packageName, userId);
9931             }
9932             return result;
9933         }
9934     }
9935
9936     @Override
9937     public String getDefaultBrowserPackageName(int userId) {
9938         synchronized (mPackages) {
9939             return mSettings.getDefaultBrowserPackageNameLPw(userId);
9940         }
9941     }
9942
9943     /**
9944      * Get the "allow unknown sources" setting.
9945      *
9946      * @return the current "allow unknown sources" setting
9947      */
9948     private int getUnknownSourcesSettings() {
9949         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9950                 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9951                 -1);
9952     }
9953
9954     @Override
9955     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9956         final int uid = Binder.getCallingUid();
9957         // writer
9958         synchronized (mPackages) {
9959             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9960             if (targetPackageSetting == null) {
9961                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9962             }
9963
9964             PackageSetting installerPackageSetting;
9965             if (installerPackageName != null) {
9966                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9967                 if (installerPackageSetting == null) {
9968                     throw new IllegalArgumentException("Unknown installer package: "
9969                             + installerPackageName);
9970                 }
9971             } else {
9972                 installerPackageSetting = null;
9973             }
9974
9975             Signature[] callerSignature;
9976             Object obj = mSettings.getUserIdLPr(uid);
9977             if (obj != null) {
9978                 if (obj instanceof SharedUserSetting) {
9979                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9980                 } else if (obj instanceof PackageSetting) {
9981                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9982                 } else {
9983                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
9984                 }
9985             } else {
9986                 throw new SecurityException("Unknown calling uid " + uid);
9987             }
9988
9989             // Verify: can't set installerPackageName to a package that is
9990             // not signed with the same cert as the caller.
9991             if (installerPackageSetting != null) {
9992                 if (compareSignatures(callerSignature,
9993                         installerPackageSetting.signatures.mSignatures)
9994                         != PackageManager.SIGNATURE_MATCH) {
9995                     throw new SecurityException(
9996                             "Caller does not have same cert as new installer package "
9997                             + installerPackageName);
9998                 }
9999             }
10000
10001             // Verify: if target already has an installer package, it must
10002             // be signed with the same cert as the caller.
10003             if (targetPackageSetting.installerPackageName != null) {
10004                 PackageSetting setting = mSettings.mPackages.get(
10005                         targetPackageSetting.installerPackageName);
10006                 // If the currently set package isn't valid, then it's always
10007                 // okay to change it.
10008                 if (setting != null) {
10009                     if (compareSignatures(callerSignature,
10010                             setting.signatures.mSignatures)
10011                             != PackageManager.SIGNATURE_MATCH) {
10012                         throw new SecurityException(
10013                                 "Caller does not have same cert as old installer package "
10014                                 + targetPackageSetting.installerPackageName);
10015                     }
10016                 }
10017             }
10018
10019             // Okay!
10020             targetPackageSetting.installerPackageName = installerPackageName;
10021             scheduleWriteSettingsLocked();
10022         }
10023     }
10024
10025     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10026         // Queue up an async operation since the package installation may take a little while.
10027         mHandler.post(new Runnable() {
10028             public void run() {
10029                 mHandler.removeCallbacks(this);
10030                  // Result object to be returned
10031                 PackageInstalledInfo res = new PackageInstalledInfo();
10032                 res.returnCode = currentStatus;
10033                 res.uid = -1;
10034                 res.pkg = null;
10035                 res.removedInfo = new PackageRemovedInfo();
10036                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10037                     args.doPreInstall(res.returnCode);
10038                     synchronized (mInstallLock) {
10039                         installPackageLI(args, res);
10040                     }
10041                     args.doPostInstall(res.returnCode, res.uid);
10042                 }
10043
10044                 // A restore should be performed at this point if (a) the install
10045                 // succeeded, (b) the operation is not an update, and (c) the new
10046                 // package has not opted out of backup participation.
10047                 final boolean update = res.removedInfo.removedPackage != null;
10048                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10049                 boolean doRestore = !update
10050                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10051
10052                 // Set up the post-install work request bookkeeping.  This will be used
10053                 // and cleaned up by the post-install event handling regardless of whether
10054                 // there's a restore pass performed.  Token values are >= 1.
10055                 int token;
10056                 if (mNextInstallToken < 0) mNextInstallToken = 1;
10057                 token = mNextInstallToken++;
10058
10059                 PostInstallData data = new PostInstallData(args, res);
10060                 mRunningInstalls.put(token, data);
10061                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10062
10063                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10064                     // Pass responsibility to the Backup Manager.  It will perform a
10065                     // restore if appropriate, then pass responsibility back to the
10066                     // Package Manager to run the post-install observer callbacks
10067                     // and broadcasts.
10068                     IBackupManager bm = IBackupManager.Stub.asInterface(
10069                             ServiceManager.getService(Context.BACKUP_SERVICE));
10070                     if (bm != null) {
10071                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10072                                 + " to BM for possible restore");
10073                         try {
10074                             if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10075                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10076                             } else {
10077                                 doRestore = false;
10078                             }
10079                         } catch (RemoteException e) {
10080                             // can't happen; the backup manager is local
10081                         } catch (Exception e) {
10082                             Slog.e(TAG, "Exception trying to enqueue restore", e);
10083                             doRestore = false;
10084                         }
10085                     } else {
10086                         Slog.e(TAG, "Backup Manager not found!");
10087                         doRestore = false;
10088                     }
10089                 }
10090
10091                 if (!doRestore) {
10092                     // No restore possible, or the Backup Manager was mysteriously not
10093                     // available -- just fire the post-install work request directly.
10094                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10095                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10096                     mHandler.sendMessage(msg);
10097                 }
10098             }
10099         });
10100     }
10101
10102     private abstract class HandlerParams {
10103         private static final int MAX_RETRIES = 4;
10104
10105         /**
10106          * Number of times startCopy() has been attempted and had a non-fatal
10107          * error.
10108          */
10109         private int mRetries = 0;
10110
10111         /** User handle for the user requesting the information or installation. */
10112         private final UserHandle mUser;
10113
10114         HandlerParams(UserHandle user) {
10115             mUser = user;
10116         }
10117
10118         UserHandle getUser() {
10119             return mUser;
10120         }
10121
10122         final boolean startCopy() {
10123             boolean res;
10124             try {
10125                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10126
10127                 if (++mRetries > MAX_RETRIES) {
10128                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10129                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
10130                     handleServiceError();
10131                     return false;
10132                 } else {
10133                     handleStartCopy();
10134                     res = true;
10135                 }
10136             } catch (RemoteException e) {
10137                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10138                 mHandler.sendEmptyMessage(MCS_RECONNECT);
10139                 res = false;
10140             }
10141             handleReturnCode();
10142             return res;
10143         }
10144
10145         final void serviceError() {
10146             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10147             handleServiceError();
10148             handleReturnCode();
10149         }
10150
10151         abstract void handleStartCopy() throws RemoteException;
10152         abstract void handleServiceError();
10153         abstract void handleReturnCode();
10154     }
10155
10156     class MeasureParams extends HandlerParams {
10157         private final PackageStats mStats;
10158         private boolean mSuccess;
10159
10160         private final IPackageStatsObserver mObserver;
10161
10162         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10163             super(new UserHandle(stats.userHandle));
10164             mObserver = observer;
10165             mStats = stats;
10166         }
10167
10168         @Override
10169         public String toString() {
10170             return "MeasureParams{"
10171                 + Integer.toHexString(System.identityHashCode(this))
10172                 + " " + mStats.packageName + "}";
10173         }
10174
10175         @Override
10176         void handleStartCopy() throws RemoteException {
10177             synchronized (mInstallLock) {
10178                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10179             }
10180
10181             if (mSuccess) {
10182                 final boolean mounted;
10183                 if (Environment.isExternalStorageEmulated()) {
10184                     mounted = true;
10185                 } else {
10186                     final String status = Environment.getExternalStorageState();
10187                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
10188                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10189                 }
10190
10191                 if (mounted) {
10192                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10193
10194                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10195                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10196
10197                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
10198                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10199
10200                     // Always subtract cache size, since it's a subdirectory
10201                     mStats.externalDataSize -= mStats.externalCacheSize;
10202
10203                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10204                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10205
10206                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
10207                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10208                 }
10209             }
10210         }
10211
10212         @Override
10213         void handleReturnCode() {
10214             if (mObserver != null) {
10215                 try {
10216                     mObserver.onGetStatsCompleted(mStats, mSuccess);
10217                 } catch (RemoteException e) {
10218                     Slog.i(TAG, "Observer no longer exists.");
10219                 }
10220             }
10221         }
10222
10223         @Override
10224         void handleServiceError() {
10225             Slog.e(TAG, "Could not measure application " + mStats.packageName
10226                             + " external storage");
10227         }
10228     }
10229
10230     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10231             throws RemoteException {
10232         long result = 0;
10233         for (File path : paths) {
10234             result += mcs.calculateDirectorySize(path.getAbsolutePath());
10235         }
10236         return result;
10237     }
10238
10239     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10240         for (File path : paths) {
10241             try {
10242                 mcs.clearDirectory(path.getAbsolutePath());
10243             } catch (RemoteException e) {
10244             }
10245         }
10246     }
10247
10248     static class OriginInfo {
10249         /**
10250          * Location where install is coming from, before it has been
10251          * copied/renamed into place. This could be a single monolithic APK
10252          * file, or a cluster directory. This location may be untrusted.
10253          */
10254         final File file;
10255         final String cid;
10256
10257         /**
10258          * Flag indicating that {@link #file} or {@link #cid} has already been
10259          * staged, meaning downstream users don't need to defensively copy the
10260          * contents.
10261          */
10262         final boolean staged;
10263
10264         /**
10265          * Flag indicating that {@link #file} or {@link #cid} is an already
10266          * installed app that is being moved.
10267          */
10268         final boolean existing;
10269
10270         final String resolvedPath;
10271         final File resolvedFile;
10272
10273         static OriginInfo fromNothing() {
10274             return new OriginInfo(null, null, false, false);
10275         }
10276
10277         static OriginInfo fromUntrustedFile(File file) {
10278             return new OriginInfo(file, null, false, false);
10279         }
10280
10281         static OriginInfo fromExistingFile(File file) {
10282             return new OriginInfo(file, null, false, true);
10283         }
10284
10285         static OriginInfo fromStagedFile(File file) {
10286             return new OriginInfo(file, null, true, false);
10287         }
10288
10289         static OriginInfo fromStagedContainer(String cid) {
10290             return new OriginInfo(null, cid, true, false);
10291         }
10292
10293         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10294             this.file = file;
10295             this.cid = cid;
10296             this.staged = staged;
10297             this.existing = existing;
10298
10299             if (cid != null) {
10300                 resolvedPath = PackageHelper.getSdDir(cid);
10301                 resolvedFile = new File(resolvedPath);
10302             } else if (file != null) {
10303                 resolvedPath = file.getAbsolutePath();
10304                 resolvedFile = file;
10305             } else {
10306                 resolvedPath = null;
10307                 resolvedFile = null;
10308             }
10309         }
10310     }
10311
10312     class MoveInfo {
10313         final int moveId;
10314         final String fromUuid;
10315         final String toUuid;
10316         final String packageName;
10317         final String dataAppName;
10318         final int appId;
10319         final String seinfo;
10320
10321         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10322                 String dataAppName, int appId, String seinfo) {
10323             this.moveId = moveId;
10324             this.fromUuid = fromUuid;
10325             this.toUuid = toUuid;
10326             this.packageName = packageName;
10327             this.dataAppName = dataAppName;
10328             this.appId = appId;
10329             this.seinfo = seinfo;
10330         }
10331     }
10332
10333     class InstallParams extends HandlerParams {
10334         final OriginInfo origin;
10335         final MoveInfo move;
10336         final IPackageInstallObserver2 observer;
10337         int installFlags;
10338         final String installerPackageName;
10339         final String volumeUuid;
10340         final VerificationParams verificationParams;
10341         private InstallArgs mArgs;
10342         private int mRet;
10343         final String packageAbiOverride;
10344
10345         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10346                 int installFlags, String installerPackageName, String volumeUuid,
10347                 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10348             super(user);
10349             this.origin = origin;
10350             this.move = move;
10351             this.observer = observer;
10352             this.installFlags = installFlags;
10353             this.installerPackageName = installerPackageName;
10354             this.volumeUuid = volumeUuid;
10355             this.verificationParams = verificationParams;
10356             this.packageAbiOverride = packageAbiOverride;
10357         }
10358
10359         @Override
10360         public String toString() {
10361             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10362                     + " file=" + origin.file + " cid=" + origin.cid + "}";
10363         }
10364
10365         public ManifestDigest getManifestDigest() {
10366             if (verificationParams == null) {
10367                 return null;
10368             }
10369             return verificationParams.getManifestDigest();
10370         }
10371
10372         private int installLocationPolicy(PackageInfoLite pkgLite) {
10373             String packageName = pkgLite.packageName;
10374             int installLocation = pkgLite.installLocation;
10375             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10376             // reader
10377             synchronized (mPackages) {
10378                 PackageParser.Package pkg = mPackages.get(packageName);
10379                 if (pkg != null) {
10380                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10381                         // Check for downgrading.
10382                         if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10383                             try {
10384                                 checkDowngrade(pkg, pkgLite);
10385                             } catch (PackageManagerException e) {
10386                                 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10387                                 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10388                             }
10389                         }
10390                         // Check for updated system application.
10391                         if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10392                             if (onSd) {
10393                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
10394                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10395                             }
10396                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10397                         } else {
10398                             if (onSd) {
10399                                 // Install flag overrides everything.
10400                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10401                             }
10402                             // If current upgrade specifies particular preference
10403                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10404                                 // Application explicitly specified internal.
10405                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10406                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10407                                 // App explictly prefers external. Let policy decide
10408                             } else {
10409                                 // Prefer previous location
10410                                 if (isExternal(pkg)) {
10411                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10412                                 }
10413                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10414                             }
10415                         }
10416                     } else {
10417                         // Invalid install. Return error code
10418                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10419                     }
10420                 }
10421             }
10422             // All the special cases have been taken care of.
10423             // Return result based on recommended install location.
10424             if (onSd) {
10425                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10426             }
10427             return pkgLite.recommendedInstallLocation;
10428         }
10429
10430         /*
10431          * Invoke remote method to get package information and install
10432          * location values. Override install location based on default
10433          * policy if needed and then create install arguments based
10434          * on the install location.
10435          */
10436         public void handleStartCopy() throws RemoteException {
10437             int ret = PackageManager.INSTALL_SUCCEEDED;
10438
10439             // If we're already staged, we've firmly committed to an install location
10440             if (origin.staged) {
10441                 if (origin.file != null) {
10442                     installFlags |= PackageManager.INSTALL_INTERNAL;
10443                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10444                 } else if (origin.cid != null) {
10445                     installFlags |= PackageManager.INSTALL_EXTERNAL;
10446                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
10447                 } else {
10448                     throw new IllegalStateException("Invalid stage location");
10449                 }
10450             }
10451
10452             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10453             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10454
10455             PackageInfoLite pkgLite = null;
10456
10457             if (onInt && onSd) {
10458                 // Check if both bits are set.
10459                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10460                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10461             } else {
10462                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10463                         packageAbiOverride);
10464
10465                 /*
10466                  * If we have too little free space, try to free cache
10467                  * before giving up.
10468                  */
10469                 if (!origin.staged && pkgLite.recommendedInstallLocation
10470                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10471                     // TODO: focus freeing disk space on the target device
10472                     final StorageManager storage = StorageManager.from(mContext);
10473                     final long lowThreshold = storage.getStorageLowBytes(
10474                             Environment.getDataDirectory());
10475
10476                     final long sizeBytes = mContainerService.calculateInstalledSize(
10477                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10478
10479                     if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10480                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10481                                 installFlags, packageAbiOverride);
10482                     }
10483
10484                     /*
10485                      * The cache free must have deleted the file we
10486                      * downloaded to install.
10487                      *
10488                      * TODO: fix the "freeCache" call to not delete
10489                      *       the file we care about.
10490                      */
10491                     if (pkgLite.recommendedInstallLocation
10492                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10493                         pkgLite.recommendedInstallLocation
10494                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10495                     }
10496                 }
10497             }
10498
10499             if (ret == PackageManager.INSTALL_SUCCEEDED) {
10500                 int loc = pkgLite.recommendedInstallLocation;
10501                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10502                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10503                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10504                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10505                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10506                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10507                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10508                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10509                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10510                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10511                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10512                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10513                 } else {
10514                     // Override with defaults if needed.
10515                     loc = installLocationPolicy(pkgLite);
10516                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10517                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10518                     } else if (!onSd && !onInt) {
10519                         // Override install location with flags
10520                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10521                             // Set the flag to install on external media.
10522                             installFlags |= PackageManager.INSTALL_EXTERNAL;
10523                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
10524                         } else {
10525                             // Make sure the flag for installing on external
10526                             // media is unset
10527                             installFlags |= PackageManager.INSTALL_INTERNAL;
10528                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10529                         }
10530                     }
10531                 }
10532             }
10533
10534             final InstallArgs args = createInstallArgs(this);
10535             mArgs = args;
10536
10537             if (ret == PackageManager.INSTALL_SUCCEEDED) {
10538                  /*
10539                  * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10540                  * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10541                  */
10542                 int userIdentifier = getUser().getIdentifier();
10543                 if (userIdentifier == UserHandle.USER_ALL
10544                         && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10545                     userIdentifier = UserHandle.USER_OWNER;
10546                 }
10547
10548                 /*
10549                  * Determine if we have any installed package verifiers. If we
10550                  * do, then we'll defer to them to verify the packages.
10551                  */
10552                 final int requiredUid = mRequiredVerifierPackage == null ? -1
10553                         : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10554                 if (!origin.existing && requiredUid != -1
10555                         && isVerificationEnabled(userIdentifier, installFlags)) {
10556                     final Intent verification = new Intent(
10557                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10558                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10559                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10560                             PACKAGE_MIME_TYPE);
10561                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10562
10563                     final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10564                             PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10565                             0 /* TODO: Which userId? */);
10566
10567                     if (DEBUG_VERIFY) {
10568                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10569                                 + verification.toString() + " with " + pkgLite.verifiers.length
10570                                 + " optional verifiers");
10571                     }
10572
10573                     final int verificationId = mPendingVerificationToken++;
10574
10575                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10576
10577                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10578                             installerPackageName);
10579
10580                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10581                             installFlags);
10582
10583                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10584                             pkgLite.packageName);
10585
10586                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10587                             pkgLite.versionCode);
10588
10589                     if (verificationParams != null) {
10590                         if (verificationParams.getVerificationURI() != null) {
10591                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10592                                  verificationParams.getVerificationURI());
10593                         }
10594                         if (verificationParams.getOriginatingURI() != null) {
10595                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10596                                   verificationParams.getOriginatingURI());
10597                         }
10598                         if (verificationParams.getReferrer() != null) {
10599                             verification.putExtra(Intent.EXTRA_REFERRER,
10600                                   verificationParams.getReferrer());
10601                         }
10602                         if (verificationParams.getOriginatingUid() >= 0) {
10603                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10604                                   verificationParams.getOriginatingUid());
10605                         }
10606                         if (verificationParams.getInstallerUid() >= 0) {
10607                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10608                                   verificationParams.getInstallerUid());
10609                         }
10610                     }
10611
10612                     final PackageVerificationState verificationState = new PackageVerificationState(
10613                             requiredUid, args);
10614
10615                     mPendingVerification.append(verificationId, verificationState);
10616
10617                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10618                             receivers, verificationState);
10619
10620                     /*
10621                      * If any sufficient verifiers were listed in the package
10622                      * manifest, attempt to ask them.
10623                      */
10624                     if (sufficientVerifiers != null) {
10625                         final int N = sufficientVerifiers.size();
10626                         if (N == 0) {
10627                             Slog.i(TAG, "Additional verifiers required, but none installed.");
10628                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10629                         } else {
10630                             for (int i = 0; i < N; i++) {
10631                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
10632
10633                                 final Intent sufficientIntent = new Intent(verification);
10634                                 sufficientIntent.setComponent(verifierComponent);
10635
10636                                 mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10637                             }
10638                         }
10639                     }
10640
10641                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10642                             mRequiredVerifierPackage, receivers);
10643                     if (ret == PackageManager.INSTALL_SUCCEEDED
10644                             && mRequiredVerifierPackage != null) {
10645                         /*
10646                          * Send the intent to the required verification agent,
10647                          * but only start the verification timeout after the
10648                          * target BroadcastReceivers have run.
10649                          */
10650                         verification.setComponent(requiredVerifierComponent);
10651                         mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10652                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10653                                 new BroadcastReceiver() {
10654                                     @Override
10655                                     public void onReceive(Context context, Intent intent) {
10656                                         final Message msg = mHandler
10657                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
10658                                         msg.arg1 = verificationId;
10659                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10660                                     }
10661                                 }, null, 0, null, null);
10662
10663                         /*
10664                          * We don't want the copy to proceed until verification
10665                          * succeeds, so null out this field.
10666                          */
10667                         mArgs = null;
10668                     }
10669                 } else {
10670                     /*
10671                      * No package verification is enabled, so immediately start
10672                      * the remote call to initiate copy using temporary file.
10673                      */
10674                     ret = args.copyApk(mContainerService, true);
10675                 }
10676             }
10677
10678             mRet = ret;
10679         }
10680
10681         @Override
10682         void handleReturnCode() {
10683             // If mArgs is null, then MCS couldn't be reached. When it
10684             // reconnects, it will try again to install. At that point, this
10685             // will succeed.
10686             if (mArgs != null) {
10687                 processPendingInstall(mArgs, mRet);
10688             }
10689         }
10690
10691         @Override
10692         void handleServiceError() {
10693             mArgs = createInstallArgs(this);
10694             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10695         }
10696
10697         public boolean isForwardLocked() {
10698             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10699         }
10700     }
10701
10702     /**
10703      * Used during creation of InstallArgs
10704      *
10705      * @param installFlags package installation flags
10706      * @return true if should be installed on external storage
10707      */
10708     private static boolean installOnExternalAsec(int installFlags) {
10709         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10710             return false;
10711         }
10712         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10713             return true;
10714         }
10715         return false;
10716     }
10717
10718     /**
10719      * Used during creation of InstallArgs
10720      *
10721      * @param installFlags package installation flags
10722      * @return true if should be installed as forward locked
10723      */
10724     private static boolean installForwardLocked(int installFlags) {
10725         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10726     }
10727
10728     private InstallArgs createInstallArgs(InstallParams params) {
10729         if (params.move != null) {
10730             return new MoveInstallArgs(params);
10731         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10732             return new AsecInstallArgs(params);
10733         } else {
10734             return new FileInstallArgs(params);
10735         }
10736     }
10737
10738     /**
10739      * Create args that describe an existing installed package. Typically used
10740      * when cleaning up old installs, or used as a move source.
10741      */
10742     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10743             String resourcePath, String[] instructionSets) {
10744         final boolean isInAsec;
10745         if (installOnExternalAsec(installFlags)) {
10746             /* Apps on SD card are always in ASEC containers. */
10747             isInAsec = true;
10748         } else if (installForwardLocked(installFlags)
10749                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10750             /*
10751              * Forward-locked apps are only in ASEC containers if they're the
10752              * new style
10753              */
10754             isInAsec = true;
10755         } else {
10756             isInAsec = false;
10757         }
10758
10759         if (isInAsec) {
10760             return new AsecInstallArgs(codePath, instructionSets,
10761                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10762         } else {
10763             return new FileInstallArgs(codePath, resourcePath, instructionSets);
10764         }
10765     }
10766
10767     static abstract class InstallArgs {
10768         /** @see InstallParams#origin */
10769         final OriginInfo origin;
10770         /** @see InstallParams#move */
10771         final MoveInfo move;
10772
10773         final IPackageInstallObserver2 observer;
10774         // Always refers to PackageManager flags only
10775         final int installFlags;
10776         final String installerPackageName;
10777         final String volumeUuid;
10778         final ManifestDigest manifestDigest;
10779         final UserHandle user;
10780         final String abiOverride;
10781
10782         // The list of instruction sets supported by this app. This is currently
10783         // only used during the rmdex() phase to clean up resources. We can get rid of this
10784         // if we move dex files under the common app path.
10785         /* nullable */ String[] instructionSets;
10786
10787         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10788                 int installFlags, String installerPackageName, String volumeUuid,
10789                 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10790                 String abiOverride) {
10791             this.origin = origin;
10792             this.move = move;
10793             this.installFlags = installFlags;
10794             this.observer = observer;
10795             this.installerPackageName = installerPackageName;
10796             this.volumeUuid = volumeUuid;
10797             this.manifestDigest = manifestDigest;
10798             this.user = user;
10799             this.instructionSets = instructionSets;
10800             this.abiOverride = abiOverride;
10801         }
10802
10803         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10804         abstract int doPreInstall(int status);
10805
10806         /**
10807          * Rename package into final resting place. All paths on the given
10808          * scanned package should be updated to reflect the rename.
10809          */
10810         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10811         abstract int doPostInstall(int status, int uid);
10812
10813         /** @see PackageSettingBase#codePathString */
10814         abstract String getCodePath();
10815         /** @see PackageSettingBase#resourcePathString */
10816         abstract String getResourcePath();
10817
10818         // Need installer lock especially for dex file removal.
10819         abstract void cleanUpResourcesLI();
10820         abstract boolean doPostDeleteLI(boolean delete);
10821
10822         /**
10823          * Called before the source arguments are copied. This is used mostly
10824          * for MoveParams when it needs to read the source file to put it in the
10825          * destination.
10826          */
10827         int doPreCopy() {
10828             return PackageManager.INSTALL_SUCCEEDED;
10829         }
10830
10831         /**
10832          * Called after the source arguments are copied. This is used mostly for
10833          * MoveParams when it needs to read the source file to put it in the
10834          * destination.
10835          *
10836          * @return
10837          */
10838         int doPostCopy(int uid) {
10839             return PackageManager.INSTALL_SUCCEEDED;
10840         }
10841
10842         protected boolean isFwdLocked() {
10843             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10844         }
10845
10846         protected boolean isExternalAsec() {
10847             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10848         }
10849
10850         UserHandle getUser() {
10851             return user;
10852         }
10853     }
10854
10855     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10856         if (!allCodePaths.isEmpty()) {
10857             if (instructionSets == null) {
10858                 throw new IllegalStateException("instructionSet == null");
10859             }
10860             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10861             for (String codePath : allCodePaths) {
10862                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10863                     int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10864                     if (retCode < 0) {
10865                         Slog.w(TAG, "Couldn't remove dex file for package: "
10866                                 + " at location " + codePath + ", retcode=" + retCode);
10867                         // we don't consider this to be a failure of the core package deletion
10868                     }
10869                 }
10870             }
10871         }
10872     }
10873
10874     /**
10875      * Logic to handle installation of non-ASEC applications, including copying
10876      * and renaming logic.
10877      */
10878     class FileInstallArgs extends InstallArgs {
10879         private File codeFile;
10880         private File resourceFile;
10881
10882         // Example topology:
10883         // /data/app/com.example/base.apk
10884         // /data/app/com.example/split_foo.apk
10885         // /data/app/com.example/lib/arm/libfoo.so
10886         // /data/app/com.example/lib/arm64/libfoo.so
10887         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10888
10889         /** New install */
10890         FileInstallArgs(InstallParams params) {
10891             super(params.origin, params.move, params.observer, params.installFlags,
10892                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10893                     params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10894             if (isFwdLocked()) {
10895                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
10896             }
10897         }
10898
10899         /** Existing install */
10900         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10901             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10902                     null);
10903             this.codeFile = (codePath != null) ? new File(codePath) : null;
10904             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10905         }
10906
10907         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10908             if (origin.staged) {
10909                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10910                 codeFile = origin.file;
10911                 resourceFile = origin.file;
10912                 return PackageManager.INSTALL_SUCCEEDED;
10913             }
10914
10915             try {
10916                 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10917                 codeFile = tempDir;
10918                 resourceFile = tempDir;
10919             } catch (IOException e) {
10920                 Slog.w(TAG, "Failed to create copy file: " + e);
10921                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10922             }
10923
10924             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10925                 @Override
10926                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10927                     if (!FileUtils.isValidExtFilename(name)) {
10928                         throw new IllegalArgumentException("Invalid filename: " + name);
10929                     }
10930                     try {
10931                         final File file = new File(codeFile, name);
10932                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10933                                 O_RDWR | O_CREAT, 0644);
10934                         Os.chmod(file.getAbsolutePath(), 0644);
10935                         return new ParcelFileDescriptor(fd);
10936                     } catch (ErrnoException e) {
10937                         throw new RemoteException("Failed to open: " + e.getMessage());
10938                     }
10939                 }
10940             };
10941
10942             int ret = PackageManager.INSTALL_SUCCEEDED;
10943             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10944             if (ret != PackageManager.INSTALL_SUCCEEDED) {
10945                 Slog.e(TAG, "Failed to copy package");
10946                 return ret;
10947             }
10948
10949             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10950             NativeLibraryHelper.Handle handle = null;
10951             try {
10952                 handle = NativeLibraryHelper.Handle.create(codeFile);
10953                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10954                         abiOverride);
10955             } catch (IOException e) {
10956                 Slog.e(TAG, "Copying native libraries failed", e);
10957                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10958             } finally {
10959                 IoUtils.closeQuietly(handle);
10960             }
10961
10962             return ret;
10963         }
10964
10965         int doPreInstall(int status) {
10966             if (status != PackageManager.INSTALL_SUCCEEDED) {
10967                 cleanUp();
10968             }
10969             return status;
10970         }
10971
10972         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10973             if (status != PackageManager.INSTALL_SUCCEEDED) {
10974                 cleanUp();
10975                 return false;
10976             }
10977
10978             final File targetDir = codeFile.getParentFile();
10979             final File beforeCodeFile = codeFile;
10980             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10981
10982             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10983             try {
10984                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10985             } catch (ErrnoException e) {
10986                 Slog.w(TAG, "Failed to rename", e);
10987                 return false;
10988             }
10989
10990             if (!SELinux.restoreconRecursive(afterCodeFile)) {
10991                 Slog.w(TAG, "Failed to restorecon");
10992                 return false;
10993             }
10994
10995             // Reflect the rename internally
10996             codeFile = afterCodeFile;
10997             resourceFile = afterCodeFile;
10998
10999             // Reflect the rename in scanned details
11000             pkg.codePath = afterCodeFile.getAbsolutePath();
11001             pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11002                     pkg.baseCodePath);
11003             pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11004                     pkg.splitCodePaths);
11005
11006             // Reflect the rename in app info
11007             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11008             pkg.applicationInfo.setCodePath(pkg.codePath);
11009             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11010             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11011             pkg.applicationInfo.setResourcePath(pkg.codePath);
11012             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11013             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11014
11015             return true;
11016         }
11017
11018         int doPostInstall(int status, int uid) {
11019             if (status != PackageManager.INSTALL_SUCCEEDED) {
11020                 cleanUp();
11021             }
11022             return status;
11023         }
11024
11025         @Override
11026         String getCodePath() {
11027             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11028         }
11029
11030         @Override
11031         String getResourcePath() {
11032             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11033         }
11034
11035         private boolean cleanUp() {
11036             if (codeFile == null || !codeFile.exists()) {
11037                 return false;
11038             }
11039
11040             if (codeFile.isDirectory()) {
11041                 mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11042             } else {
11043                 codeFile.delete();
11044             }
11045
11046             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11047                 resourceFile.delete();
11048             }
11049
11050             return true;
11051         }
11052
11053         void cleanUpResourcesLI() {
11054             // Try enumerating all code paths before deleting
11055             List<String> allCodePaths = Collections.EMPTY_LIST;
11056             if (codeFile != null && codeFile.exists()) {
11057                 try {
11058                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11059                     allCodePaths = pkg.getAllCodePaths();
11060                 } catch (PackageParserException e) {
11061                     // Ignored; we tried our best
11062                 }
11063             }
11064
11065             cleanUp();
11066             removeDexFiles(allCodePaths, instructionSets);
11067         }
11068
11069         boolean doPostDeleteLI(boolean delete) {
11070             // XXX err, shouldn't we respect the delete flag?
11071             cleanUpResourcesLI();
11072             return true;
11073         }
11074     }
11075
11076     private boolean isAsecExternal(String cid) {
11077         final String asecPath = PackageHelper.getSdFilesystem(cid);
11078         return !asecPath.startsWith(mAsecInternalPath);
11079     }
11080
11081     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11082             PackageManagerException {
11083         if (copyRet < 0) {
11084             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11085                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11086                 throw new PackageManagerException(copyRet, message);
11087             }
11088         }
11089     }
11090
11091     /**
11092      * Extract the MountService "container ID" from the full code path of an
11093      * .apk.
11094      */
11095     static String cidFromCodePath(String fullCodePath) {
11096         int eidx = fullCodePath.lastIndexOf("/");
11097         String subStr1 = fullCodePath.substring(0, eidx);
11098         int sidx = subStr1.lastIndexOf("/");
11099         return subStr1.substring(sidx+1, eidx);
11100     }
11101
11102     /**
11103      * Logic to handle installation of ASEC applications, including copying and
11104      * renaming logic.
11105      */
11106     class AsecInstallArgs extends InstallArgs {
11107         static final String RES_FILE_NAME = "pkg.apk";
11108         static final String PUBLIC_RES_FILE_NAME = "res.zip";
11109
11110         String cid;
11111         String packagePath;
11112         String resourcePath;
11113
11114         /** New install */
11115         AsecInstallArgs(InstallParams params) {
11116             super(params.origin, params.move, params.observer, params.installFlags,
11117                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11118                     params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11119         }
11120
11121         /** Existing install */
11122         AsecInstallArgs(String fullCodePath, String[] instructionSets,
11123                         boolean isExternal, boolean isForwardLocked) {
11124             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11125                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11126                     instructionSets, null);
11127             // Hackily pretend we're still looking at a full code path
11128             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11129                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11130             }
11131
11132             // Extract cid from fullCodePath
11133             int eidx = fullCodePath.lastIndexOf("/");
11134             String subStr1 = fullCodePath.substring(0, eidx);
11135             int sidx = subStr1.lastIndexOf("/");
11136             cid = subStr1.substring(sidx+1, eidx);
11137             setMountPath(subStr1);
11138         }
11139
11140         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11141             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11142                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11143                     instructionSets, null);
11144             this.cid = cid;
11145             setMountPath(PackageHelper.getSdDir(cid));
11146         }
11147
11148         void createCopyFile() {
11149             cid = mInstallerService.allocateExternalStageCidLegacy();
11150         }
11151
11152         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11153             if (origin.staged) {
11154                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11155                 cid = origin.cid;
11156                 setMountPath(PackageHelper.getSdDir(cid));
11157                 return PackageManager.INSTALL_SUCCEEDED;
11158             }
11159
11160             if (temp) {
11161                 createCopyFile();
11162             } else {
11163                 /*
11164                  * Pre-emptively destroy the container since it's destroyed if
11165                  * copying fails due to it existing anyway.
11166                  */
11167                 PackageHelper.destroySdDir(cid);
11168             }
11169
11170             final String newMountPath = imcs.copyPackageToContainer(
11171                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11172                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11173
11174             if (newMountPath != null) {
11175                 setMountPath(newMountPath);
11176                 return PackageManager.INSTALL_SUCCEEDED;
11177             } else {
11178                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11179             }
11180         }
11181
11182         @Override
11183         String getCodePath() {
11184             return packagePath;
11185         }
11186
11187         @Override
11188         String getResourcePath() {
11189             return resourcePath;
11190         }
11191
11192         int doPreInstall(int status) {
11193             if (status != PackageManager.INSTALL_SUCCEEDED) {
11194                 // Destroy container
11195                 PackageHelper.destroySdDir(cid);
11196             } else {
11197                 boolean mounted = PackageHelper.isContainerMounted(cid);
11198                 if (!mounted) {
11199                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11200                             Process.SYSTEM_UID);
11201                     if (newMountPath != null) {
11202                         setMountPath(newMountPath);
11203                     } else {
11204                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11205                     }
11206                 }
11207             }
11208             return status;
11209         }
11210
11211         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11212             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11213             String newMountPath = null;
11214             if (PackageHelper.isContainerMounted(cid)) {
11215                 // Unmount the container
11216                 if (!PackageHelper.unMountSdDir(cid)) {
11217                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11218                     return false;
11219                 }
11220             }
11221             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11222                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11223                         " which might be stale. Will try to clean up.");
11224                 // Clean up the stale container and proceed to recreate.
11225                 if (!PackageHelper.destroySdDir(newCacheId)) {
11226                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11227                     return false;
11228                 }
11229                 // Successfully cleaned up stale container. Try to rename again.
11230                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11231                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11232                             + " inspite of cleaning it up.");
11233                     return false;
11234                 }
11235             }
11236             if (!PackageHelper.isContainerMounted(newCacheId)) {
11237                 Slog.w(TAG, "Mounting container " + newCacheId);
11238                 newMountPath = PackageHelper.mountSdDir(newCacheId,
11239                         getEncryptKey(), Process.SYSTEM_UID);
11240             } else {
11241                 newMountPath = PackageHelper.getSdDir(newCacheId);
11242             }
11243             if (newMountPath == null) {
11244                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11245                 return false;
11246             }
11247             Log.i(TAG, "Succesfully renamed " + cid +
11248                     " to " + newCacheId +
11249                     " at new path: " + newMountPath);
11250             cid = newCacheId;
11251
11252             final File beforeCodeFile = new File(packagePath);
11253             setMountPath(newMountPath);
11254             final File afterCodeFile = new File(packagePath);
11255
11256             // Reflect the rename in scanned details
11257             pkg.codePath = afterCodeFile.getAbsolutePath();
11258             pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11259                     pkg.baseCodePath);
11260             pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11261                     pkg.splitCodePaths);
11262
11263             // Reflect the rename in app info
11264             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11265             pkg.applicationInfo.setCodePath(pkg.codePath);
11266             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11267             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11268             pkg.applicationInfo.setResourcePath(pkg.codePath);
11269             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11270             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11271
11272             return true;
11273         }
11274
11275         private void setMountPath(String mountPath) {
11276             final File mountFile = new File(mountPath);
11277
11278             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11279             if (monolithicFile.exists()) {
11280                 packagePath = monolithicFile.getAbsolutePath();
11281                 if (isFwdLocked()) {
11282                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11283                 } else {
11284                     resourcePath = packagePath;
11285                 }
11286             } else {
11287                 packagePath = mountFile.getAbsolutePath();
11288                 resourcePath = packagePath;
11289             }
11290         }
11291
11292         int doPostInstall(int status, int uid) {
11293             if (status != PackageManager.INSTALL_SUCCEEDED) {
11294                 cleanUp();
11295             } else {
11296                 final int groupOwner;
11297                 final String protectedFile;
11298                 if (isFwdLocked()) {
11299                     groupOwner = UserHandle.getSharedAppGid(uid);
11300                     protectedFile = RES_FILE_NAME;
11301                 } else {
11302                     groupOwner = -1;
11303                     protectedFile = null;
11304                 }
11305
11306                 if (uid < Process.FIRST_APPLICATION_UID
11307                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11308                     Slog.e(TAG, "Failed to finalize " + cid);
11309                     PackageHelper.destroySdDir(cid);
11310                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11311                 }
11312
11313                 boolean mounted = PackageHelper.isContainerMounted(cid);
11314                 if (!mounted) {
11315                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11316                 }
11317             }
11318             return status;
11319         }
11320
11321         private void cleanUp() {
11322             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11323
11324             // Destroy secure container
11325             PackageHelper.destroySdDir(cid);
11326         }
11327
11328         private List<String> getAllCodePaths() {
11329             final File codeFile = new File(getCodePath());
11330             if (codeFile != null && codeFile.exists()) {
11331                 try {
11332                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11333                     return pkg.getAllCodePaths();
11334                 } catch (PackageParserException e) {
11335                     // Ignored; we tried our best
11336                 }
11337             }
11338             return Collections.EMPTY_LIST;
11339         }
11340
11341         void cleanUpResourcesLI() {
11342             // Enumerate all code paths before deleting
11343             cleanUpResourcesLI(getAllCodePaths());
11344         }
11345
11346         private void cleanUpResourcesLI(List<String> allCodePaths) {
11347             cleanUp();
11348             removeDexFiles(allCodePaths, instructionSets);
11349         }
11350
11351         String getPackageName() {
11352             return getAsecPackageName(cid);
11353         }
11354
11355         boolean doPostDeleteLI(boolean delete) {
11356             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11357             final List<String> allCodePaths = getAllCodePaths();
11358             boolean mounted = PackageHelper.isContainerMounted(cid);
11359             if (mounted) {
11360                 // Unmount first
11361                 if (PackageHelper.unMountSdDir(cid)) {
11362                     mounted = false;
11363                 }
11364             }
11365             if (!mounted && delete) {
11366                 cleanUpResourcesLI(allCodePaths);
11367             }
11368             return !mounted;
11369         }
11370
11371         @Override
11372         int doPreCopy() {
11373             if (isFwdLocked()) {
11374                 if (!PackageHelper.fixSdPermissions(cid,
11375                         getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11376                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11377                 }
11378             }
11379
11380             return PackageManager.INSTALL_SUCCEEDED;
11381         }
11382
11383         @Override
11384         int doPostCopy(int uid) {
11385             if (isFwdLocked()) {
11386                 if (uid < Process.FIRST_APPLICATION_UID
11387                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11388                                 RES_FILE_NAME)) {
11389                     Slog.e(TAG, "Failed to finalize " + cid);
11390                     PackageHelper.destroySdDir(cid);
11391                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11392                 }
11393             }
11394
11395             return PackageManager.INSTALL_SUCCEEDED;
11396         }
11397     }
11398
11399     /**
11400      * Logic to handle movement of existing installed applications.
11401      */
11402     class MoveInstallArgs extends InstallArgs {
11403         private File codeFile;
11404         private File resourceFile;
11405
11406         /** New install */
11407         MoveInstallArgs(InstallParams params) {
11408             super(params.origin, params.move, params.observer, params.installFlags,
11409                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11410                     params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11411         }
11412
11413         int copyApk(IMediaContainerService imcs, boolean temp) {
11414             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11415                     + move.fromUuid + " to " + move.toUuid);
11416             synchronized (mInstaller) {
11417                 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11418                         move.dataAppName, move.appId, move.seinfo) != 0) {
11419                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11420                 }
11421             }
11422
11423             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11424             resourceFile = codeFile;
11425             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11426
11427             return PackageManager.INSTALL_SUCCEEDED;
11428         }
11429
11430         int doPreInstall(int status) {
11431             if (status != PackageManager.INSTALL_SUCCEEDED) {
11432                 cleanUp(move.toUuid);
11433             }
11434             return status;
11435         }
11436
11437         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11438             if (status != PackageManager.INSTALL_SUCCEEDED) {
11439                 cleanUp(move.toUuid);
11440                 return false;
11441             }
11442
11443             // Reflect the move in app info
11444             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11445             pkg.applicationInfo.setCodePath(pkg.codePath);
11446             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11447             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11448             pkg.applicationInfo.setResourcePath(pkg.codePath);
11449             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11450             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11451
11452             return true;
11453         }
11454
11455         int doPostInstall(int status, int uid) {
11456             if (status == PackageManager.INSTALL_SUCCEEDED) {
11457                 cleanUp(move.fromUuid);
11458             } else {
11459                 cleanUp(move.toUuid);
11460             }
11461             return status;
11462         }
11463
11464         @Override
11465         String getCodePath() {
11466             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11467         }
11468
11469         @Override
11470         String getResourcePath() {
11471             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11472         }
11473
11474         private boolean cleanUp(String volumeUuid) {
11475             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11476                     move.dataAppName);
11477             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11478             synchronized (mInstallLock) {
11479                 // Clean up both app data and code
11480                 removeDataDirsLI(volumeUuid, move.packageName);
11481                 if (codeFile.isDirectory()) {
11482                     mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11483                 } else {
11484                     codeFile.delete();
11485                 }
11486             }
11487             return true;
11488         }
11489
11490         void cleanUpResourcesLI() {
11491             throw new UnsupportedOperationException();
11492         }
11493
11494         boolean doPostDeleteLI(boolean delete) {
11495             throw new UnsupportedOperationException();
11496         }
11497     }
11498
11499     static String getAsecPackageName(String packageCid) {
11500         int idx = packageCid.lastIndexOf("-");
11501         if (idx == -1) {
11502             return packageCid;
11503         }
11504         return packageCid.substring(0, idx);
11505     }
11506
11507     // Utility method used to create code paths based on package name and available index.
11508     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11509         String idxStr = "";
11510         int idx = 1;
11511         // Fall back to default value of idx=1 if prefix is not
11512         // part of oldCodePath
11513         if (oldCodePath != null) {
11514             String subStr = oldCodePath;
11515             // Drop the suffix right away
11516             if (suffix != null && subStr.endsWith(suffix)) {
11517                 subStr = subStr.substring(0, subStr.length() - suffix.length());
11518             }
11519             // If oldCodePath already contains prefix find out the
11520             // ending index to either increment or decrement.
11521             int sidx = subStr.lastIndexOf(prefix);
11522             if (sidx != -1) {
11523                 subStr = subStr.substring(sidx + prefix.length());
11524                 if (subStr != null) {
11525                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11526                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11527                     }
11528                     try {
11529                         idx = Integer.parseInt(subStr);
11530                         if (idx <= 1) {
11531                             idx++;
11532                         } else {
11533                             idx--;
11534                         }
11535                     } catch(NumberFormatException e) {
11536                     }
11537                 }
11538             }
11539         }
11540         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11541         return prefix + idxStr;
11542     }
11543
11544     private File getNextCodePath(File targetDir, String packageName) {
11545         int suffix = 1;
11546         File result;
11547         do {
11548             result = new File(targetDir, packageName + "-" + suffix);
11549             suffix++;
11550         } while (result.exists());
11551         return result;
11552     }
11553
11554     // Utility method that returns the relative package path with respect
11555     // to the installation directory. Like say for /data/data/com.test-1.apk
11556     // string com.test-1 is returned.
11557     static String deriveCodePathName(String codePath) {
11558         if (codePath == null) {
11559             return null;
11560         }
11561         final File codeFile = new File(codePath);
11562         final String name = codeFile.getName();
11563         if (codeFile.isDirectory()) {
11564             return name;
11565         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11566             final int lastDot = name.lastIndexOf('.');
11567             return name.substring(0, lastDot);
11568         } else {
11569             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11570             return null;
11571         }
11572     }
11573
11574     class PackageInstalledInfo {
11575         String name;
11576         int uid;
11577         // The set of users that originally had this package installed.
11578         int[] origUsers;
11579         // The set of users that now have this package installed.
11580         int[] newUsers;
11581         PackageParser.Package pkg;
11582         int returnCode;
11583         String returnMsg;
11584         PackageRemovedInfo removedInfo;
11585
11586         public void setError(int code, String msg) {
11587             returnCode = code;
11588             returnMsg = msg;
11589             Slog.w(TAG, msg);
11590         }
11591
11592         public void setError(String msg, PackageParserException e) {
11593             returnCode = e.error;
11594             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11595             Slog.w(TAG, msg, e);
11596         }
11597
11598         public void setError(String msg, PackageManagerException e) {
11599             returnCode = e.error;
11600             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11601             Slog.w(TAG, msg, e);
11602         }
11603
11604         // In some error cases we want to convey more info back to the observer
11605         String origPackage;
11606         String origPermission;
11607     }
11608
11609     /*
11610      * Install a non-existing package.
11611      */
11612     private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11613             UserHandle user, String installerPackageName, String volumeUuid,
11614             PackageInstalledInfo res) {
11615         // Remember this for later, in case we need to rollback this install
11616         String pkgName = pkg.packageName;
11617
11618         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11619         final boolean dataDirExists = Environment
11620                 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11621         synchronized(mPackages) {
11622             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11623                 // A package with the same name is already installed, though
11624                 // it has been renamed to an older name.  The package we
11625                 // are trying to install should be installed as an update to
11626                 // the existing one, but that has not been requested, so bail.
11627                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11628                         + " without first uninstalling package running as "
11629                         + mSettings.mRenamedPackages.get(pkgName));
11630                 return;
11631             }
11632             if (mPackages.containsKey(pkgName)) {
11633                 // Don't allow installation over an existing package with the same name.
11634                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11635                         + " without first uninstalling.");
11636                 return;
11637             }
11638         }
11639
11640         try {
11641             PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11642                     System.currentTimeMillis(), user);
11643
11644             updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11645             // delete the partially installed application. the data directory will have to be
11646             // restored if it was already existing
11647             if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11648                 // remove package from internal structures.  Note that we want deletePackageX to
11649                 // delete the package data and cache directories that it created in
11650                 // scanPackageLocked, unless those directories existed before we even tried to
11651                 // install.
11652                 deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11653                         dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11654                                 res.removedInfo, true);
11655             }
11656
11657         } catch (PackageManagerException e) {
11658             res.setError("Package couldn't be installed in " + pkg.codePath, e);
11659         }
11660     }
11661
11662     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11663         // Can't rotate keys during boot or if sharedUser.
11664         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11665                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11666             return false;
11667         }
11668         // app is using upgradeKeySets; make sure all are valid
11669         KeySetManagerService ksms = mSettings.mKeySetManagerService;
11670         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11671         for (int i = 0; i < upgradeKeySets.length; i++) {
11672             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11673                 Slog.wtf(TAG, "Package "
11674                          + (oldPs.name != null ? oldPs.name : "<null>")
11675                          + " contains upgrade-key-set reference to unknown key-set: "
11676                          + upgradeKeySets[i]
11677                          + " reverting to signatures check.");
11678                 return false;
11679             }
11680         }
11681         return true;
11682     }
11683
11684     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11685         // Upgrade keysets are being used.  Determine if new package has a superset of the
11686         // required keys.
11687         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11688         KeySetManagerService ksms = mSettings.mKeySetManagerService;
11689         for (int i = 0; i < upgradeKeySets.length; i++) {
11690             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11691             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11692                 return true;
11693             }
11694         }
11695         return false;
11696     }
11697
11698     private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11699             UserHandle user, String installerPackageName, String volumeUuid,
11700             PackageInstalledInfo res) {
11701         final PackageParser.Package oldPackage;
11702         final String pkgName = pkg.packageName;
11703         final int[] allUsers;
11704         final boolean[] perUserInstalled;
11705         final boolean weFroze;
11706
11707         // First find the old package info and check signatures
11708         synchronized(mPackages) {
11709             oldPackage = mPackages.get(pkgName);
11710             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11711             final PackageSetting ps = mSettings.mPackages.get(pkgName);
11712             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11713                 if(!checkUpgradeKeySetLP(ps, pkg)) {
11714                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11715                             "New package not signed by keys specified by upgrade-keysets: "
11716                             + pkgName);
11717                     return;
11718                 }
11719             } else {
11720                 // default to original signature matching
11721                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11722                     != PackageManager.SIGNATURE_MATCH) {
11723                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11724                             "New package has a different signature: " + pkgName);
11725                     return;
11726                 }
11727             }
11728
11729             // In case of rollback, remember per-user/profile install state
11730             allUsers = sUserManager.getUserIds();
11731             perUserInstalled = new boolean[allUsers.length];
11732             for (int i = 0; i < allUsers.length; i++) {
11733                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11734             }
11735
11736             // Mark the app as frozen to prevent launching during the upgrade
11737             // process, and then kill all running instances
11738             if (!ps.frozen) {
11739                 ps.frozen = true;
11740                 weFroze = true;
11741             } else {
11742                 weFroze = false;
11743             }
11744         }
11745
11746         // Now that we're guarded by frozen state, kill app during upgrade
11747         killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11748
11749         try {
11750             boolean sysPkg = (isSystemApp(oldPackage));
11751             if (sysPkg) {
11752                 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11753                         user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11754             } else {
11755                 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11756                         user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11757             }
11758         } finally {
11759             // Regardless of success or failure of upgrade steps above, always
11760             // unfreeze the package if we froze it
11761             if (weFroze) {
11762                 unfreezePackage(pkgName);
11763             }
11764         }
11765     }
11766
11767     private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11768             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11769             int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11770             String volumeUuid, PackageInstalledInfo res) {
11771         String pkgName = deletedPackage.packageName;
11772         boolean deletedPkg = true;
11773         boolean updatedSettings = false;
11774
11775         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11776                 + deletedPackage);
11777         long origUpdateTime;
11778         if (pkg.mExtras != null) {
11779             origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11780         } else {
11781             origUpdateTime = 0;
11782         }
11783
11784         // First delete the existing package while retaining the data directory
11785         if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11786                 res.removedInfo, true)) {
11787             // If the existing package wasn't successfully deleted
11788             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11789             deletedPkg = false;
11790         } else {
11791             // Successfully deleted the old package; proceed with replace.
11792
11793             // If deleted package lived in a container, give users a chance to
11794             // relinquish resources before killing.
11795             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11796                 if (DEBUG_INSTALL) {
11797                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11798                 }
11799                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11800                 final ArrayList<String> pkgList = new ArrayList<String>(1);
11801                 pkgList.add(deletedPackage.applicationInfo.packageName);
11802                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11803             }
11804
11805             deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11806             try {
11807                 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11808                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11809                 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11810                         perUserInstalled, res, user);
11811                 updatedSettings = true;
11812             } catch (PackageManagerException e) {
11813                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
11814             }
11815         }
11816
11817         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11818             // remove package from internal structures.  Note that we want deletePackageX to
11819             // delete the package data and cache directories that it created in
11820             // scanPackageLocked, unless those directories existed before we even tried to
11821             // install.
11822             if(updatedSettings) {
11823                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11824                 deletePackageLI(
11825                         pkgName, null, true, allUsers, perUserInstalled,
11826                         PackageManager.DELETE_KEEP_DATA,
11827                                 res.removedInfo, true);
11828             }
11829             // Since we failed to install the new package we need to restore the old
11830             // package that we deleted.
11831             if (deletedPkg) {
11832                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11833                 File restoreFile = new File(deletedPackage.codePath);
11834                 // Parse old package
11835                 boolean oldExternal = isExternal(deletedPackage);
11836                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11837                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11838                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11839                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11840                 try {
11841                     scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11842                 } catch (PackageManagerException e) {
11843                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11844                             + e.getMessage());
11845                     return;
11846                 }
11847                 // Restore of old package succeeded. Update permissions.
11848                 // writer
11849                 synchronized (mPackages) {
11850                     updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11851                             UPDATE_PERMISSIONS_ALL);
11852                     // can downgrade to reader
11853                     mSettings.writeLPr();
11854                 }
11855                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11856             }
11857         }
11858     }
11859
11860     private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11861             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11862             int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11863             String volumeUuid, PackageInstalledInfo res) {
11864         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11865                 + ", old=" + deletedPackage);
11866         boolean disabledSystem = false;
11867         boolean updatedSettings = false;
11868         parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11869         if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11870                 != 0) {
11871             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11872         }
11873         String packageName = deletedPackage.packageName;
11874         if (packageName == null) {
11875             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11876                     "Attempt to delete null packageName.");
11877             return;
11878         }
11879         PackageParser.Package oldPkg;
11880         PackageSetting oldPkgSetting;
11881         // reader
11882         synchronized (mPackages) {
11883             oldPkg = mPackages.get(packageName);
11884             oldPkgSetting = mSettings.mPackages.get(packageName);
11885             if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11886                     (oldPkgSetting == null)) {
11887                 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11888                         "Couldn't find package:" + packageName + " information");
11889                 return;
11890             }
11891         }
11892
11893         res.removedInfo.uid = oldPkg.applicationInfo.uid;
11894         res.removedInfo.removedPackage = packageName;
11895         // Remove existing system package
11896         removePackageLI(oldPkgSetting, true);
11897         // writer
11898         synchronized (mPackages) {
11899             disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11900             if (!disabledSystem && deletedPackage != null) {
11901                 // We didn't need to disable the .apk as a current system package,
11902                 // which means we are replacing another update that is already
11903                 // installed.  We need to make sure to delete the older one's .apk.
11904                 res.removedInfo.args = createInstallArgsForExisting(0,
11905                         deletedPackage.applicationInfo.getCodePath(),
11906                         deletedPackage.applicationInfo.getResourcePath(),
11907                         getAppDexInstructionSets(deletedPackage.applicationInfo));
11908             } else {
11909                 res.removedInfo.args = null;
11910             }
11911         }
11912
11913         // Successfully disabled the old package. Now proceed with re-installation
11914         deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11915
11916         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11917         pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11918
11919         PackageParser.Package newPackage = null;
11920         try {
11921             newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11922             if (newPackage.mExtras != null) {
11923                 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11924                 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11925                 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11926
11927                 // is the update attempting to change shared user? that isn't going to work...
11928                 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11929                     res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11930                             "Forbidding shared user change from " + oldPkgSetting.sharedUser
11931                             + " to " + newPkgSetting.sharedUser);
11932                     updatedSettings = true;
11933                 }
11934             }
11935
11936             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11937                 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11938                         perUserInstalled, res, user);
11939                 updatedSettings = true;
11940             }
11941
11942         } catch (PackageManagerException e) {
11943             res.setError("Package couldn't be installed in " + pkg.codePath, e);
11944         }
11945
11946         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11947             // Re installation failed. Restore old information
11948             // Remove new pkg information
11949             if (newPackage != null) {
11950                 removeInstalledPackageLI(newPackage, true);
11951             }
11952             // Add back the old system package
11953             try {
11954                 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11955             } catch (PackageManagerException e) {
11956                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11957             }
11958             // Restore the old system information in Settings
11959             synchronized (mPackages) {
11960                 if (disabledSystem) {
11961                     mSettings.enableSystemPackageLPw(packageName);
11962                 }
11963                 if (updatedSettings) {
11964                     mSettings.setInstallerPackageName(packageName,
11965                             oldPkgSetting.installerPackageName);
11966                 }
11967                 mSettings.writeLPr();
11968             }
11969         }
11970     }
11971
11972     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11973             String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11974             UserHandle user) {
11975         String pkgName = newPackage.packageName;
11976         synchronized (mPackages) {
11977             //write settings. the installStatus will be incomplete at this stage.
11978             //note that the new package setting would have already been
11979             //added to mPackages. It hasn't been persisted yet.
11980             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11981             mSettings.writeLPr();
11982         }
11983
11984         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11985
11986         synchronized (mPackages) {
11987             updatePermissionsLPw(newPackage.packageName, newPackage,
11988                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11989                             ? UPDATE_PERMISSIONS_ALL : 0));
11990             // For system-bundled packages, we assume that installing an upgraded version
11991             // of the package implies that the user actually wants to run that new code,
11992             // so we enable the package.
11993             PackageSetting ps = mSettings.mPackages.get(pkgName);
11994             if (ps != null) {
11995                 if (isSystemApp(newPackage)) {
11996                     // NB: implicit assumption that system package upgrades apply to all users
11997                     if (DEBUG_INSTALL) {
11998                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11999                     }
12000                     if (res.origUsers != null) {
12001                         for (int userHandle : res.origUsers) {
12002                             ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12003                                     userHandle, installerPackageName);
12004                         }
12005                     }
12006                     // Also convey the prior install/uninstall state
12007                     if (allUsers != null && perUserInstalled != null) {
12008                         for (int i = 0; i < allUsers.length; i++) {
12009                             if (DEBUG_INSTALL) {
12010                                 Slog.d(TAG, "    user " + allUsers[i]
12011                                         + " => " + perUserInstalled[i]);
12012                             }
12013                             ps.setInstalled(perUserInstalled[i], allUsers[i]);
12014                         }
12015                         // these install state changes will be persisted in the
12016                         // upcoming call to mSettings.writeLPr().
12017                     }
12018                 }
12019                 // It's implied that when a user requests installation, they want the app to be
12020                 // installed and enabled.
12021                 int userId = user.getIdentifier();
12022                 if (userId != UserHandle.USER_ALL) {
12023                     ps.setInstalled(true, userId);
12024                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12025                 }
12026             }
12027             res.name = pkgName;
12028             res.uid = newPackage.applicationInfo.uid;
12029             res.pkg = newPackage;
12030             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12031             mSettings.setInstallerPackageName(pkgName, installerPackageName);
12032             res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12033             //to update install status
12034             mSettings.writeLPr();
12035         }
12036     }
12037
12038     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12039         final int installFlags = args.installFlags;
12040         final String installerPackageName = args.installerPackageName;
12041         final String volumeUuid = args.volumeUuid;
12042         final File tmpPackageFile = new File(args.getCodePath());
12043         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12044         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12045                 || (args.volumeUuid != null));
12046         boolean replace = false;
12047         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12048         if (args.move != null) {
12049             // moving a complete application; perfom an initial scan on the new install location
12050             scanFlags |= SCAN_INITIAL;
12051         }
12052         // Result object to be returned
12053         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12054
12055         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12056         // Retrieve PackageSettings and parse package
12057         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12058                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12059                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12060         PackageParser pp = new PackageParser();
12061         pp.setSeparateProcesses(mSeparateProcesses);
12062         pp.setDisplayMetrics(mMetrics);
12063
12064         final PackageParser.Package pkg;
12065         try {
12066             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12067         } catch (PackageParserException e) {
12068             res.setError("Failed parse during installPackageLI", e);
12069             return;
12070         }
12071
12072         // Mark that we have an install time CPU ABI override.
12073         pkg.cpuAbiOverride = args.abiOverride;
12074
12075         String pkgName = res.name = pkg.packageName;
12076         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12077             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12078                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12079                 return;
12080             }
12081         }
12082
12083         try {
12084             pp.collectCertificates(pkg, parseFlags);
12085             pp.collectManifestDigest(pkg);
12086         } catch (PackageParserException e) {
12087             res.setError("Failed collect during installPackageLI", e);
12088             return;
12089         }
12090
12091         /* If the installer passed in a manifest digest, compare it now. */
12092         if (args.manifestDigest != null) {
12093             if (DEBUG_INSTALL) {
12094                 final String parsedManifest = pkg.manifestDigest == null ? "null"
12095                         : pkg.manifestDigest.toString();
12096                 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12097                         + parsedManifest);
12098             }
12099
12100             if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12101                 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12102                 return;
12103             }
12104         } else if (DEBUG_INSTALL) {
12105             final String parsedManifest = pkg.manifestDigest == null
12106                     ? "null" : pkg.manifestDigest.toString();
12107             Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12108         }
12109
12110         // Get rid of all references to package scan path via parser.
12111         pp = null;
12112         String oldCodePath = null;
12113         boolean systemApp = false;
12114         synchronized (mPackages) {
12115             // Check if installing already existing package
12116             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12117                 String oldName = mSettings.mRenamedPackages.get(pkgName);
12118                 if (pkg.mOriginalPackages != null
12119                         && pkg.mOriginalPackages.contains(oldName)
12120                         && mPackages.containsKey(oldName)) {
12121                     // This package is derived from an original package,
12122                     // and this device has been updating from that original
12123                     // name.  We must continue using the original name, so
12124                     // rename the new package here.
12125                     pkg.setPackageName(oldName);
12126                     pkgName = pkg.packageName;
12127                     replace = true;
12128                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12129                             + oldName + " pkgName=" + pkgName);
12130                 } else if (mPackages.containsKey(pkgName)) {
12131                     // This package, under its official name, already exists
12132                     // on the device; we should replace it.
12133                     replace = true;
12134                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12135                 }
12136
12137                 // Prevent apps opting out from runtime permissions
12138                 if (replace) {
12139                     PackageParser.Package oldPackage = mPackages.get(pkgName);
12140                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12141                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12142                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12143                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12144                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12145                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12146                                         + " doesn't support runtime permissions but the old"
12147                                         + " target SDK " + oldTargetSdk + " does.");
12148                         return;
12149                     }
12150                 }
12151             }
12152
12153             PackageSetting ps = mSettings.mPackages.get(pkgName);
12154             if (ps != null) {
12155                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12156
12157                 // Quick sanity check that we're signed correctly if updating;
12158                 // we'll check this again later when scanning, but we want to
12159                 // bail early here before tripping over redefined permissions.
12160                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12161                     if (!checkUpgradeKeySetLP(ps, pkg)) {
12162                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12163                                 + pkg.packageName + " upgrade keys do not match the "
12164                                 + "previously installed version");
12165                         return;
12166                     }
12167                 } else {
12168                     try {
12169                         verifySignaturesLP(ps, pkg);
12170                     } catch (PackageManagerException e) {
12171                         res.setError(e.error, e.getMessage());
12172                         return;
12173                     }
12174                 }
12175
12176                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12177                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12178                     systemApp = (ps.pkg.applicationInfo.flags &
12179                             ApplicationInfo.FLAG_SYSTEM) != 0;
12180                 }
12181                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12182             }
12183
12184             // Check whether the newly-scanned package wants to define an already-defined perm
12185             int N = pkg.permissions.size();
12186             for (int i = N-1; i >= 0; i--) {
12187                 PackageParser.Permission perm = pkg.permissions.get(i);
12188                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12189                 if (bp != null) {
12190                     // If the defining package is signed with our cert, it's okay.  This
12191                     // also includes the "updating the same package" case, of course.
12192                     // "updating same package" could also involve key-rotation.
12193                     final boolean sigsOk;
12194                     if (bp.sourcePackage.equals(pkg.packageName)
12195                             && (bp.packageSetting instanceof PackageSetting)
12196                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12197                                     scanFlags))) {
12198                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12199                     } else {
12200                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12201                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12202                     }
12203                     if (!sigsOk) {
12204                         // If the owning package is the system itself, we log but allow
12205                         // install to proceed; we fail the install on all other permission
12206                         // redefinitions.
12207                         if (!bp.sourcePackage.equals("android")) {
12208                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12209                                     + pkg.packageName + " attempting to redeclare permission "
12210                                     + perm.info.name + " already owned by " + bp.sourcePackage);
12211                             res.origPermission = perm.info.name;
12212                             res.origPackage = bp.sourcePackage;
12213                             return;
12214                         } else {
12215                             Slog.w(TAG, "Package " + pkg.packageName
12216                                     + " attempting to redeclare system permission "
12217                                     + perm.info.name + "; ignoring new declaration");
12218                             pkg.permissions.remove(i);
12219                         }
12220                     }
12221                 }
12222             }
12223
12224         }
12225
12226         if (systemApp && onExternal) {
12227             // Disable updates to system apps on sdcard
12228             res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12229                     "Cannot install updates to system apps on sdcard");
12230             return;
12231         }
12232
12233         if (args.move != null) {
12234             // We did an in-place move, so dex is ready to roll
12235             scanFlags |= SCAN_NO_DEX;
12236             scanFlags |= SCAN_MOVE;
12237         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12238             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12239             scanFlags |= SCAN_NO_DEX;
12240
12241             try {
12242                 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12243                         true /* extract libs */);
12244             } catch (PackageManagerException pme) {
12245                 Slog.e(TAG, "Error deriving application ABI", pme);
12246                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12247                 return;
12248             }
12249
12250             // Run dexopt before old package gets removed, to minimize time when app is unavailable
12251             int result = mPackageDexOptimizer
12252                     .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12253                             false /* defer */, false /* inclDependencies */);
12254             if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12255                 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12256                 return;
12257             }
12258         }
12259
12260         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12261             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12262             return;
12263         }
12264
12265         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12266
12267         if (replace) {
12268             replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12269                     installerPackageName, volumeUuid, res);
12270         } else {
12271             installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12272                     args.user, installerPackageName, volumeUuid, res);
12273         }
12274         synchronized (mPackages) {
12275             final PackageSetting ps = mSettings.mPackages.get(pkgName);
12276             if (ps != null) {
12277                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12278             }
12279         }
12280     }
12281
12282     private void startIntentFilterVerifications(int userId, boolean replacing,
12283             PackageParser.Package pkg) {
12284         if (mIntentFilterVerifierComponent == null) {
12285             Slog.w(TAG, "No IntentFilter verification will not be done as "
12286                     + "there is no IntentFilterVerifier available!");
12287             return;
12288         }
12289
12290         final int verifierUid = getPackageUid(
12291                 mIntentFilterVerifierComponent.getPackageName(),
12292                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12293
12294         mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12295         final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12296         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12297         mHandler.sendMessage(msg);
12298     }
12299
12300     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12301             PackageParser.Package pkg) {
12302         int size = pkg.activities.size();
12303         if (size == 0) {
12304             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12305                     "No activity, so no need to verify any IntentFilter!");
12306             return;
12307         }
12308
12309         final boolean hasDomainURLs = hasDomainURLs(pkg);
12310         if (!hasDomainURLs) {
12311             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12312                     "No domain URLs, so no need to verify any IntentFilter!");
12313             return;
12314         }
12315
12316         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12317                 + " if any IntentFilter from the " + size
12318                 + " Activities needs verification ...");
12319
12320         int count = 0;
12321         final String packageName = pkg.packageName;
12322
12323         synchronized (mPackages) {
12324             // If this is a new install and we see that we've already run verification for this
12325             // package, we have nothing to do: it means the state was restored from backup.
12326             if (!replacing) {
12327                 IntentFilterVerificationInfo ivi =
12328                         mSettings.getIntentFilterVerificationLPr(packageName);
12329                 if (ivi != null) {
12330                     if (DEBUG_DOMAIN_VERIFICATION) {
12331                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
12332                                 + ivi.getStatusString());
12333                     }
12334                     return;
12335                 }
12336             }
12337
12338             // If any filters need to be verified, then all need to be.
12339             boolean needToVerify = false;
12340             for (PackageParser.Activity a : pkg.activities) {
12341                 for (ActivityIntentInfo filter : a.intents) {
12342                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12343                         if (DEBUG_DOMAIN_VERIFICATION) {
12344                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12345                         }
12346                         needToVerify = true;
12347                         break;
12348                     }
12349                 }
12350             }
12351
12352             if (needToVerify) {
12353                 final int verificationId = mIntentFilterVerificationToken++;
12354                 for (PackageParser.Activity a : pkg.activities) {
12355                     for (ActivityIntentInfo filter : a.intents) {
12356                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12357                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12358                                     "Verification needed for IntentFilter:" + filter.toString());
12359                             mIntentFilterVerifier.addOneIntentFilterVerification(
12360                                     verifierUid, userId, verificationId, filter, packageName);
12361                             count++;
12362                         }
12363                     }
12364                 }
12365             }
12366         }
12367
12368         if (count > 0) {
12369             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12370                     + " IntentFilter verification" + (count > 1 ? "s" : "")
12371                     +  " for userId:" + userId);
12372             mIntentFilterVerifier.startVerifications(userId);
12373         } else {
12374             if (DEBUG_DOMAIN_VERIFICATION) {
12375                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12376             }
12377         }
12378     }
12379
12380     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12381         final ComponentName cn  = filter.activity.getComponentName();
12382         final String packageName = cn.getPackageName();
12383
12384         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12385                 packageName);
12386         if (ivi == null) {
12387             return true;
12388         }
12389         int status = ivi.getStatus();
12390         switch (status) {
12391             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12392             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12393                 return true;
12394
12395             default:
12396                 // Nothing to do
12397                 return false;
12398         }
12399     }
12400
12401     private static boolean isMultiArch(PackageSetting ps) {
12402         return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12403     }
12404
12405     private static boolean isMultiArch(ApplicationInfo info) {
12406         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12407     }
12408
12409     private static boolean isExternal(PackageParser.Package pkg) {
12410         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12411     }
12412
12413     private static boolean isExternal(PackageSetting ps) {
12414         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12415     }
12416
12417     private static boolean isExternal(ApplicationInfo info) {
12418         return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12419     }
12420
12421     private static boolean isSystemApp(PackageParser.Package pkg) {
12422         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12423     }
12424
12425     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12426         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12427     }
12428
12429     private static boolean hasDomainURLs(PackageParser.Package pkg) {
12430         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12431     }
12432
12433     private static boolean isSystemApp(PackageSetting ps) {
12434         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12435     }
12436
12437     private static boolean isUpdatedSystemApp(PackageSetting ps) {
12438         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12439     }
12440
12441     private int packageFlagsToInstallFlags(PackageSetting ps) {
12442         int installFlags = 0;
12443         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12444             // This existing package was an external ASEC install when we have
12445             // the external flag without a UUID
12446             installFlags |= PackageManager.INSTALL_EXTERNAL;
12447         }
12448         if (ps.isForwardLocked()) {
12449             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12450         }
12451         return installFlags;
12452     }
12453
12454     private void deleteTempPackageFiles() {
12455         final FilenameFilter filter = new FilenameFilter() {
12456             public boolean accept(File dir, String name) {
12457                 return name.startsWith("vmdl") && name.endsWith(".tmp");
12458             }
12459         };
12460         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12461             file.delete();
12462         }
12463     }
12464
12465     @Override
12466     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12467             int flags) {
12468         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12469                 flags);
12470     }
12471
12472     @Override
12473     public void deletePackage(final String packageName,
12474             final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12475         mContext.enforceCallingOrSelfPermission(
12476                 android.Manifest.permission.DELETE_PACKAGES, null);
12477         Preconditions.checkNotNull(packageName);
12478         Preconditions.checkNotNull(observer);
12479         final int uid = Binder.getCallingUid();
12480         if (UserHandle.getUserId(uid) != userId) {
12481             mContext.enforceCallingPermission(
12482                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12483                     "deletePackage for user " + userId);
12484         }
12485         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12486             try {
12487                 observer.onPackageDeleted(packageName,
12488                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12489             } catch (RemoteException re) {
12490             }
12491             return;
12492         }
12493
12494         boolean uninstallBlocked = false;
12495         if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12496             int[] users = sUserManager.getUserIds();
12497             for (int i = 0; i < users.length; ++i) {
12498                 if (getBlockUninstallForUser(packageName, users[i])) {
12499                     uninstallBlocked = true;
12500                     break;
12501                 }
12502             }
12503         } else {
12504             uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12505         }
12506         if (uninstallBlocked) {
12507             try {
12508                 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12509                         null);
12510             } catch (RemoteException re) {
12511             }
12512             return;
12513         }
12514
12515         if (DEBUG_REMOVE) {
12516             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12517         }
12518         // Queue up an async operation since the package deletion may take a little while.
12519         mHandler.post(new Runnable() {
12520             public void run() {
12521                 mHandler.removeCallbacks(this);
12522                 final int returnCode = deletePackageX(packageName, userId, flags);
12523                 if (observer != null) {
12524                     try {
12525                         observer.onPackageDeleted(packageName, returnCode, null);
12526                     } catch (RemoteException e) {
12527                         Log.i(TAG, "Observer no longer exists.");
12528                     } //end catch
12529                 } //end if
12530             } //end run
12531         });
12532     }
12533
12534     private boolean isPackageDeviceAdmin(String packageName, int userId) {
12535         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12536                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12537         try {
12538             if (dpm != null) {
12539                 if (dpm.isDeviceOwner(packageName)) {
12540                     return true;
12541                 }
12542                 int[] users;
12543                 if (userId == UserHandle.USER_ALL) {
12544                     users = sUserManager.getUserIds();
12545                 } else {
12546                     users = new int[]{userId};
12547                 }
12548                 for (int i = 0; i < users.length; ++i) {
12549                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12550                         return true;
12551                     }
12552                 }
12553             }
12554         } catch (RemoteException e) {
12555         }
12556         return false;
12557     }
12558
12559     /**
12560      *  This method is an internal method that could be get invoked either
12561      *  to delete an installed package or to clean up a failed installation.
12562      *  After deleting an installed package, a broadcast is sent to notify any
12563      *  listeners that the package has been installed. For cleaning up a failed
12564      *  installation, the broadcast is not necessary since the package's
12565      *  installation wouldn't have sent the initial broadcast either
12566      *  The key steps in deleting a package are
12567      *  deleting the package information in internal structures like mPackages,
12568      *  deleting the packages base directories through installd
12569      *  updating mSettings to reflect current status
12570      *  persisting settings for later use
12571      *  sending a broadcast if necessary
12572      */
12573     private int deletePackageX(String packageName, int userId, int flags) {
12574         final PackageRemovedInfo info = new PackageRemovedInfo();
12575         final boolean res;
12576
12577         final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12578                 ? UserHandle.ALL : new UserHandle(userId);
12579
12580         if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12581             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12582             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12583         }
12584
12585         boolean removedForAllUsers = false;
12586         boolean systemUpdate = false;
12587
12588         // for the uninstall-updates case and restricted profiles, remember the per-
12589         // userhandle installed state
12590         int[] allUsers;
12591         boolean[] perUserInstalled;
12592         synchronized (mPackages) {
12593             PackageSetting ps = mSettings.mPackages.get(packageName);
12594             allUsers = sUserManager.getUserIds();
12595             perUserInstalled = new boolean[allUsers.length];
12596             for (int i = 0; i < allUsers.length; i++) {
12597                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12598             }
12599         }
12600
12601         synchronized (mInstallLock) {
12602             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12603             res = deletePackageLI(packageName, removeForUser,
12604                     true, allUsers, perUserInstalled,
12605                     flags | REMOVE_CHATTY, info, true);
12606             systemUpdate = info.isRemovedPackageSystemUpdate;
12607             if (res && !systemUpdate && mPackages.get(packageName) == null) {
12608                 removedForAllUsers = true;
12609             }
12610             if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12611                     + " removedForAllUsers=" + removedForAllUsers);
12612         }
12613
12614         if (res) {
12615             info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12616
12617             // If the removed package was a system update, the old system package
12618             // was re-enabled; we need to broadcast this information
12619             if (systemUpdate) {
12620                 Bundle extras = new Bundle(1);
12621                 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12622                         ? info.removedAppId : info.uid);
12623                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
12624
12625                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12626                         extras, null, null, null);
12627                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12628                         extras, null, null, null);
12629                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12630                         null, packageName, null, null);
12631             }
12632         }
12633         // Force a gc here.
12634         Runtime.getRuntime().gc();
12635         // Delete the resources here after sending the broadcast to let
12636         // other processes clean up before deleting resources.
12637         if (info.args != null) {
12638             synchronized (mInstallLock) {
12639                 info.args.doPostDeleteLI(true);
12640             }
12641         }
12642
12643         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12644     }
12645
12646     class PackageRemovedInfo {
12647         String removedPackage;
12648         int uid = -1;
12649         int removedAppId = -1;
12650         int[] removedUsers = null;
12651         boolean isRemovedPackageSystemUpdate = false;
12652         // Clean up resources deleted packages.
12653         InstallArgs args = null;
12654
12655         void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12656             Bundle extras = new Bundle(1);
12657             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12658             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12659             if (replacing) {
12660                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
12661             }
12662             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12663             if (removedPackage != null) {
12664                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12665                         extras, null, null, removedUsers);
12666                 if (fullRemove && !replacing) {
12667                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12668                             extras, null, null, removedUsers);
12669                 }
12670             }
12671             if (removedAppId >= 0) {
12672                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12673                         removedUsers);
12674             }
12675         }
12676     }
12677
12678     /*
12679      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12680      * flag is not set, the data directory is removed as well.
12681      * make sure this flag is set for partially installed apps. If not its meaningless to
12682      * delete a partially installed application.
12683      */
12684     private void removePackageDataLI(PackageSetting ps,
12685             int[] allUserHandles, boolean[] perUserInstalled,
12686             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12687         String packageName = ps.name;
12688         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12689         removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12690         // Retrieve object to delete permissions for shared user later on
12691         final PackageSetting deletedPs;
12692         // reader
12693         synchronized (mPackages) {
12694             deletedPs = mSettings.mPackages.get(packageName);
12695             if (outInfo != null) {
12696                 outInfo.removedPackage = packageName;
12697                 outInfo.removedUsers = deletedPs != null
12698                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12699                         : null;
12700             }
12701         }
12702         if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12703             removeDataDirsLI(ps.volumeUuid, packageName);
12704             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12705         }
12706         // writer
12707         synchronized (mPackages) {
12708             if (deletedPs != null) {
12709                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12710                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12711                     clearDefaultBrowserIfNeeded(packageName);
12712                     if (outInfo != null) {
12713                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12714                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12715                     }
12716                     updatePermissionsLPw(deletedPs.name, null, 0);
12717                     if (deletedPs.sharedUser != null) {
12718                         // Remove permissions associated with package. Since runtime
12719                         // permissions are per user we have to kill the removed package
12720                         // or packages running under the shared user of the removed
12721                         // package if revoking the permissions requested only by the removed
12722                         // package is successful and this causes a change in gids.
12723                         for (int userId : UserManagerService.getInstance().getUserIds()) {
12724                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12725                                     userId);
12726                             if (userIdToKill == UserHandle.USER_ALL
12727                                     || userIdToKill >= UserHandle.USER_OWNER) {
12728                                 // If gids changed for this user, kill all affected packages.
12729                                 mHandler.post(new Runnable() {
12730                                     @Override
12731                                     public void run() {
12732                                         // This has to happen with no lock held.
12733                                         killSettingPackagesForUser(deletedPs, userIdToKill,
12734                                                 KILL_APP_REASON_GIDS_CHANGED);
12735                                     }
12736                                 });
12737                                 break;
12738                             }
12739                         }
12740                     }
12741                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12742                 }
12743                 // make sure to preserve per-user disabled state if this removal was just
12744                 // a downgrade of a system app to the factory package
12745                 if (allUserHandles != null && perUserInstalled != null) {
12746                     if (DEBUG_REMOVE) {
12747                         Slog.d(TAG, "Propagating install state across downgrade");
12748                     }
12749                     for (int i = 0; i < allUserHandles.length; i++) {
12750                         if (DEBUG_REMOVE) {
12751                             Slog.d(TAG, "    user " + allUserHandles[i]
12752                                     + " => " + perUserInstalled[i]);
12753                         }
12754                         ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12755                     }
12756                 }
12757             }
12758             // can downgrade to reader
12759             if (writeSettings) {
12760                 // Save settings now
12761                 mSettings.writeLPr();
12762             }
12763         }
12764         if (outInfo != null) {
12765             // A user ID was deleted here. Go through all users and remove it
12766             // from KeyStore.
12767             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12768         }
12769     }
12770
12771     static boolean locationIsPrivileged(File path) {
12772         try {
12773             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12774                     .getCanonicalPath();
12775             return path.getCanonicalPath().startsWith(privilegedAppDir);
12776         } catch (IOException e) {
12777             Slog.e(TAG, "Unable to access code path " + path);
12778         }
12779         return false;
12780     }
12781
12782     /*
12783      * Tries to delete system package.
12784      */
12785     private boolean deleteSystemPackageLI(PackageSetting newPs,
12786             int[] allUserHandles, boolean[] perUserInstalled,
12787             int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12788         final boolean applyUserRestrictions
12789                 = (allUserHandles != null) && (perUserInstalled != null);
12790         PackageSetting disabledPs = null;
12791         // Confirm if the system package has been updated
12792         // An updated system app can be deleted. This will also have to restore
12793         // the system pkg from system partition
12794         // reader
12795         synchronized (mPackages) {
12796             disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12797         }
12798         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12799                 + " disabledPs=" + disabledPs);
12800         if (disabledPs == null) {
12801             Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12802             return false;
12803         } else if (DEBUG_REMOVE) {
12804             Slog.d(TAG, "Deleting system pkg from data partition");
12805         }
12806         if (DEBUG_REMOVE) {
12807             if (applyUserRestrictions) {
12808                 Slog.d(TAG, "Remembering install states:");
12809                 for (int i = 0; i < allUserHandles.length; i++) {
12810                     Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12811                 }
12812             }
12813         }
12814         // Delete the updated package
12815         outInfo.isRemovedPackageSystemUpdate = true;
12816         if (disabledPs.versionCode < newPs.versionCode) {
12817             // Delete data for downgrades
12818             flags &= ~PackageManager.DELETE_KEEP_DATA;
12819         } else {
12820             // Preserve data by setting flag
12821             flags |= PackageManager.DELETE_KEEP_DATA;
12822         }
12823         boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12824                 allUserHandles, perUserInstalled, outInfo, writeSettings);
12825         if (!ret) {
12826             return false;
12827         }
12828         // writer
12829         synchronized (mPackages) {
12830             // Reinstate the old system package
12831             mSettings.enableSystemPackageLPw(newPs.name);
12832             // Remove any native libraries from the upgraded package.
12833             NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12834         }
12835         // Install the system package
12836         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12837         int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12838         if (locationIsPrivileged(disabledPs.codePath)) {
12839             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12840         }
12841
12842         final PackageParser.Package newPkg;
12843         try {
12844             newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12845         } catch (PackageManagerException e) {
12846             Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12847             return false;
12848         }
12849
12850         // writer
12851         synchronized (mPackages) {
12852             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12853
12854             // Propagate the permissions state as we do want to drop on the floor
12855             // runtime permissions. The update permissions method below will take
12856             // care of removing obsolete permissions and grant install permissions.
12857             ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12858             updatePermissionsLPw(newPkg.packageName, newPkg,
12859                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12860
12861             if (applyUserRestrictions) {
12862                 if (DEBUG_REMOVE) {
12863                     Slog.d(TAG, "Propagating install state across reinstall");
12864                 }
12865                 for (int i = 0; i < allUserHandles.length; i++) {
12866                     if (DEBUG_REMOVE) {
12867                         Slog.d(TAG, "    user " + allUserHandles[i]
12868                                 + " => " + perUserInstalled[i]);
12869                     }
12870                     ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12871                 }
12872                 // Regardless of writeSettings we need to ensure that this restriction
12873                 // state propagation is persisted
12874                 mSettings.writeAllUsersPackageRestrictionsLPr();
12875             }
12876             // can downgrade to reader here
12877             if (writeSettings) {
12878                 mSettings.writeLPr();
12879             }
12880         }
12881         return true;
12882     }
12883
12884     private boolean deleteInstalledPackageLI(PackageSetting ps,
12885             boolean deleteCodeAndResources, int flags,
12886             int[] allUserHandles, boolean[] perUserInstalled,
12887             PackageRemovedInfo outInfo, boolean writeSettings) {
12888         if (outInfo != null) {
12889             outInfo.uid = ps.appId;
12890         }
12891
12892         // Delete package data from internal structures and also remove data if flag is set
12893         removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12894
12895         // Delete application code and resources
12896         if (deleteCodeAndResources && (outInfo != null)) {
12897             outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12898                     ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12899             if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12900         }
12901         return true;
12902     }
12903
12904     @Override
12905     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12906             int userId) {
12907         mContext.enforceCallingOrSelfPermission(
12908                 android.Manifest.permission.DELETE_PACKAGES, null);
12909         synchronized (mPackages) {
12910             PackageSetting ps = mSettings.mPackages.get(packageName);
12911             if (ps == null) {
12912                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12913                 return false;
12914             }
12915             if (!ps.getInstalled(userId)) {
12916                 // Can't block uninstall for an app that is not installed or enabled.
12917                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12918                 return false;
12919             }
12920             ps.setBlockUninstall(blockUninstall, userId);
12921             mSettings.writePackageRestrictionsLPr(userId);
12922         }
12923         return true;
12924     }
12925
12926     @Override
12927     public boolean getBlockUninstallForUser(String packageName, int userId) {
12928         synchronized (mPackages) {
12929             PackageSetting ps = mSettings.mPackages.get(packageName);
12930             if (ps == null) {
12931                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12932                 return false;
12933             }
12934             return ps.getBlockUninstall(userId);
12935         }
12936     }
12937
12938     /*
12939      * This method handles package deletion in general
12940      */
12941     private boolean deletePackageLI(String packageName, UserHandle user,
12942             boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12943             int flags, PackageRemovedInfo outInfo,
12944             boolean writeSettings) {
12945         if (packageName == null) {
12946             Slog.w(TAG, "Attempt to delete null packageName.");
12947             return false;
12948         }
12949         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12950         PackageSetting ps;
12951         boolean dataOnly = false;
12952         int removeUser = -1;
12953         int appId = -1;
12954         synchronized (mPackages) {
12955             ps = mSettings.mPackages.get(packageName);
12956             if (ps == null) {
12957                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12958                 return false;
12959             }
12960             if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12961                     && user.getIdentifier() != UserHandle.USER_ALL) {
12962                 // The caller is asking that the package only be deleted for a single
12963                 // user.  To do this, we just mark its uninstalled state and delete
12964                 // its data.  If this is a system app, we only allow this to happen if
12965                 // they have set the special DELETE_SYSTEM_APP which requests different
12966                 // semantics than normal for uninstalling system apps.
12967                 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12968                 ps.setUserState(user.getIdentifier(),
12969                         COMPONENT_ENABLED_STATE_DEFAULT,
12970                         false, //installed
12971                         true,  //stopped
12972                         true,  //notLaunched
12973                         false, //hidden
12974                         null, null, null,
12975                         false, // blockUninstall
12976                         INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
12977                 if (!isSystemApp(ps)) {
12978                     if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12979                         // Other user still have this package installed, so all
12980                         // we need to do is clear this user's data and save that
12981                         // it is uninstalled.
12982                         if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12983                         removeUser = user.getIdentifier();
12984                         appId = ps.appId;
12985                         scheduleWritePackageRestrictionsLocked(removeUser);
12986                     } else {
12987                         // We need to set it back to 'installed' so the uninstall
12988                         // broadcasts will be sent correctly.
12989                         if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12990                         ps.setInstalled(true, user.getIdentifier());
12991                     }
12992                 } else {
12993                     // This is a system app, so we assume that the
12994                     // other users still have this package installed, so all
12995                     // we need to do is clear this user's data and save that
12996                     // it is uninstalled.
12997                     if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12998                     removeUser = user.getIdentifier();
12999                     appId = ps.appId;
13000                     scheduleWritePackageRestrictionsLocked(removeUser);
13001                 }
13002             }
13003         }
13004
13005         if (removeUser >= 0) {
13006             // From above, we determined that we are deleting this only
13007             // for a single user.  Continue the work here.
13008             if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13009             if (outInfo != null) {
13010                 outInfo.removedPackage = packageName;
13011                 outInfo.removedAppId = appId;
13012                 outInfo.removedUsers = new int[] {removeUser};
13013             }
13014             mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13015             removeKeystoreDataIfNeeded(removeUser, appId);
13016             schedulePackageCleaning(packageName, removeUser, false);
13017             synchronized (mPackages) {
13018                 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13019                     scheduleWritePackageRestrictionsLocked(removeUser);
13020                 }
13021                 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13022             }
13023             return true;
13024         }
13025
13026         if (dataOnly) {
13027             // Delete application data first
13028             if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13029             removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13030             return true;
13031         }
13032
13033         boolean ret = false;
13034         if (isSystemApp(ps)) {
13035             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13036             // When an updated system application is deleted we delete the existing resources as well and
13037             // fall back to existing code in system partition
13038             ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13039                     flags, outInfo, writeSettings);
13040         } else {
13041             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13042             // Kill application pre-emptively especially for apps on sd.
13043             killApplication(packageName, ps.appId, "uninstall pkg");
13044             ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13045                     allUserHandles, perUserInstalled,
13046                     outInfo, writeSettings);
13047         }
13048
13049         return ret;
13050     }
13051
13052     private final class ClearStorageConnection implements ServiceConnection {
13053         IMediaContainerService mContainerService;
13054
13055         @Override
13056         public void onServiceConnected(ComponentName name, IBinder service) {
13057             synchronized (this) {
13058                 mContainerService = IMediaContainerService.Stub.asInterface(service);
13059                 notifyAll();
13060             }
13061         }
13062
13063         @Override
13064         public void onServiceDisconnected(ComponentName name) {
13065         }
13066     }
13067
13068     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13069         final boolean mounted;
13070         if (Environment.isExternalStorageEmulated()) {
13071             mounted = true;
13072         } else {
13073             final String status = Environment.getExternalStorageState();
13074
13075             mounted = status.equals(Environment.MEDIA_MOUNTED)
13076                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13077         }
13078
13079         if (!mounted) {
13080             return;
13081         }
13082
13083         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13084         int[] users;
13085         if (userId == UserHandle.USER_ALL) {
13086             users = sUserManager.getUserIds();
13087         } else {
13088             users = new int[] { userId };
13089         }
13090         final ClearStorageConnection conn = new ClearStorageConnection();
13091         if (mContext.bindServiceAsUser(
13092                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13093             try {
13094                 for (int curUser : users) {
13095                     long timeout = SystemClock.uptimeMillis() + 5000;
13096                     synchronized (conn) {
13097                         long now = SystemClock.uptimeMillis();
13098                         while (conn.mContainerService == null && now < timeout) {
13099                             try {
13100                                 conn.wait(timeout - now);
13101                             } catch (InterruptedException e) {
13102                             }
13103                         }
13104                     }
13105                     if (conn.mContainerService == null) {
13106                         return;
13107                     }
13108
13109                     final UserEnvironment userEnv = new UserEnvironment(curUser);
13110                     clearDirectory(conn.mContainerService,
13111                             userEnv.buildExternalStorageAppCacheDirs(packageName));
13112                     if (allData) {
13113                         clearDirectory(conn.mContainerService,
13114                                 userEnv.buildExternalStorageAppDataDirs(packageName));
13115                         clearDirectory(conn.mContainerService,
13116                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
13117                     }
13118                 }
13119             } finally {
13120                 mContext.unbindService(conn);
13121             }
13122         }
13123     }
13124
13125     @Override
13126     public void clearApplicationUserData(final String packageName,
13127             final IPackageDataObserver observer, final int userId) {
13128         mContext.enforceCallingOrSelfPermission(
13129                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13130         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13131         // Queue up an async operation since the package deletion may take a little while.
13132         mHandler.post(new Runnable() {
13133             public void run() {
13134                 mHandler.removeCallbacks(this);
13135                 final boolean succeeded;
13136                 synchronized (mInstallLock) {
13137                     succeeded = clearApplicationUserDataLI(packageName, userId);
13138                 }
13139                 clearExternalStorageDataSync(packageName, userId, true);
13140                 if (succeeded) {
13141                     // invoke DeviceStorageMonitor's update method to clear any notifications
13142                     DeviceStorageMonitorInternal
13143                             dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13144                     if (dsm != null) {
13145                         dsm.checkMemory();
13146                     }
13147                 }
13148                 if(observer != null) {
13149                     try {
13150                         observer.onRemoveCompleted(packageName, succeeded);
13151                     } catch (RemoteException e) {
13152                         Log.i(TAG, "Observer no longer exists.");
13153                     }
13154                 } //end if observer
13155             } //end run
13156         });
13157     }
13158
13159     private boolean clearApplicationUserDataLI(String packageName, int userId) {
13160         if (packageName == null) {
13161             Slog.w(TAG, "Attempt to delete null packageName.");
13162             return false;
13163         }
13164
13165         // Try finding details about the requested package
13166         PackageParser.Package pkg;
13167         synchronized (mPackages) {
13168             pkg = mPackages.get(packageName);
13169             if (pkg == null) {
13170                 final PackageSetting ps = mSettings.mPackages.get(packageName);
13171                 if (ps != null) {
13172                     pkg = ps.pkg;
13173                 }
13174             }
13175
13176             if (pkg == null) {
13177                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13178                 return false;
13179             }
13180
13181             PackageSetting ps = (PackageSetting) pkg.mExtras;
13182             resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13183         }
13184
13185         // Always delete data directories for package, even if we found no other
13186         // record of app. This helps users recover from UID mismatches without
13187         // resorting to a full data wipe.
13188         int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13189         if (retCode < 0) {
13190             Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13191             return false;
13192         }
13193
13194         final int appId = pkg.applicationInfo.uid;
13195         removeKeystoreDataIfNeeded(userId, appId);
13196
13197         // Create a native library symlink only if we have native libraries
13198         // and if the native libraries are 32 bit libraries. We do not provide
13199         // this symlink for 64 bit libraries.
13200         if (pkg.applicationInfo.primaryCpuAbi != null &&
13201                 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13202             final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13203             if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13204                     nativeLibPath, userId) < 0) {
13205                 Slog.w(TAG, "Failed linking native library dir");
13206                 return false;
13207             }
13208         }
13209
13210         return true;
13211     }
13212
13213     /**
13214      * Reverts user permission state changes (permissions and flags).
13215      *
13216      * @param ps The package for which to reset.
13217      * @param userId The device user for which to do a reset.
13218      */
13219     private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13220             final PackageSetting ps, final int userId) {
13221         if (ps.pkg == null) {
13222             return;
13223         }
13224
13225         final int userSettableFlags = FLAG_PERMISSION_USER_SET
13226                 | FLAG_PERMISSION_USER_FIXED
13227                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13228
13229         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13230                 | FLAG_PERMISSION_POLICY_FIXED;
13231
13232         boolean writeInstallPermissions = false;
13233         boolean writeRuntimePermissions = false;
13234
13235         final int permissionCount = ps.pkg.requestedPermissions.size();
13236         for (int i = 0; i < permissionCount; i++) {
13237             String permission = ps.pkg.requestedPermissions.get(i);
13238
13239             BasePermission bp = mSettings.mPermissions.get(permission);
13240             if (bp == null) {
13241                 continue;
13242             }
13243
13244             // If shared user we just reset the state to which only this app contributed.
13245             if (ps.sharedUser != null) {
13246                 boolean used = false;
13247                 final int packageCount = ps.sharedUser.packages.size();
13248                 for (int j = 0; j < packageCount; j++) {
13249                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13250                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13251                             && pkg.pkg.requestedPermissions.contains(permission)) {
13252                         used = true;
13253                         break;
13254                     }
13255                 }
13256                 if (used) {
13257                     continue;
13258                 }
13259             }
13260
13261             PermissionsState permissionsState = ps.getPermissionsState();
13262
13263             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13264
13265             // Always clear the user settable flags.
13266             final boolean hasInstallState = permissionsState.getInstallPermissionState(
13267                     bp.name) != null;
13268             if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13269                 if (hasInstallState) {
13270                     writeInstallPermissions = true;
13271                 } else {
13272                     writeRuntimePermissions = true;
13273                 }
13274             }
13275
13276             // Below is only runtime permission handling.
13277             if (!bp.isRuntime()) {
13278                 continue;
13279             }
13280
13281             // Never clobber system or policy.
13282             if ((oldFlags & policyOrSystemFlags) != 0) {
13283                 continue;
13284             }
13285
13286             // If this permission was granted by default, make sure it is.
13287             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13288                 if (permissionsState.grantRuntimePermission(bp, userId)
13289                         != PERMISSION_OPERATION_FAILURE) {
13290                     writeRuntimePermissions = true;
13291                 }
13292             } else {
13293                 // Otherwise, reset the permission.
13294                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13295                 switch (revokeResult) {
13296                     case PERMISSION_OPERATION_SUCCESS: {
13297                         writeRuntimePermissions = true;
13298                     } break;
13299
13300                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13301                         writeRuntimePermissions = true;
13302                         // If gids changed for this user, kill all affected packages.
13303                         mHandler.post(new Runnable() {
13304                             @Override
13305                             public void run() {
13306                                 // This has to happen with no lock held.
13307                                 killSettingPackagesForUser(ps, userId,
13308                                         KILL_APP_REASON_GIDS_CHANGED);
13309                             }
13310                         });
13311                     } break;
13312                 }
13313             }
13314         }
13315
13316         // Synchronously write as we are taking permissions away.
13317         if (writeRuntimePermissions) {
13318             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13319         }
13320
13321         // Synchronously write as we are taking permissions away.
13322         if (writeInstallPermissions) {
13323             mSettings.writeLPr();
13324         }
13325     }
13326
13327     /**
13328      * Remove entries from the keystore daemon. Will only remove it if the
13329      * {@code appId} is valid.
13330      */
13331     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13332         if (appId < 0) {
13333             return;
13334         }
13335
13336         final KeyStore keyStore = KeyStore.getInstance();
13337         if (keyStore != null) {
13338             if (userId == UserHandle.USER_ALL) {
13339                 for (final int individual : sUserManager.getUserIds()) {
13340                     keyStore.clearUid(UserHandle.getUid(individual, appId));
13341                 }
13342             } else {
13343                 keyStore.clearUid(UserHandle.getUid(userId, appId));
13344             }
13345         } else {
13346             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13347         }
13348     }
13349
13350     @Override
13351     public void deleteApplicationCacheFiles(final String packageName,
13352             final IPackageDataObserver observer) {
13353         mContext.enforceCallingOrSelfPermission(
13354                 android.Manifest.permission.DELETE_CACHE_FILES, null);
13355         // Queue up an async operation since the package deletion may take a little while.
13356         final int userId = UserHandle.getCallingUserId();
13357         mHandler.post(new Runnable() {
13358             public void run() {
13359                 mHandler.removeCallbacks(this);
13360                 final boolean succeded;
13361                 synchronized (mInstallLock) {
13362                     succeded = deleteApplicationCacheFilesLI(packageName, userId);
13363                 }
13364                 clearExternalStorageDataSync(packageName, userId, false);
13365                 if (observer != null) {
13366                     try {
13367                         observer.onRemoveCompleted(packageName, succeded);
13368                     } catch (RemoteException e) {
13369                         Log.i(TAG, "Observer no longer exists.");
13370                     }
13371                 } //end if observer
13372             } //end run
13373         });
13374     }
13375
13376     private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13377         if (packageName == null) {
13378             Slog.w(TAG, "Attempt to delete null packageName.");
13379             return false;
13380         }
13381         PackageParser.Package p;
13382         synchronized (mPackages) {
13383             p = mPackages.get(packageName);
13384         }
13385         if (p == null) {
13386             Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13387             return false;
13388         }
13389         final ApplicationInfo applicationInfo = p.applicationInfo;
13390         if (applicationInfo == null) {
13391             Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13392             return false;
13393         }
13394         int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13395         if (retCode < 0) {
13396             Slog.w(TAG, "Couldn't remove cache files for package: "
13397                        + packageName + " u" + userId);
13398             return false;
13399         }
13400         return true;
13401     }
13402
13403     @Override
13404     public void getPackageSizeInfo(final String packageName, int userHandle,
13405             final IPackageStatsObserver observer) {
13406         mContext.enforceCallingOrSelfPermission(
13407                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
13408         if (packageName == null) {
13409             throw new IllegalArgumentException("Attempt to get size of null packageName");
13410         }
13411
13412         PackageStats stats = new PackageStats(packageName, userHandle);
13413
13414         /*
13415          * Queue up an async operation since the package measurement may take a
13416          * little while.
13417          */
13418         Message msg = mHandler.obtainMessage(INIT_COPY);
13419         msg.obj = new MeasureParams(stats, observer);
13420         mHandler.sendMessage(msg);
13421     }
13422
13423     private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13424             PackageStats pStats) {
13425         if (packageName == null) {
13426             Slog.w(TAG, "Attempt to get size of null packageName.");
13427             return false;
13428         }
13429         PackageParser.Package p;
13430         boolean dataOnly = false;
13431         String libDirRoot = null;
13432         String asecPath = null;
13433         PackageSetting ps = null;
13434         synchronized (mPackages) {
13435             p = mPackages.get(packageName);
13436             ps = mSettings.mPackages.get(packageName);
13437             if(p == null) {
13438                 dataOnly = true;
13439                 if((ps == null) || (ps.pkg == null)) {
13440                     Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13441                     return false;
13442                 }
13443                 p = ps.pkg;
13444             }
13445             if (ps != null) {
13446                 libDirRoot = ps.legacyNativeLibraryPathString;
13447             }
13448             if (p != null && (isExternal(p) || p.isForwardLocked())) {
13449                 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13450                 if (secureContainerId != null) {
13451                     asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13452                 }
13453             }
13454         }
13455         String publicSrcDir = null;
13456         if(!dataOnly) {
13457             final ApplicationInfo applicationInfo = p.applicationInfo;
13458             if (applicationInfo == null) {
13459                 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13460                 return false;
13461             }
13462             if (p.isForwardLocked()) {
13463                 publicSrcDir = applicationInfo.getBaseResourcePath();
13464             }
13465         }
13466         // TODO: extend to measure size of split APKs
13467         // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13468         // not just the first level.
13469         // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13470         // just the primary.
13471         String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13472         int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13473                 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13474         if (res < 0) {
13475             return false;
13476         }
13477
13478         // Fix-up for forward-locked applications in ASEC containers.
13479         if (!isExternal(p)) {
13480             pStats.codeSize += pStats.externalCodeSize;
13481             pStats.externalCodeSize = 0L;
13482         }
13483
13484         return true;
13485     }
13486
13487
13488     @Override
13489     public void addPackageToPreferred(String packageName) {
13490         Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13491     }
13492
13493     @Override
13494     public void removePackageFromPreferred(String packageName) {
13495         Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13496     }
13497
13498     @Override
13499     public List<PackageInfo> getPreferredPackages(int flags) {
13500         return new ArrayList<PackageInfo>();
13501     }
13502
13503     private int getUidTargetSdkVersionLockedLPr(int uid) {
13504         Object obj = mSettings.getUserIdLPr(uid);
13505         if (obj instanceof SharedUserSetting) {
13506             final SharedUserSetting sus = (SharedUserSetting) obj;
13507             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13508             final Iterator<PackageSetting> it = sus.packages.iterator();
13509             while (it.hasNext()) {
13510                 final PackageSetting ps = it.next();
13511                 if (ps.pkg != null) {
13512                     int v = ps.pkg.applicationInfo.targetSdkVersion;
13513                     if (v < vers) vers = v;
13514                 }
13515             }
13516             return vers;
13517         } else if (obj instanceof PackageSetting) {
13518             final PackageSetting ps = (PackageSetting) obj;
13519             if (ps.pkg != null) {
13520                 return ps.pkg.applicationInfo.targetSdkVersion;
13521             }
13522         }
13523         return Build.VERSION_CODES.CUR_DEVELOPMENT;
13524     }
13525
13526     @Override
13527     public void addPreferredActivity(IntentFilter filter, int match,
13528             ComponentName[] set, ComponentName activity, int userId) {
13529         addPreferredActivityInternal(filter, match, set, activity, true, userId,
13530                 "Adding preferred");
13531     }
13532
13533     private void addPreferredActivityInternal(IntentFilter filter, int match,
13534             ComponentName[] set, ComponentName activity, boolean always, int userId,
13535             String opname) {
13536         // writer
13537         int callingUid = Binder.getCallingUid();
13538         enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13539         if (filter.countActions() == 0) {
13540             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13541             return;
13542         }
13543         synchronized (mPackages) {
13544             if (mContext.checkCallingOrSelfPermission(
13545                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13546                     != PackageManager.PERMISSION_GRANTED) {
13547                 if (getUidTargetSdkVersionLockedLPr(callingUid)
13548                         < Build.VERSION_CODES.FROYO) {
13549                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13550                             + callingUid);
13551                     return;
13552                 }
13553                 mContext.enforceCallingOrSelfPermission(
13554                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13555             }
13556
13557             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13558             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13559                     + userId + ":");
13560             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13561             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13562             scheduleWritePackageRestrictionsLocked(userId);
13563         }
13564     }
13565
13566     @Override
13567     public void replacePreferredActivity(IntentFilter filter, int match,
13568             ComponentName[] set, ComponentName activity, int userId) {
13569         if (filter.countActions() != 1) {
13570             throw new IllegalArgumentException(
13571                     "replacePreferredActivity expects filter to have only 1 action.");
13572         }
13573         if (filter.countDataAuthorities() != 0
13574                 || filter.countDataPaths() != 0
13575                 || filter.countDataSchemes() > 1
13576                 || filter.countDataTypes() != 0) {
13577             throw new IllegalArgumentException(
13578                     "replacePreferredActivity expects filter to have no data authorities, " +
13579                     "paths, or types; and at most one scheme.");
13580         }
13581
13582         final int callingUid = Binder.getCallingUid();
13583         enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13584         synchronized (mPackages) {
13585             if (mContext.checkCallingOrSelfPermission(
13586                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13587                     != PackageManager.PERMISSION_GRANTED) {
13588                 if (getUidTargetSdkVersionLockedLPr(callingUid)
13589                         < Build.VERSION_CODES.FROYO) {
13590                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13591                             + Binder.getCallingUid());
13592                     return;
13593                 }
13594                 mContext.enforceCallingOrSelfPermission(
13595                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13596             }
13597
13598             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13599             if (pir != null) {
13600                 // Get all of the existing entries that exactly match this filter.
13601                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13602                 if (existing != null && existing.size() == 1) {
13603                     PreferredActivity cur = existing.get(0);
13604                     if (DEBUG_PREFERRED) {
13605                         Slog.i(TAG, "Checking replace of preferred:");
13606                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13607                         if (!cur.mPref.mAlways) {
13608                             Slog.i(TAG, "  -- CUR; not mAlways!");
13609                         } else {
13610                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13611                             Slog.i(TAG, "  -- CUR: mSet="
13612                                     + Arrays.toString(cur.mPref.mSetComponents));
13613                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13614                             Slog.i(TAG, "  -- NEW: mMatch="
13615                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
13616                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13617                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13618                         }
13619                     }
13620                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13621                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13622                             && cur.mPref.sameSet(set)) {
13623                         // Setting the preferred activity to what it happens to be already
13624                         if (DEBUG_PREFERRED) {
13625                             Slog.i(TAG, "Replacing with same preferred activity "
13626                                     + cur.mPref.mShortComponent + " for user "
13627                                     + userId + ":");
13628                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13629                         }
13630                         return;
13631                     }
13632                 }
13633
13634                 if (existing != null) {
13635                     if (DEBUG_PREFERRED) {
13636                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
13637                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13638                     }
13639                     for (int i = 0; i < existing.size(); i++) {
13640                         PreferredActivity pa = existing.get(i);
13641                         if (DEBUG_PREFERRED) {
13642                             Slog.i(TAG, "Removing existing preferred activity "
13643                                     + pa.mPref.mComponent + ":");
13644                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13645                         }
13646                         pir.removeFilter(pa);
13647                     }
13648                 }
13649             }
13650             addPreferredActivityInternal(filter, match, set, activity, true, userId,
13651                     "Replacing preferred");
13652         }
13653     }
13654
13655     @Override
13656     public void clearPackagePreferredActivities(String packageName) {
13657         final int uid = Binder.getCallingUid();
13658         // writer
13659         synchronized (mPackages) {
13660             PackageParser.Package pkg = mPackages.get(packageName);
13661             if (pkg == null || pkg.applicationInfo.uid != uid) {
13662                 if (mContext.checkCallingOrSelfPermission(
13663                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13664                         != PackageManager.PERMISSION_GRANTED) {
13665                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13666                             < Build.VERSION_CODES.FROYO) {
13667                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13668                                 + Binder.getCallingUid());
13669                         return;
13670                     }
13671                     mContext.enforceCallingOrSelfPermission(
13672                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13673                 }
13674             }
13675
13676             int user = UserHandle.getCallingUserId();
13677             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13678                 scheduleWritePackageRestrictionsLocked(user);
13679             }
13680         }
13681     }
13682
13683     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13684     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13685         ArrayList<PreferredActivity> removed = null;
13686         boolean changed = false;
13687         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13688             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13689             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13690             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13691                 continue;
13692             }
13693             Iterator<PreferredActivity> it = pir.filterIterator();
13694             while (it.hasNext()) {
13695                 PreferredActivity pa = it.next();
13696                 // Mark entry for removal only if it matches the package name
13697                 // and the entry is of type "always".
13698                 if (packageName == null ||
13699                         (pa.mPref.mComponent.getPackageName().equals(packageName)
13700                                 && pa.mPref.mAlways)) {
13701                     if (removed == null) {
13702                         removed = new ArrayList<PreferredActivity>();
13703                     }
13704                     removed.add(pa);
13705                 }
13706             }
13707             if (removed != null) {
13708                 for (int j=0; j<removed.size(); j++) {
13709                     PreferredActivity pa = removed.get(j);
13710                     pir.removeFilter(pa);
13711                 }
13712                 changed = true;
13713             }
13714         }
13715         return changed;
13716     }
13717
13718     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13719     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13720         if (userId == UserHandle.USER_ALL) {
13721             if (mSettings.removeIntentFilterVerificationLPw(packageName,
13722                     sUserManager.getUserIds())) {
13723                 for (int oneUserId : sUserManager.getUserIds()) {
13724                     scheduleWritePackageRestrictionsLocked(oneUserId);
13725                 }
13726             }
13727         } else {
13728             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13729                 scheduleWritePackageRestrictionsLocked(userId);
13730             }
13731         }
13732     }
13733
13734
13735     void clearDefaultBrowserIfNeeded(String packageName) {
13736         for (int oneUserId : sUserManager.getUserIds()) {
13737             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13738             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13739             if (packageName.equals(defaultBrowserPackageName)) {
13740                 setDefaultBrowserPackageName(null, oneUserId);
13741             }
13742         }
13743     }
13744
13745     @Override
13746     public void resetPreferredActivities(int userId) {
13747         mContext.enforceCallingOrSelfPermission(
13748                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13749         // writer
13750         synchronized (mPackages) {
13751             clearPackagePreferredActivitiesLPw(null, userId);
13752             mSettings.applyDefaultPreferredAppsLPw(this, userId);
13753             applyFactoryDefaultBrowserLPw(userId);
13754             primeDomainVerificationsLPw(userId);
13755
13756             scheduleWritePackageRestrictionsLocked(userId);
13757         }
13758     }
13759
13760     @Override
13761     public int getPreferredActivities(List<IntentFilter> outFilters,
13762             List<ComponentName> outActivities, String packageName) {
13763
13764         int num = 0;
13765         final int userId = UserHandle.getCallingUserId();
13766         // reader
13767         synchronized (mPackages) {
13768             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13769             if (pir != null) {
13770                 final Iterator<PreferredActivity> it = pir.filterIterator();
13771                 while (it.hasNext()) {
13772                     final PreferredActivity pa = it.next();
13773                     if (packageName == null
13774                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
13775                                     && pa.mPref.mAlways)) {
13776                         if (outFilters != null) {
13777                             outFilters.add(new IntentFilter(pa));
13778                         }
13779                         if (outActivities != null) {
13780                             outActivities.add(pa.mPref.mComponent);
13781                         }
13782                     }
13783                 }
13784             }
13785         }
13786
13787         return num;
13788     }
13789
13790     @Override
13791     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13792             int userId) {
13793         int callingUid = Binder.getCallingUid();
13794         if (callingUid != Process.SYSTEM_UID) {
13795             throw new SecurityException(
13796                     "addPersistentPreferredActivity can only be run by the system");
13797         }
13798         if (filter.countActions() == 0) {
13799             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13800             return;
13801         }
13802         synchronized (mPackages) {
13803             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13804                     " :");
13805             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13806             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13807                     new PersistentPreferredActivity(filter, activity));
13808             scheduleWritePackageRestrictionsLocked(userId);
13809         }
13810     }
13811
13812     @Override
13813     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13814         int callingUid = Binder.getCallingUid();
13815         if (callingUid != Process.SYSTEM_UID) {
13816             throw new SecurityException(
13817                     "clearPackagePersistentPreferredActivities can only be run by the system");
13818         }
13819         ArrayList<PersistentPreferredActivity> removed = null;
13820         boolean changed = false;
13821         synchronized (mPackages) {
13822             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13823                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13824                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13825                         .valueAt(i);
13826                 if (userId != thisUserId) {
13827                     continue;
13828                 }
13829                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13830                 while (it.hasNext()) {
13831                     PersistentPreferredActivity ppa = it.next();
13832                     // Mark entry for removal only if it matches the package name.
13833                     if (ppa.mComponent.getPackageName().equals(packageName)) {
13834                         if (removed == null) {
13835                             removed = new ArrayList<PersistentPreferredActivity>();
13836                         }
13837                         removed.add(ppa);
13838                     }
13839                 }
13840                 if (removed != null) {
13841                     for (int j=0; j<removed.size(); j++) {
13842                         PersistentPreferredActivity ppa = removed.get(j);
13843                         ppir.removeFilter(ppa);
13844                     }
13845                     changed = true;
13846                 }
13847             }
13848
13849             if (changed) {
13850                 scheduleWritePackageRestrictionsLocked(userId);
13851             }
13852         }
13853     }
13854
13855     /**
13856      * Common machinery for picking apart a restored XML blob and passing
13857      * it to a caller-supplied functor to be applied to the running system.
13858      */
13859     private void restoreFromXml(XmlPullParser parser, int userId,
13860             String expectedStartTag, BlobXmlRestorer functor)
13861             throws IOException, XmlPullParserException {
13862         int type;
13863         while ((type = parser.next()) != XmlPullParser.START_TAG
13864                 && type != XmlPullParser.END_DOCUMENT) {
13865         }
13866         if (type != XmlPullParser.START_TAG) {
13867             // oops didn't find a start tag?!
13868             if (DEBUG_BACKUP) {
13869                 Slog.e(TAG, "Didn't find start tag during restore");
13870             }
13871             return;
13872         }
13873
13874         // this is supposed to be TAG_PREFERRED_BACKUP
13875         if (!expectedStartTag.equals(parser.getName())) {
13876             if (DEBUG_BACKUP) {
13877                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
13878             }
13879             return;
13880         }
13881
13882         // skip interfering stuff, then we're aligned with the backing implementation
13883         while ((type = parser.next()) == XmlPullParser.TEXT) { }
13884         functor.apply(parser, userId);
13885     }
13886
13887     private interface BlobXmlRestorer {
13888         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13889     }
13890
13891     /**
13892      * Non-Binder method, support for the backup/restore mechanism: write the
13893      * full set of preferred activities in its canonical XML format.  Returns the
13894      * XML output as a byte array, or null if there is none.
13895      */
13896     @Override
13897     public byte[] getPreferredActivityBackup(int userId) {
13898         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13899             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13900         }
13901
13902         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13903         try {
13904             final XmlSerializer serializer = new FastXmlSerializer();
13905             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13906             serializer.startDocument(null, true);
13907             serializer.startTag(null, TAG_PREFERRED_BACKUP);
13908
13909             synchronized (mPackages) {
13910                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13911             }
13912
13913             serializer.endTag(null, TAG_PREFERRED_BACKUP);
13914             serializer.endDocument();
13915             serializer.flush();
13916         } catch (Exception e) {
13917             if (DEBUG_BACKUP) {
13918                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
13919             }
13920             return null;
13921         }
13922
13923         return dataStream.toByteArray();
13924     }
13925
13926     @Override
13927     public void restorePreferredActivities(byte[] backup, int userId) {
13928         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13929             throw new SecurityException("Only the system may call restorePreferredActivities()");
13930         }
13931
13932         try {
13933             final XmlPullParser parser = Xml.newPullParser();
13934             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13935             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13936                     new BlobXmlRestorer() {
13937                         @Override
13938                         public void apply(XmlPullParser parser, int userId)
13939                                 throws XmlPullParserException, IOException {
13940                             synchronized (mPackages) {
13941                                 mSettings.readPreferredActivitiesLPw(parser, userId);
13942                             }
13943                         }
13944                     } );
13945         } catch (Exception e) {
13946             if (DEBUG_BACKUP) {
13947                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13948             }
13949         }
13950     }
13951
13952     /**
13953      * Non-Binder method, support for the backup/restore mechanism: write the
13954      * default browser (etc) settings in its canonical XML format.  Returns the default
13955      * browser XML representation as a byte array, or null if there is none.
13956      */
13957     @Override
13958     public byte[] getDefaultAppsBackup(int userId) {
13959         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13960             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13961         }
13962
13963         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13964         try {
13965             final XmlSerializer serializer = new FastXmlSerializer();
13966             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13967             serializer.startDocument(null, true);
13968             serializer.startTag(null, TAG_DEFAULT_APPS);
13969
13970             synchronized (mPackages) {
13971                 mSettings.writeDefaultAppsLPr(serializer, userId);
13972             }
13973
13974             serializer.endTag(null, TAG_DEFAULT_APPS);
13975             serializer.endDocument();
13976             serializer.flush();
13977         } catch (Exception e) {
13978             if (DEBUG_BACKUP) {
13979                 Slog.e(TAG, "Unable to write default apps for backup", e);
13980             }
13981             return null;
13982         }
13983
13984         return dataStream.toByteArray();
13985     }
13986
13987     @Override
13988     public void restoreDefaultApps(byte[] backup, int userId) {
13989         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13990             throw new SecurityException("Only the system may call restoreDefaultApps()");
13991         }
13992
13993         try {
13994             final XmlPullParser parser = Xml.newPullParser();
13995             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13996             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13997                     new BlobXmlRestorer() {
13998                         @Override
13999                         public void apply(XmlPullParser parser, int userId)
14000                                 throws XmlPullParserException, IOException {
14001                             synchronized (mPackages) {
14002                                 mSettings.readDefaultAppsLPw(parser, userId);
14003                             }
14004                         }
14005                     } );
14006         } catch (Exception e) {
14007             if (DEBUG_BACKUP) {
14008                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14009             }
14010         }
14011     }
14012
14013     @Override
14014     public byte[] getIntentFilterVerificationBackup(int userId) {
14015         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14016             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14017         }
14018
14019         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14020         try {
14021             final XmlSerializer serializer = new FastXmlSerializer();
14022             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14023             serializer.startDocument(null, true);
14024             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14025
14026             synchronized (mPackages) {
14027                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14028             }
14029
14030             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14031             serializer.endDocument();
14032             serializer.flush();
14033         } catch (Exception e) {
14034             if (DEBUG_BACKUP) {
14035                 Slog.e(TAG, "Unable to write default apps for backup", e);
14036             }
14037             return null;
14038         }
14039
14040         return dataStream.toByteArray();
14041     }
14042
14043     @Override
14044     public void restoreIntentFilterVerification(byte[] backup, int userId) {
14045         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14046             throw new SecurityException("Only the system may call restorePreferredActivities()");
14047         }
14048
14049         try {
14050             final XmlPullParser parser = Xml.newPullParser();
14051             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14052             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14053                     new BlobXmlRestorer() {
14054                         @Override
14055                         public void apply(XmlPullParser parser, int userId)
14056                                 throws XmlPullParserException, IOException {
14057                             synchronized (mPackages) {
14058                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
14059                                 mSettings.writeLPr();
14060                             }
14061                         }
14062                     } );
14063         } catch (Exception e) {
14064             if (DEBUG_BACKUP) {
14065                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14066             }
14067         }
14068     }
14069
14070     @Override
14071     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14072             int sourceUserId, int targetUserId, int flags) {
14073         mContext.enforceCallingOrSelfPermission(
14074                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14075         int callingUid = Binder.getCallingUid();
14076         enforceOwnerRights(ownerPackage, callingUid);
14077         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14078         if (intentFilter.countActions() == 0) {
14079             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14080             return;
14081         }
14082         synchronized (mPackages) {
14083             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14084                     ownerPackage, targetUserId, flags);
14085             CrossProfileIntentResolver resolver =
14086                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14087             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14088             // We have all those whose filter is equal. Now checking if the rest is equal as well.
14089             if (existing != null) {
14090                 int size = existing.size();
14091                 for (int i = 0; i < size; i++) {
14092                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14093                         return;
14094                     }
14095                 }
14096             }
14097             resolver.addFilter(newFilter);
14098             scheduleWritePackageRestrictionsLocked(sourceUserId);
14099         }
14100     }
14101
14102     @Override
14103     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14104         mContext.enforceCallingOrSelfPermission(
14105                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14106         int callingUid = Binder.getCallingUid();
14107         enforceOwnerRights(ownerPackage, callingUid);
14108         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14109         synchronized (mPackages) {
14110             CrossProfileIntentResolver resolver =
14111                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14112             ArraySet<CrossProfileIntentFilter> set =
14113                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14114             for (CrossProfileIntentFilter filter : set) {
14115                 if (filter.getOwnerPackage().equals(ownerPackage)) {
14116                     resolver.removeFilter(filter);
14117                 }
14118             }
14119             scheduleWritePackageRestrictionsLocked(sourceUserId);
14120         }
14121     }
14122
14123     // Enforcing that callingUid is owning pkg on userId
14124     private void enforceOwnerRights(String pkg, int callingUid) {
14125         // The system owns everything.
14126         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14127             return;
14128         }
14129         int callingUserId = UserHandle.getUserId(callingUid);
14130         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14131         if (pi == null) {
14132             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14133                     + callingUserId);
14134         }
14135         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14136             throw new SecurityException("Calling uid " + callingUid
14137                     + " does not own package " + pkg);
14138         }
14139     }
14140
14141     @Override
14142     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14143         Intent intent = new Intent(Intent.ACTION_MAIN);
14144         intent.addCategory(Intent.CATEGORY_HOME);
14145
14146         final int callingUserId = UserHandle.getCallingUserId();
14147         List<ResolveInfo> list = queryIntentActivities(intent, null,
14148                 PackageManager.GET_META_DATA, callingUserId);
14149         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14150                 true, false, false, callingUserId);
14151
14152         allHomeCandidates.clear();
14153         if (list != null) {
14154             for (ResolveInfo ri : list) {
14155                 allHomeCandidates.add(ri);
14156             }
14157         }
14158         return (preferred == null || preferred.activityInfo == null)
14159                 ? null
14160                 : new ComponentName(preferred.activityInfo.packageName,
14161                         preferred.activityInfo.name);
14162     }
14163
14164     @Override
14165     public void setApplicationEnabledSetting(String appPackageName,
14166             int newState, int flags, int userId, String callingPackage) {
14167         if (!sUserManager.exists(userId)) return;
14168         if (callingPackage == null) {
14169             callingPackage = Integer.toString(Binder.getCallingUid());
14170         }
14171         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14172     }
14173
14174     @Override
14175     public void setComponentEnabledSetting(ComponentName componentName,
14176             int newState, int flags, int userId) {
14177         if (!sUserManager.exists(userId)) return;
14178         setEnabledSetting(componentName.getPackageName(),
14179                 componentName.getClassName(), newState, flags, userId, null);
14180     }
14181
14182     private void setEnabledSetting(final String packageName, String className, int newState,
14183             final int flags, int userId, String callingPackage) {
14184         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14185               || newState == COMPONENT_ENABLED_STATE_ENABLED
14186               || newState == COMPONENT_ENABLED_STATE_DISABLED
14187               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14188               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14189             throw new IllegalArgumentException("Invalid new component state: "
14190                     + newState);
14191         }
14192         PackageSetting pkgSetting;
14193         final int uid = Binder.getCallingUid();
14194         final int permission = mContext.checkCallingOrSelfPermission(
14195                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14196         enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14197         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14198         boolean sendNow = false;
14199         boolean isApp = (className == null);
14200         String componentName = isApp ? packageName : className;
14201         int packageUid = -1;
14202         ArrayList<String> components;
14203
14204         // writer
14205         synchronized (mPackages) {
14206             pkgSetting = mSettings.mPackages.get(packageName);
14207             if (pkgSetting == null) {
14208                 if (className == null) {
14209                     throw new IllegalArgumentException(
14210                             "Unknown package: " + packageName);
14211                 }
14212                 throw new IllegalArgumentException(
14213                         "Unknown component: " + packageName
14214                         + "/" + className);
14215             }
14216             // Allow root and verify that userId is not being specified by a different user
14217             if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14218                 throw new SecurityException(
14219                         "Permission Denial: attempt to change component state from pid="
14220                         + Binder.getCallingPid()
14221                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14222             }
14223             if (className == null) {
14224                 // We're dealing with an application/package level state change
14225                 if (pkgSetting.getEnabled(userId) == newState) {
14226                     // Nothing to do
14227                     return;
14228                 }
14229                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14230                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14231                     // Don't care about who enables an app.
14232                     callingPackage = null;
14233                 }
14234                 pkgSetting.setEnabled(newState, userId, callingPackage);
14235                 // pkgSetting.pkg.mSetEnabled = newState;
14236             } else {
14237                 // We're dealing with a component level state change
14238                 // First, verify that this is a valid class name.
14239                 PackageParser.Package pkg = pkgSetting.pkg;
14240                 if (pkg == null || !pkg.hasComponentClassName(className)) {
14241                     if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14242                         throw new IllegalArgumentException("Component class " + className
14243                                 + " does not exist in " + packageName);
14244                     } else {
14245                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14246                                 + className + " does not exist in " + packageName);
14247                     }
14248                 }
14249                 switch (newState) {
14250                 case COMPONENT_ENABLED_STATE_ENABLED:
14251                     if (!pkgSetting.enableComponentLPw(className, userId)) {
14252                         return;
14253                     }
14254                     break;
14255                 case COMPONENT_ENABLED_STATE_DISABLED:
14256                     if (!pkgSetting.disableComponentLPw(className, userId)) {
14257                         return;
14258                     }
14259                     break;
14260                 case COMPONENT_ENABLED_STATE_DEFAULT:
14261                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
14262                         return;
14263                     }
14264                     break;
14265                 default:
14266                     Slog.e(TAG, "Invalid new component state: " + newState);
14267                     return;
14268                 }
14269             }
14270             scheduleWritePackageRestrictionsLocked(userId);
14271             components = mPendingBroadcasts.get(userId, packageName);
14272             final boolean newPackage = components == null;
14273             if (newPackage) {
14274                 components = new ArrayList<String>();
14275             }
14276             if (!components.contains(componentName)) {
14277                 components.add(componentName);
14278             }
14279             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14280                 sendNow = true;
14281                 // Purge entry from pending broadcast list if another one exists already
14282                 // since we are sending one right away.
14283                 mPendingBroadcasts.remove(userId, packageName);
14284             } else {
14285                 if (newPackage) {
14286                     mPendingBroadcasts.put(userId, packageName, components);
14287                 }
14288                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14289                     // Schedule a message
14290                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14291                 }
14292             }
14293         }
14294
14295         long callingId = Binder.clearCallingIdentity();
14296         try {
14297             if (sendNow) {
14298                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14299                 sendPackageChangedBroadcast(packageName,
14300                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14301             }
14302         } finally {
14303             Binder.restoreCallingIdentity(callingId);
14304         }
14305     }
14306
14307     private void sendPackageChangedBroadcast(String packageName,
14308             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14309         if (DEBUG_INSTALL)
14310             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14311                     + componentNames);
14312         Bundle extras = new Bundle(4);
14313         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14314         String nameList[] = new String[componentNames.size()];
14315         componentNames.toArray(nameList);
14316         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14317         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14318         extras.putInt(Intent.EXTRA_UID, packageUid);
14319         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14320                 new int[] {UserHandle.getUserId(packageUid)});
14321     }
14322
14323     @Override
14324     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14325         if (!sUserManager.exists(userId)) return;
14326         final int uid = Binder.getCallingUid();
14327         final int permission = mContext.checkCallingOrSelfPermission(
14328                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14329         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14330         enforceCrossUserPermission(uid, userId, true, true, "stop package");
14331         // writer
14332         synchronized (mPackages) {
14333             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14334                     allowedByPermission, uid, userId)) {
14335                 scheduleWritePackageRestrictionsLocked(userId);
14336             }
14337         }
14338     }
14339
14340     @Override
14341     public String getInstallerPackageName(String packageName) {
14342         // reader
14343         synchronized (mPackages) {
14344             return mSettings.getInstallerPackageNameLPr(packageName);
14345         }
14346     }
14347
14348     @Override
14349     public int getApplicationEnabledSetting(String packageName, int userId) {
14350         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14351         int uid = Binder.getCallingUid();
14352         enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14353         // reader
14354         synchronized (mPackages) {
14355             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14356         }
14357     }
14358
14359     @Override
14360     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14361         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14362         int uid = Binder.getCallingUid();
14363         enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14364         // reader
14365         synchronized (mPackages) {
14366             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14367         }
14368     }
14369
14370     @Override
14371     public void enterSafeMode() {
14372         enforceSystemOrRoot("Only the system can request entering safe mode");
14373
14374         if (!mSystemReady) {
14375             mSafeMode = true;
14376         }
14377     }
14378
14379     @Override
14380     public void systemReady() {
14381         mSystemReady = true;
14382
14383         // Read the compatibilty setting when the system is ready.
14384         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14385                 mContext.getContentResolver(),
14386                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14387         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14388         if (DEBUG_SETTINGS) {
14389             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14390         }
14391
14392         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14393
14394         synchronized (mPackages) {
14395             // Verify that all of the preferred activity components actually
14396             // exist.  It is possible for applications to be updated and at
14397             // that point remove a previously declared activity component that
14398             // had been set as a preferred activity.  We try to clean this up
14399             // the next time we encounter that preferred activity, but it is
14400             // possible for the user flow to never be able to return to that
14401             // situation so here we do a sanity check to make sure we haven't
14402             // left any junk around.
14403             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14404             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14405                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14406                 removed.clear();
14407                 for (PreferredActivity pa : pir.filterSet()) {
14408                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14409                         removed.add(pa);
14410                     }
14411                 }
14412                 if (removed.size() > 0) {
14413                     for (int r=0; r<removed.size(); r++) {
14414                         PreferredActivity pa = removed.get(r);
14415                         Slog.w(TAG, "Removing dangling preferred activity: "
14416                                 + pa.mPref.mComponent);
14417                         pir.removeFilter(pa);
14418                     }
14419                     mSettings.writePackageRestrictionsLPr(
14420                             mSettings.mPreferredActivities.keyAt(i));
14421                 }
14422             }
14423
14424             for (int userId : UserManagerService.getInstance().getUserIds()) {
14425                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14426                     grantPermissionsUserIds = ArrayUtils.appendInt(
14427                             grantPermissionsUserIds, userId);
14428                 }
14429             }
14430         }
14431         sUserManager.systemReady();
14432
14433         // If we upgraded grant all default permissions before kicking off.
14434         for (int userId : grantPermissionsUserIds) {
14435             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14436         }
14437
14438         // Kick off any messages waiting for system ready
14439         if (mPostSystemReadyMessages != null) {
14440             for (Message msg : mPostSystemReadyMessages) {
14441                 msg.sendToTarget();
14442             }
14443             mPostSystemReadyMessages = null;
14444         }
14445
14446         // Watch for external volumes that come and go over time
14447         final StorageManager storage = mContext.getSystemService(StorageManager.class);
14448         storage.registerListener(mStorageListener);
14449
14450         mInstallerService.systemReady();
14451         mPackageDexOptimizer.systemReady();
14452     }
14453
14454     @Override
14455     public boolean isSafeMode() {
14456         return mSafeMode;
14457     }
14458
14459     @Override
14460     public boolean hasSystemUidErrors() {
14461         return mHasSystemUidErrors;
14462     }
14463
14464     static String arrayToString(int[] array) {
14465         StringBuffer buf = new StringBuffer(128);
14466         buf.append('[');
14467         if (array != null) {
14468             for (int i=0; i<array.length; i++) {
14469                 if (i > 0) buf.append(", ");
14470                 buf.append(array[i]);
14471             }
14472         }
14473         buf.append(']');
14474         return buf.toString();
14475     }
14476
14477     static class DumpState {
14478         public static final int DUMP_LIBS = 1 << 0;
14479         public static final int DUMP_FEATURES = 1 << 1;
14480         public static final int DUMP_RESOLVERS = 1 << 2;
14481         public static final int DUMP_PERMISSIONS = 1 << 3;
14482         public static final int DUMP_PACKAGES = 1 << 4;
14483         public static final int DUMP_SHARED_USERS = 1 << 5;
14484         public static final int DUMP_MESSAGES = 1 << 6;
14485         public static final int DUMP_PROVIDERS = 1 << 7;
14486         public static final int DUMP_VERIFIERS = 1 << 8;
14487         public static final int DUMP_PREFERRED = 1 << 9;
14488         public static final int DUMP_PREFERRED_XML = 1 << 10;
14489         public static final int DUMP_KEYSETS = 1 << 11;
14490         public static final int DUMP_VERSION = 1 << 12;
14491         public static final int DUMP_INSTALLS = 1 << 13;
14492         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14493         public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14494
14495         public static final int OPTION_SHOW_FILTERS = 1 << 0;
14496
14497         private int mTypes;
14498
14499         private int mOptions;
14500
14501         private boolean mTitlePrinted;
14502
14503         private SharedUserSetting mSharedUser;
14504
14505         public boolean isDumping(int type) {
14506             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14507                 return true;
14508             }
14509
14510             return (mTypes & type) != 0;
14511         }
14512
14513         public void setDump(int type) {
14514             mTypes |= type;
14515         }
14516
14517         public boolean isOptionEnabled(int option) {
14518             return (mOptions & option) != 0;
14519         }
14520
14521         public void setOptionEnabled(int option) {
14522             mOptions |= option;
14523         }
14524
14525         public boolean onTitlePrinted() {
14526             final boolean printed = mTitlePrinted;
14527             mTitlePrinted = true;
14528             return printed;
14529         }
14530
14531         public boolean getTitlePrinted() {
14532             return mTitlePrinted;
14533         }
14534
14535         public void setTitlePrinted(boolean enabled) {
14536             mTitlePrinted = enabled;
14537         }
14538
14539         public SharedUserSetting getSharedUser() {
14540             return mSharedUser;
14541         }
14542
14543         public void setSharedUser(SharedUserSetting user) {
14544             mSharedUser = user;
14545         }
14546     }
14547
14548     @Override
14549     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14550         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14551                 != PackageManager.PERMISSION_GRANTED) {
14552             pw.println("Permission Denial: can't dump ActivityManager from from pid="
14553                     + Binder.getCallingPid()
14554                     + ", uid=" + Binder.getCallingUid()
14555                     + " without permission "
14556                     + android.Manifest.permission.DUMP);
14557             return;
14558         }
14559
14560         DumpState dumpState = new DumpState();
14561         boolean fullPreferred = false;
14562         boolean checkin = false;
14563
14564         String packageName = null;
14565         ArraySet<String> permissionNames = null;
14566
14567         int opti = 0;
14568         while (opti < args.length) {
14569             String opt = args[opti];
14570             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14571                 break;
14572             }
14573             opti++;
14574
14575             if ("-a".equals(opt)) {
14576                 // Right now we only know how to print all.
14577             } else if ("-h".equals(opt)) {
14578                 pw.println("Package manager dump options:");
14579                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14580                 pw.println("    --checkin: dump for a checkin");
14581                 pw.println("    -f: print details of intent filters");
14582                 pw.println("    -h: print this help");
14583                 pw.println("  cmd may be one of:");
14584                 pw.println("    l[ibraries]: list known shared libraries");
14585                 pw.println("    f[ibraries]: list device features");
14586                 pw.println("    k[eysets]: print known keysets");
14587                 pw.println("    r[esolvers]: dump intent resolvers");
14588                 pw.println("    perm[issions]: dump permissions");
14589                 pw.println("    permission [name ...]: dump declaration and use of given permission");
14590                 pw.println("    pref[erred]: print preferred package settings");
14591                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14592                 pw.println("    prov[iders]: dump content providers");
14593                 pw.println("    p[ackages]: dump installed packages");
14594                 pw.println("    s[hared-users]: dump shared user IDs");
14595                 pw.println("    m[essages]: print collected runtime messages");
14596                 pw.println("    v[erifiers]: print package verifier info");
14597                 pw.println("    version: print database version info");
14598                 pw.println("    write: write current settings now");
14599                 pw.println("    <package.name>: info about given package");
14600                 pw.println("    installs: details about install sessions");
14601                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14602                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14603                 return;
14604             } else if ("--checkin".equals(opt)) {
14605                 checkin = true;
14606             } else if ("-f".equals(opt)) {
14607                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14608             } else {
14609                 pw.println("Unknown argument: " + opt + "; use -h for help");
14610             }
14611         }
14612
14613         // Is the caller requesting to dump a particular piece of data?
14614         if (opti < args.length) {
14615             String cmd = args[opti];
14616             opti++;
14617             // Is this a package name?
14618             if ("android".equals(cmd) || cmd.contains(".")) {
14619                 packageName = cmd;
14620                 // When dumping a single package, we always dump all of its
14621                 // filter information since the amount of data will be reasonable.
14622                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14623             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14624                 dumpState.setDump(DumpState.DUMP_LIBS);
14625             } else if ("f".equals(cmd) || "features".equals(cmd)) {
14626                 dumpState.setDump(DumpState.DUMP_FEATURES);
14627             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14628                 dumpState.setDump(DumpState.DUMP_RESOLVERS);
14629             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14630                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14631             } else if ("permission".equals(cmd)) {
14632                 if (opti >= args.length) {
14633                     pw.println("Error: permission requires permission name");
14634                     return;
14635                 }
14636                 permissionNames = new ArraySet<>();
14637                 while (opti < args.length) {
14638                     permissionNames.add(args[opti]);
14639                     opti++;
14640                 }
14641                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
14642                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14643             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14644                 dumpState.setDump(DumpState.DUMP_PREFERRED);
14645             } else if ("preferred-xml".equals(cmd)) {
14646                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14647                 if (opti < args.length && "--full".equals(args[opti])) {
14648                     fullPreferred = true;
14649                     opti++;
14650                 }
14651             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14652                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14653             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14654                 dumpState.setDump(DumpState.DUMP_PACKAGES);
14655             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14656                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14657             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14658                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
14659             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14660                 dumpState.setDump(DumpState.DUMP_MESSAGES);
14661             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14662                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
14663             } else if ("i".equals(cmd) || "ifv".equals(cmd)
14664                     || "intent-filter-verifiers".equals(cmd)) {
14665                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14666             } else if ("version".equals(cmd)) {
14667                 dumpState.setDump(DumpState.DUMP_VERSION);
14668             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14669                 dumpState.setDump(DumpState.DUMP_KEYSETS);
14670             } else if ("installs".equals(cmd)) {
14671                 dumpState.setDump(DumpState.DUMP_INSTALLS);
14672             } else if ("write".equals(cmd)) {
14673                 synchronized (mPackages) {
14674                     mSettings.writeLPr();
14675                     pw.println("Settings written.");
14676                     return;
14677                 }
14678             }
14679         }
14680
14681         if (checkin) {
14682             pw.println("vers,1");
14683         }
14684
14685         // reader
14686         synchronized (mPackages) {
14687             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14688                 if (!checkin) {
14689                     if (dumpState.onTitlePrinted())
14690                         pw.println();
14691                     pw.println("Database versions:");
14692                     pw.print("  SDK Version:");
14693                     pw.print(" internal=");
14694                     pw.print(mSettings.mInternalSdkPlatform);
14695                     pw.print(" external=");
14696                     pw.println(mSettings.mExternalSdkPlatform);
14697                     pw.print("  DB Version:");
14698                     pw.print(" internal=");
14699                     pw.print(mSettings.mInternalDatabaseVersion);
14700                     pw.print(" external=");
14701                     pw.println(mSettings.mExternalDatabaseVersion);
14702                 }
14703             }
14704
14705             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14706                 if (!checkin) {
14707                     if (dumpState.onTitlePrinted())
14708                         pw.println();
14709                     pw.println("Verifiers:");
14710                     pw.print("  Required: ");
14711                     pw.print(mRequiredVerifierPackage);
14712                     pw.print(" (uid=");
14713                     pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14714                     pw.println(")");
14715                 } else if (mRequiredVerifierPackage != null) {
14716                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14717                     pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14718                 }
14719             }
14720
14721             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14722                     packageName == null) {
14723                 if (mIntentFilterVerifierComponent != null) {
14724                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14725                     if (!checkin) {
14726                         if (dumpState.onTitlePrinted())
14727                             pw.println();
14728                         pw.println("Intent Filter Verifier:");
14729                         pw.print("  Using: ");
14730                         pw.print(verifierPackageName);
14731                         pw.print(" (uid=");
14732                         pw.print(getPackageUid(verifierPackageName, 0));
14733                         pw.println(")");
14734                     } else if (verifierPackageName != null) {
14735                         pw.print("ifv,"); pw.print(verifierPackageName);
14736                         pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14737                     }
14738                 } else {
14739                     pw.println();
14740                     pw.println("No Intent Filter Verifier available!");
14741                 }
14742             }
14743
14744             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14745                 boolean printedHeader = false;
14746                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
14747                 while (it.hasNext()) {
14748                     String name = it.next();
14749                     SharedLibraryEntry ent = mSharedLibraries.get(name);
14750                     if (!checkin) {
14751                         if (!printedHeader) {
14752                             if (dumpState.onTitlePrinted())
14753                                 pw.println();
14754                             pw.println("Libraries:");
14755                             printedHeader = true;
14756                         }
14757                         pw.print("  ");
14758                     } else {
14759                         pw.print("lib,");
14760                     }
14761                     pw.print(name);
14762                     if (!checkin) {
14763                         pw.print(" -> ");
14764                     }
14765                     if (ent.path != null) {
14766                         if (!checkin) {
14767                             pw.print("(jar) ");
14768                             pw.print(ent.path);
14769                         } else {
14770                             pw.print(",jar,");
14771                             pw.print(ent.path);
14772                         }
14773                     } else {
14774                         if (!checkin) {
14775                             pw.print("(apk) ");
14776                             pw.print(ent.apk);
14777                         } else {
14778                             pw.print(",apk,");
14779                             pw.print(ent.apk);
14780                         }
14781                     }
14782                     pw.println();
14783                 }
14784             }
14785
14786             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14787                 if (dumpState.onTitlePrinted())
14788                     pw.println();
14789                 if (!checkin) {
14790                     pw.println("Features:");
14791                 }
14792                 Iterator<String> it = mAvailableFeatures.keySet().iterator();
14793                 while (it.hasNext()) {
14794                     String name = it.next();
14795                     if (!checkin) {
14796                         pw.print("  ");
14797                     } else {
14798                         pw.print("feat,");
14799                     }
14800                     pw.println(name);
14801                 }
14802             }
14803
14804             if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14805                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14806                         : "Activity Resolver Table:", "  ", packageName,
14807                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14808                     dumpState.setTitlePrinted(true);
14809                 }
14810                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14811                         : "Receiver Resolver Table:", "  ", packageName,
14812                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14813                     dumpState.setTitlePrinted(true);
14814                 }
14815                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14816                         : "Service Resolver Table:", "  ", packageName,
14817                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14818                     dumpState.setTitlePrinted(true);
14819                 }
14820                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14821                         : "Provider Resolver Table:", "  ", packageName,
14822                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14823                     dumpState.setTitlePrinted(true);
14824                 }
14825             }
14826
14827             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14828                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14829                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14830                     int user = mSettings.mPreferredActivities.keyAt(i);
14831                     if (pir.dump(pw,
14832                             dumpState.getTitlePrinted()
14833                                 ? "\nPreferred Activities User " + user + ":"
14834                                 : "Preferred Activities User " + user + ":", "  ",
14835                             packageName, true, false)) {
14836                         dumpState.setTitlePrinted(true);
14837                     }
14838                 }
14839             }
14840
14841             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14842                 pw.flush();
14843                 FileOutputStream fout = new FileOutputStream(fd);
14844                 BufferedOutputStream str = new BufferedOutputStream(fout);
14845                 XmlSerializer serializer = new FastXmlSerializer();
14846                 try {
14847                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
14848                     serializer.startDocument(null, true);
14849                     serializer.setFeature(
14850                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14851                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14852                     serializer.endDocument();
14853                     serializer.flush();
14854                 } catch (IllegalArgumentException e) {
14855                     pw.println("Failed writing: " + e);
14856                 } catch (IllegalStateException e) {
14857                     pw.println("Failed writing: " + e);
14858                 } catch (IOException e) {
14859                     pw.println("Failed writing: " + e);
14860                 }
14861             }
14862
14863             if (!checkin
14864                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14865                     && packageName == null) {
14866                 pw.println();
14867                 int count = mSettings.mPackages.size();
14868                 if (count == 0) {
14869                     pw.println("No applications!");
14870                     pw.println();
14871                 } else {
14872                     final String prefix = "  ";
14873                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14874                     if (allPackageSettings.size() == 0) {
14875                         pw.println("No domain preferred apps!");
14876                         pw.println();
14877                     } else {
14878                         pw.println("App verification status:");
14879                         pw.println();
14880                         count = 0;
14881                         for (PackageSetting ps : allPackageSettings) {
14882                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14883                             if (ivi == null || ivi.getPackageName() == null) continue;
14884                             pw.println(prefix + "Package: " + ivi.getPackageName());
14885                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
14886                             pw.println(prefix + "Status:  " + ivi.getStatusString());
14887                             pw.println();
14888                             count++;
14889                         }
14890                         if (count == 0) {
14891                             pw.println(prefix + "No app verification established.");
14892                             pw.println();
14893                         }
14894                         for (int userId : sUserManager.getUserIds()) {
14895                             pw.println("App linkages for user " + userId + ":");
14896                             pw.println();
14897                             count = 0;
14898                             for (PackageSetting ps : allPackageSettings) {
14899                                 final long status = ps.getDomainVerificationStatusForUser(userId);
14900                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14901                                     continue;
14902                                 }
14903                                 pw.println(prefix + "Package: " + ps.name);
14904                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14905                                 String statusStr = IntentFilterVerificationInfo.
14906                                         getStatusStringFromValue(status);
14907                                 pw.println(prefix + "Status:  " + statusStr);
14908                                 pw.println();
14909                                 count++;
14910                             }
14911                             if (count == 0) {
14912                                 pw.println(prefix + "No configured app linkages.");
14913                                 pw.println();
14914                             }
14915                         }
14916                     }
14917                 }
14918             }
14919
14920             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14921                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14922                 if (packageName == null && permissionNames == null) {
14923                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14924                         if (iperm == 0) {
14925                             if (dumpState.onTitlePrinted())
14926                                 pw.println();
14927                             pw.println("AppOp Permissions:");
14928                         }
14929                         pw.print("  AppOp Permission ");
14930                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
14931                         pw.println(":");
14932                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14933                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14934                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14935                         }
14936                     }
14937                 }
14938             }
14939
14940             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14941                 boolean printedSomething = false;
14942                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
14943                     if (packageName != null && !packageName.equals(p.info.packageName)) {
14944                         continue;
14945                     }
14946                     if (!printedSomething) {
14947                         if (dumpState.onTitlePrinted())
14948                             pw.println();
14949                         pw.println("Registered ContentProviders:");
14950                         printedSomething = true;
14951                     }
14952                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14953                     pw.print("    "); pw.println(p.toString());
14954                 }
14955                 printedSomething = false;
14956                 for (Map.Entry<String, PackageParser.Provider> entry :
14957                         mProvidersByAuthority.entrySet()) {
14958                     PackageParser.Provider p = entry.getValue();
14959                     if (packageName != null && !packageName.equals(p.info.packageName)) {
14960                         continue;
14961                     }
14962                     if (!printedSomething) {
14963                         if (dumpState.onTitlePrinted())
14964                             pw.println();
14965                         pw.println("ContentProvider Authorities:");
14966                         printedSomething = true;
14967                     }
14968                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14969                     pw.print("    "); pw.println(p.toString());
14970                     if (p.info != null && p.info.applicationInfo != null) {
14971                         final String appInfo = p.info.applicationInfo.toString();
14972                         pw.print("      applicationInfo="); pw.println(appInfo);
14973                     }
14974                 }
14975             }
14976
14977             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14978                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14979             }
14980
14981             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14982                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14983             }
14984
14985             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14986                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14987             }
14988
14989             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14990                 // XXX should handle packageName != null by dumping only install data that
14991                 // the given package is involved with.
14992                 if (dumpState.onTitlePrinted()) pw.println();
14993                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14994             }
14995
14996             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14997                 if (dumpState.onTitlePrinted()) pw.println();
14998                 mSettings.dumpReadMessagesLPr(pw, dumpState);
14999
15000                 pw.println();
15001                 pw.println("Package warning messages:");
15002                 BufferedReader in = null;
15003                 String line = null;
15004                 try {
15005                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15006                     while ((line = in.readLine()) != null) {
15007                         if (line.contains("ignored: updated version")) continue;
15008                         pw.println(line);
15009                     }
15010                 } catch (IOException ignored) {
15011                 } finally {
15012                     IoUtils.closeQuietly(in);
15013                 }
15014             }
15015
15016             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15017                 BufferedReader in = null;
15018                 String line = null;
15019                 try {
15020                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15021                     while ((line = in.readLine()) != null) {
15022                         if (line.contains("ignored: updated version")) continue;
15023                         pw.print("msg,");
15024                         pw.println(line);
15025                     }
15026                 } catch (IOException ignored) {
15027                 } finally {
15028                     IoUtils.closeQuietly(in);
15029                 }
15030             }
15031         }
15032     }
15033
15034     private String dumpDomainString(String packageName) {
15035         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15036         List<IntentFilter> filters = getAllIntentFilters(packageName);
15037
15038         ArraySet<String> result = new ArraySet<>();
15039         if (iviList.size() > 0) {
15040             for (IntentFilterVerificationInfo ivi : iviList) {
15041                 for (String host : ivi.getDomains()) {
15042                     result.add(host);
15043                 }
15044             }
15045         }
15046         if (filters != null && filters.size() > 0) {
15047             for (IntentFilter filter : filters) {
15048                 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15049                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15050                     result.addAll(filter.getHostsList());
15051                 }
15052             }
15053         }
15054
15055         StringBuilder sb = new StringBuilder(result.size() * 16);
15056         for (String domain : result) {
15057             if (sb.length() > 0) sb.append(" ");
15058             sb.append(domain);
15059         }
15060         return sb.toString();
15061     }
15062
15063     // ------- apps on sdcard specific code -------
15064     static final boolean DEBUG_SD_INSTALL = false;
15065
15066     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15067
15068     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15069
15070     private boolean mMediaMounted = false;
15071
15072     static String getEncryptKey() {
15073         try {
15074             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15075                     SD_ENCRYPTION_KEYSTORE_NAME);
15076             if (sdEncKey == null) {
15077                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15078                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15079                 if (sdEncKey == null) {
15080                     Slog.e(TAG, "Failed to create encryption keys");
15081                     return null;
15082                 }
15083             }
15084             return sdEncKey;
15085         } catch (NoSuchAlgorithmException nsae) {
15086             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15087             return null;
15088         } catch (IOException ioe) {
15089             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15090             return null;
15091         }
15092     }
15093
15094     /*
15095      * Update media status on PackageManager.
15096      */
15097     @Override
15098     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15099         int callingUid = Binder.getCallingUid();
15100         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15101             throw new SecurityException("Media status can only be updated by the system");
15102         }
15103         // reader; this apparently protects mMediaMounted, but should probably
15104         // be a different lock in that case.
15105         synchronized (mPackages) {
15106             Log.i(TAG, "Updating external media status from "
15107                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
15108                     + (mediaStatus ? "mounted" : "unmounted"));
15109             if (DEBUG_SD_INSTALL)
15110                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15111                         + ", mMediaMounted=" + mMediaMounted);
15112             if (mediaStatus == mMediaMounted) {
15113                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15114                         : 0, -1);
15115                 mHandler.sendMessage(msg);
15116                 return;
15117             }
15118             mMediaMounted = mediaStatus;
15119         }
15120         // Queue up an async operation since the package installation may take a
15121         // little while.
15122         mHandler.post(new Runnable() {
15123             public void run() {
15124                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15125             }
15126         });
15127     }
15128
15129     /**
15130      * Called by MountService when the initial ASECs to scan are available.
15131      * Should block until all the ASEC containers are finished being scanned.
15132      */
15133     public void scanAvailableAsecs() {
15134         updateExternalMediaStatusInner(true, false, false);
15135         if (mShouldRestoreconData) {
15136             SELinuxMMAC.setRestoreconDone();
15137             mShouldRestoreconData = false;
15138         }
15139     }
15140
15141     /*
15142      * Collect information of applications on external media, map them against
15143      * existing containers and update information based on current mount status.
15144      * Please note that we always have to report status if reportStatus has been
15145      * set to true especially when unloading packages.
15146      */
15147     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15148             boolean externalStorage) {
15149         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15150         int[] uidArr = EmptyArray.INT;
15151
15152         final String[] list = PackageHelper.getSecureContainerList();
15153         if (ArrayUtils.isEmpty(list)) {
15154             Log.i(TAG, "No secure containers found");
15155         } else {
15156             // Process list of secure containers and categorize them
15157             // as active or stale based on their package internal state.
15158
15159             // reader
15160             synchronized (mPackages) {
15161                 for (String cid : list) {
15162                     // Leave stages untouched for now; installer service owns them
15163                     if (PackageInstallerService.isStageName(cid)) continue;
15164
15165                     if (DEBUG_SD_INSTALL)
15166                         Log.i(TAG, "Processing container " + cid);
15167                     String pkgName = getAsecPackageName(cid);
15168                     if (pkgName == null) {
15169                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
15170                         continue;
15171                     }
15172                     if (DEBUG_SD_INSTALL)
15173                         Log.i(TAG, "Looking for pkg : " + pkgName);
15174
15175                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
15176                     if (ps == null) {
15177                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15178                         continue;
15179                     }
15180
15181                     /*
15182                      * Skip packages that are not external if we're unmounting
15183                      * external storage.
15184                      */
15185                     if (externalStorage && !isMounted && !isExternal(ps)) {
15186                         continue;
15187                     }
15188
15189                     final AsecInstallArgs args = new AsecInstallArgs(cid,
15190                             getAppDexInstructionSets(ps), ps.isForwardLocked());
15191                     // The package status is changed only if the code path
15192                     // matches between settings and the container id.
15193                     if (ps.codePathString != null
15194                             && ps.codePathString.startsWith(args.getCodePath())) {
15195                         if (DEBUG_SD_INSTALL) {
15196                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15197                                     + " at code path: " + ps.codePathString);
15198                         }
15199
15200                         // We do have a valid package installed on sdcard
15201                         processCids.put(args, ps.codePathString);
15202                         final int uid = ps.appId;
15203                         if (uid != -1) {
15204                             uidArr = ArrayUtils.appendInt(uidArr, uid);
15205                         }
15206                     } else {
15207                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15208                                 + ps.codePathString);
15209                     }
15210                 }
15211             }
15212
15213             Arrays.sort(uidArr);
15214         }
15215
15216         // Process packages with valid entries.
15217         if (isMounted) {
15218             if (DEBUG_SD_INSTALL)
15219                 Log.i(TAG, "Loading packages");
15220             loadMediaPackages(processCids, uidArr);
15221             startCleaningPackages();
15222             mInstallerService.onSecureContainersAvailable();
15223         } else {
15224             if (DEBUG_SD_INSTALL)
15225                 Log.i(TAG, "Unloading packages");
15226             unloadMediaPackages(processCids, uidArr, reportStatus);
15227         }
15228     }
15229
15230     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15231             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15232         final int size = infos.size();
15233         final String[] packageNames = new String[size];
15234         final int[] packageUids = new int[size];
15235         for (int i = 0; i < size; i++) {
15236             final ApplicationInfo info = infos.get(i);
15237             packageNames[i] = info.packageName;
15238             packageUids[i] = info.uid;
15239         }
15240         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15241                 finishedReceiver);
15242     }
15243
15244     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15245             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15246         sendResourcesChangedBroadcast(mediaStatus, replacing,
15247                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15248     }
15249
15250     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15251             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15252         int size = pkgList.length;
15253         if (size > 0) {
15254             // Send broadcasts here
15255             Bundle extras = new Bundle();
15256             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15257             if (uidArr != null) {
15258                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15259             }
15260             if (replacing) {
15261                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15262             }
15263             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15264                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15265             sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15266         }
15267     }
15268
15269    /*
15270      * Look at potentially valid container ids from processCids If package
15271      * information doesn't match the one on record or package scanning fails,
15272      * the cid is added to list of removeCids. We currently don't delete stale
15273      * containers.
15274      */
15275     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15276         ArrayList<String> pkgList = new ArrayList<String>();
15277         Set<AsecInstallArgs> keys = processCids.keySet();
15278
15279         for (AsecInstallArgs args : keys) {
15280             String codePath = processCids.get(args);
15281             if (DEBUG_SD_INSTALL)
15282                 Log.i(TAG, "Loading container : " + args.cid);
15283             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15284             try {
15285                 // Make sure there are no container errors first.
15286                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15287                     Slog.e(TAG, "Failed to mount cid : " + args.cid
15288                             + " when installing from sdcard");
15289                     continue;
15290                 }
15291                 // Check code path here.
15292                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15293                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15294                             + " does not match one in settings " + codePath);
15295                     continue;
15296                 }
15297                 // Parse package
15298                 int parseFlags = mDefParseFlags;
15299                 if (args.isExternalAsec()) {
15300                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15301                 }
15302                 if (args.isFwdLocked()) {
15303                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15304                 }
15305
15306                 synchronized (mInstallLock) {
15307                     PackageParser.Package pkg = null;
15308                     try {
15309                         pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15310                     } catch (PackageManagerException e) {
15311                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15312                     }
15313                     // Scan the package
15314                     if (pkg != null) {
15315                         /*
15316                          * TODO why is the lock being held? doPostInstall is
15317                          * called in other places without the lock. This needs
15318                          * to be straightened out.
15319                          */
15320                         // writer
15321                         synchronized (mPackages) {
15322                             retCode = PackageManager.INSTALL_SUCCEEDED;
15323                             pkgList.add(pkg.packageName);
15324                             // Post process args
15325                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15326                                     pkg.applicationInfo.uid);
15327                         }
15328                     } else {
15329                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15330                     }
15331                 }
15332
15333             } finally {
15334                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15335                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15336                 }
15337             }
15338         }
15339         // writer
15340         synchronized (mPackages) {
15341             // If the platform SDK has changed since the last time we booted,
15342             // we need to re-grant app permission to catch any new ones that
15343             // appear. This is really a hack, and means that apps can in some
15344             // cases get permissions that the user didn't initially explicitly
15345             // allow... it would be nice to have some better way to handle
15346             // this situation.
15347             final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15348             if (regrantPermissions)
15349                 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15350                         + mSdkVersion + "; regranting permissions for external storage");
15351             mSettings.mExternalSdkPlatform = mSdkVersion;
15352
15353             // Make sure group IDs have been assigned, and any permission
15354             // changes in other apps are accounted for
15355             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15356                     | (regrantPermissions
15357                             ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15358                             : 0));
15359
15360             mSettings.updateExternalDatabaseVersion();
15361
15362             // can downgrade to reader
15363             // Persist settings
15364             mSettings.writeLPr();
15365         }
15366         // Send a broadcast to let everyone know we are done processing
15367         if (pkgList.size() > 0) {
15368             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15369         }
15370     }
15371
15372    /*
15373      * Utility method to unload a list of specified containers
15374      */
15375     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15376         // Just unmount all valid containers.
15377         for (AsecInstallArgs arg : cidArgs) {
15378             synchronized (mInstallLock) {
15379                 arg.doPostDeleteLI(false);
15380            }
15381        }
15382    }
15383
15384     /*
15385      * Unload packages mounted on external media. This involves deleting package
15386      * data from internal structures, sending broadcasts about diabled packages,
15387      * gc'ing to free up references, unmounting all secure containers
15388      * corresponding to packages on external media, and posting a
15389      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15390      * that we always have to post this message if status has been requested no
15391      * matter what.
15392      */
15393     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15394             final boolean reportStatus) {
15395         if (DEBUG_SD_INSTALL)
15396             Log.i(TAG, "unloading media packages");
15397         ArrayList<String> pkgList = new ArrayList<String>();
15398         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15399         final Set<AsecInstallArgs> keys = processCids.keySet();
15400         for (AsecInstallArgs args : keys) {
15401             String pkgName = args.getPackageName();
15402             if (DEBUG_SD_INSTALL)
15403                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
15404             // Delete package internally
15405             PackageRemovedInfo outInfo = new PackageRemovedInfo();
15406             synchronized (mInstallLock) {
15407                 boolean res = deletePackageLI(pkgName, null, false, null, null,
15408                         PackageManager.DELETE_KEEP_DATA, outInfo, false);
15409                 if (res) {
15410                     pkgList.add(pkgName);
15411                 } else {
15412                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15413                     failedList.add(args);
15414                 }
15415             }
15416         }
15417
15418         // reader
15419         synchronized (mPackages) {
15420             // We didn't update the settings after removing each package;
15421             // write them now for all packages.
15422             mSettings.writeLPr();
15423         }
15424
15425         // We have to absolutely send UPDATED_MEDIA_STATUS only
15426         // after confirming that all the receivers processed the ordered
15427         // broadcast when packages get disabled, force a gc to clean things up.
15428         // and unload all the containers.
15429         if (pkgList.size() > 0) {
15430             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15431                     new IIntentReceiver.Stub() {
15432                 public void performReceive(Intent intent, int resultCode, String data,
15433                         Bundle extras, boolean ordered, boolean sticky,
15434                         int sendingUser) throws RemoteException {
15435                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15436                             reportStatus ? 1 : 0, 1, keys);
15437                     mHandler.sendMessage(msg);
15438                 }
15439             });
15440         } else {
15441             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15442                     keys);
15443             mHandler.sendMessage(msg);
15444         }
15445     }
15446
15447     private void loadPrivatePackages(VolumeInfo vol) {
15448         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15449         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15450         synchronized (mInstallLock) {
15451         synchronized (mPackages) {
15452             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15453             for (PackageSetting ps : packages) {
15454                 final PackageParser.Package pkg;
15455                 try {
15456                     pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15457                     loaded.add(pkg.applicationInfo);
15458                 } catch (PackageManagerException e) {
15459                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15460                 }
15461             }
15462
15463             // TODO: regrant any permissions that changed based since original install
15464
15465             mSettings.writeLPr();
15466         }
15467         }
15468
15469         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15470         sendResourcesChangedBroadcast(true, false, loaded, null);
15471     }
15472
15473     private void unloadPrivatePackages(VolumeInfo vol) {
15474         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15475         synchronized (mInstallLock) {
15476         synchronized (mPackages) {
15477             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15478             for (PackageSetting ps : packages) {
15479                 if (ps.pkg == null) continue;
15480
15481                 final ApplicationInfo info = ps.pkg.applicationInfo;
15482                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15483                 if (deletePackageLI(ps.name, null, false, null, null,
15484                         PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15485                     unloaded.add(info);
15486                 } else {
15487                     Slog.w(TAG, "Failed to unload " + ps.codePath);
15488                 }
15489             }
15490
15491             mSettings.writeLPr();
15492         }
15493         }
15494
15495         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15496         sendResourcesChangedBroadcast(false, false, unloaded, null);
15497     }
15498
15499     /**
15500      * Examine all users present on given mounted volume, and destroy data
15501      * belonging to users that are no longer valid, or whose user ID has been
15502      * recycled.
15503      */
15504     private void reconcileUsers(String volumeUuid) {
15505         final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15506         if (ArrayUtils.isEmpty(files)) {
15507             Slog.d(TAG, "No users found on " + volumeUuid);
15508             return;
15509         }
15510
15511         for (File file : files) {
15512             if (!file.isDirectory()) continue;
15513
15514             final int userId;
15515             final UserInfo info;
15516             try {
15517                 userId = Integer.parseInt(file.getName());
15518                 info = sUserManager.getUserInfo(userId);
15519             } catch (NumberFormatException e) {
15520                 Slog.w(TAG, "Invalid user directory " + file);
15521                 continue;
15522             }
15523
15524             boolean destroyUser = false;
15525             if (info == null) {
15526                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
15527                         + " because no matching user was found");
15528                 destroyUser = true;
15529             } else {
15530                 try {
15531                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
15532                 } catch (IOException e) {
15533                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
15534                             + " because we failed to enforce serial number: " + e);
15535                     destroyUser = true;
15536                 }
15537             }
15538
15539             if (destroyUser) {
15540                 synchronized (mInstallLock) {
15541                     mInstaller.removeUserDataDirs(volumeUuid, userId);
15542                 }
15543             }
15544         }
15545
15546         final UserManager um = mContext.getSystemService(UserManager.class);
15547         for (UserInfo user : um.getUsers()) {
15548             final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15549             if (userDir.exists()) continue;
15550
15551             try {
15552                 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15553                 UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15554             } catch (IOException e) {
15555                 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15556             }
15557         }
15558     }
15559
15560     /**
15561      * Examine all apps present on given mounted volume, and destroy apps that
15562      * aren't expected, either due to uninstallation or reinstallation on
15563      * another volume.
15564      */
15565     private void reconcileApps(String volumeUuid) {
15566         final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15567         if (ArrayUtils.isEmpty(files)) {
15568             Slog.d(TAG, "No apps found on " + volumeUuid);
15569             return;
15570         }
15571
15572         for (File file : files) {
15573             final boolean isPackage = (isApkFile(file) || file.isDirectory())
15574                     && !PackageInstallerService.isStageName(file.getName());
15575             if (!isPackage) {
15576                 // Ignore entries which are not packages
15577                 continue;
15578             }
15579
15580             boolean destroyApp = false;
15581             String packageName = null;
15582             try {
15583                 final PackageLite pkg = PackageParser.parsePackageLite(file,
15584                         PackageParser.PARSE_MUST_BE_APK);
15585                 packageName = pkg.packageName;
15586
15587                 synchronized (mPackages) {
15588                     final PackageSetting ps = mSettings.mPackages.get(packageName);
15589                     if (ps == null) {
15590                         logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15591                                 + volumeUuid + " because we found no install record");
15592                         destroyApp = true;
15593                     } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15594                         logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15595                                 + volumeUuid + " because we expected it on " + ps.volumeUuid);
15596                         destroyApp = true;
15597                     }
15598                 }
15599
15600             } catch (PackageParserException e) {
15601                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15602                 destroyApp = true;
15603             }
15604
15605             if (destroyApp) {
15606                 synchronized (mInstallLock) {
15607                     if (packageName != null) {
15608                         removeDataDirsLI(volumeUuid, packageName);
15609                     }
15610                     if (file.isDirectory()) {
15611                         mInstaller.rmPackageDir(file.getAbsolutePath());
15612                     } else {
15613                         file.delete();
15614                     }
15615                 }
15616             }
15617         }
15618     }
15619
15620     private void unfreezePackage(String packageName) {
15621         synchronized (mPackages) {
15622             final PackageSetting ps = mSettings.mPackages.get(packageName);
15623             if (ps != null) {
15624                 ps.frozen = false;
15625             }
15626         }
15627     }
15628
15629     @Override
15630     public int movePackage(final String packageName, final String volumeUuid) {
15631         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15632
15633         final int moveId = mNextMoveId.getAndIncrement();
15634         try {
15635             movePackageInternal(packageName, volumeUuid, moveId);
15636         } catch (PackageManagerException e) {
15637             Slog.w(TAG, "Failed to move " + packageName, e);
15638             mMoveCallbacks.notifyStatusChanged(moveId,
15639                     PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15640         }
15641         return moveId;
15642     }
15643
15644     private void movePackageInternal(final String packageName, final String volumeUuid,
15645             final int moveId) throws PackageManagerException {
15646         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15647         final StorageManager storage = mContext.getSystemService(StorageManager.class);
15648         final PackageManager pm = mContext.getPackageManager();
15649
15650         final boolean currentAsec;
15651         final String currentVolumeUuid;
15652         final File codeFile;
15653         final String installerPackageName;
15654         final String packageAbiOverride;
15655         final int appId;
15656         final String seinfo;
15657         final String label;
15658
15659         // reader
15660         synchronized (mPackages) {
15661             final PackageParser.Package pkg = mPackages.get(packageName);
15662             final PackageSetting ps = mSettings.mPackages.get(packageName);
15663             if (pkg == null || ps == null) {
15664                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15665             }
15666
15667             if (pkg.applicationInfo.isSystemApp()) {
15668                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15669                         "Cannot move system application");
15670             }
15671
15672             if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15673                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15674                         "Package already moved to " + volumeUuid);
15675             }
15676
15677             final File probe = new File(pkg.codePath);
15678             final File probeOat = new File(probe, "oat");
15679             if (!probe.isDirectory() || !probeOat.isDirectory()) {
15680                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15681                         "Move only supported for modern cluster style installs");
15682             }
15683
15684             if (ps.frozen) {
15685                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15686                         "Failed to move already frozen package");
15687             }
15688             ps.frozen = true;
15689
15690             currentAsec = pkg.applicationInfo.isForwardLocked()
15691                     || pkg.applicationInfo.isExternalAsec();
15692             currentVolumeUuid = ps.volumeUuid;
15693             codeFile = new File(pkg.codePath);
15694             installerPackageName = ps.installerPackageName;
15695             packageAbiOverride = ps.cpuAbiOverrideString;
15696             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15697             seinfo = pkg.applicationInfo.seinfo;
15698             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15699         }
15700
15701         // Now that we're guarded by frozen state, kill app during move
15702         killApplication(packageName, appId, "move pkg");
15703
15704         final Bundle extras = new Bundle();
15705         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15706         extras.putString(Intent.EXTRA_TITLE, label);
15707         mMoveCallbacks.notifyCreated(moveId, extras);
15708
15709         int installFlags;
15710         final boolean moveCompleteApp;
15711         final File measurePath;
15712
15713         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15714             installFlags = INSTALL_INTERNAL;
15715             moveCompleteApp = !currentAsec;
15716             measurePath = Environment.getDataAppDirectory(volumeUuid);
15717         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15718             installFlags = INSTALL_EXTERNAL;
15719             moveCompleteApp = false;
15720             measurePath = storage.getPrimaryPhysicalVolume().getPath();
15721         } else {
15722             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15723             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15724                     || !volume.isMountedWritable()) {
15725                 unfreezePackage(packageName);
15726                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15727                         "Move location not mounted private volume");
15728             }
15729
15730             Preconditions.checkState(!currentAsec);
15731
15732             installFlags = INSTALL_INTERNAL;
15733             moveCompleteApp = true;
15734             measurePath = Environment.getDataAppDirectory(volumeUuid);
15735         }
15736
15737         final PackageStats stats = new PackageStats(null, -1);
15738         synchronized (mInstaller) {
15739             if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15740                 unfreezePackage(packageName);
15741                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15742                         "Failed to measure package size");
15743             }
15744         }
15745
15746         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15747                 + stats.dataSize);
15748
15749         final long startFreeBytes = measurePath.getFreeSpace();
15750         final long sizeBytes;
15751         if (moveCompleteApp) {
15752             sizeBytes = stats.codeSize + stats.dataSize;
15753         } else {
15754             sizeBytes = stats.codeSize;
15755         }
15756
15757         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15758             unfreezePackage(packageName);
15759             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15760                     "Not enough free space to move");
15761         }
15762
15763         mMoveCallbacks.notifyStatusChanged(moveId, 10);
15764
15765         final CountDownLatch installedLatch = new CountDownLatch(1);
15766         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15767             @Override
15768             public void onUserActionRequired(Intent intent) throws RemoteException {
15769                 throw new IllegalStateException();
15770             }
15771
15772             @Override
15773             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15774                     Bundle extras) throws RemoteException {
15775                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15776                         + PackageManager.installStatusToString(returnCode, msg));
15777
15778                 installedLatch.countDown();
15779
15780                 // Regardless of success or failure of the move operation,
15781                 // always unfreeze the package
15782                 unfreezePackage(packageName);
15783
15784                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
15785                 switch (status) {
15786                     case PackageInstaller.STATUS_SUCCESS:
15787                         mMoveCallbacks.notifyStatusChanged(moveId,
15788                                 PackageManager.MOVE_SUCCEEDED);
15789                         break;
15790                     case PackageInstaller.STATUS_FAILURE_STORAGE:
15791                         mMoveCallbacks.notifyStatusChanged(moveId,
15792                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15793                         break;
15794                     default:
15795                         mMoveCallbacks.notifyStatusChanged(moveId,
15796                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15797                         break;
15798                 }
15799             }
15800         };
15801
15802         final MoveInfo move;
15803         if (moveCompleteApp) {
15804             // Kick off a thread to report progress estimates
15805             new Thread() {
15806                 @Override
15807                 public void run() {
15808                     while (true) {
15809                         try {
15810                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
15811                                 break;
15812                             }
15813                         } catch (InterruptedException ignored) {
15814                         }
15815
15816                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15817                         final int progress = 10 + (int) MathUtils.constrain(
15818                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15819                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
15820                     }
15821                 }
15822             }.start();
15823
15824             final String dataAppName = codeFile.getName();
15825             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15826                     dataAppName, appId, seinfo);
15827         } else {
15828             move = null;
15829         }
15830
15831         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15832
15833         final Message msg = mHandler.obtainMessage(INIT_COPY);
15834         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15835         msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15836                 installerPackageName, volumeUuid, null, user, packageAbiOverride);
15837         mHandler.sendMessage(msg);
15838     }
15839
15840     @Override
15841     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15842         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15843
15844         final int realMoveId = mNextMoveId.getAndIncrement();
15845         final Bundle extras = new Bundle();
15846         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15847         mMoveCallbacks.notifyCreated(realMoveId, extras);
15848
15849         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15850             @Override
15851             public void onCreated(int moveId, Bundle extras) {
15852                 // Ignored
15853             }
15854
15855             @Override
15856             public void onStatusChanged(int moveId, int status, long estMillis) {
15857                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15858             }
15859         };
15860
15861         final StorageManager storage = mContext.getSystemService(StorageManager.class);
15862         storage.setPrimaryStorageUuid(volumeUuid, callback);
15863         return realMoveId;
15864     }
15865
15866     @Override
15867     public int getMoveStatus(int moveId) {
15868         mContext.enforceCallingOrSelfPermission(
15869                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15870         return mMoveCallbacks.mLastStatus.get(moveId);
15871     }
15872
15873     @Override
15874     public void registerMoveCallback(IPackageMoveObserver callback) {
15875         mContext.enforceCallingOrSelfPermission(
15876                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15877         mMoveCallbacks.register(callback);
15878     }
15879
15880     @Override
15881     public void unregisterMoveCallback(IPackageMoveObserver callback) {
15882         mContext.enforceCallingOrSelfPermission(
15883                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15884         mMoveCallbacks.unregister(callback);
15885     }
15886
15887     @Override
15888     public boolean setInstallLocation(int loc) {
15889         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15890                 null);
15891         if (getInstallLocation() == loc) {
15892             return true;
15893         }
15894         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15895                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15896             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15897                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15898             return true;
15899         }
15900         return false;
15901    }
15902
15903     @Override
15904     public int getInstallLocation() {
15905         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15906                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15907                 PackageHelper.APP_INSTALL_AUTO);
15908     }
15909
15910     /** Called by UserManagerService */
15911     void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15912         mDirtyUsers.remove(userHandle);
15913         mSettings.removeUserLPw(userHandle);
15914         mPendingBroadcasts.remove(userHandle);
15915         if (mInstaller != null) {
15916             // Technically, we shouldn't be doing this with the package lock
15917             // held.  However, this is very rare, and there is already so much
15918             // other disk I/O going on, that we'll let it slide for now.
15919             final StorageManager storage = mContext.getSystemService(StorageManager.class);
15920             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15921                 final String volumeUuid = vol.getFsUuid();
15922                 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15923                 mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15924             }
15925         }
15926         mUserNeedsBadging.delete(userHandle);
15927         removeUnusedPackagesLILPw(userManager, userHandle);
15928     }
15929
15930     /**
15931      * We're removing userHandle and would like to remove any downloaded packages
15932      * that are no longer in use by any other user.
15933      * @param userHandle the user being removed
15934      */
15935     private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15936         final boolean DEBUG_CLEAN_APKS = false;
15937         int [] users = userManager.getUserIdsLPr();
15938         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15939         while (psit.hasNext()) {
15940             PackageSetting ps = psit.next();
15941             if (ps.pkg == null) {
15942                 continue;
15943             }
15944             final String packageName = ps.pkg.packageName;
15945             // Skip over if system app
15946             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15947                 continue;
15948             }
15949             if (DEBUG_CLEAN_APKS) {
15950                 Slog.i(TAG, "Checking package " + packageName);
15951             }
15952             boolean keep = false;
15953             for (int i = 0; i < users.length; i++) {
15954                 if (users[i] != userHandle && ps.getInstalled(users[i])) {
15955                     keep = true;
15956                     if (DEBUG_CLEAN_APKS) {
15957                         Slog.i(TAG, "  Keeping package " + packageName + " for user "
15958                                 + users[i]);
15959                     }
15960                     break;
15961                 }
15962             }
15963             if (!keep) {
15964                 if (DEBUG_CLEAN_APKS) {
15965                     Slog.i(TAG, "  Removing package " + packageName);
15966                 }
15967                 mHandler.post(new Runnable() {
15968                     public void run() {
15969                         deletePackageX(packageName, userHandle, 0);
15970                     } //end run
15971                 });
15972             }
15973         }
15974     }
15975
15976     /** Called by UserManagerService */
15977     void createNewUserLILPw(int userHandle) {
15978         if (mInstaller != null) {
15979             mInstaller.createUserConfig(userHandle);
15980             mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15981             applyFactoryDefaultBrowserLPw(userHandle);
15982             primeDomainVerificationsLPw(userHandle);
15983         }
15984     }
15985
15986     void newUserCreated(final int userHandle) {
15987         mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15988     }
15989
15990     @Override
15991     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15992         mContext.enforceCallingOrSelfPermission(
15993                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15994                 "Only package verification agents can read the verifier device identity");
15995
15996         synchronized (mPackages) {
15997             return mSettings.getVerifierDeviceIdentityLPw();
15998         }
15999     }
16000
16001     @Override
16002     public void setPermissionEnforced(String permission, boolean enforced) {
16003         mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16004         if (READ_EXTERNAL_STORAGE.equals(permission)) {
16005             synchronized (mPackages) {
16006                 if (mSettings.mReadExternalStorageEnforced == null
16007                         || mSettings.mReadExternalStorageEnforced != enforced) {
16008                     mSettings.mReadExternalStorageEnforced = enforced;
16009                     mSettings.writeLPr();
16010                 }
16011             }
16012             // kill any non-foreground processes so we restart them and
16013             // grant/revoke the GID.
16014             final IActivityManager am = ActivityManagerNative.getDefault();
16015             if (am != null) {
16016                 final long token = Binder.clearCallingIdentity();
16017                 try {
16018                     am.killProcessesBelowForeground("setPermissionEnforcement");
16019                 } catch (RemoteException e) {
16020                 } finally {
16021                     Binder.restoreCallingIdentity(token);
16022                 }
16023             }
16024         } else {
16025             throw new IllegalArgumentException("No selective enforcement for " + permission);
16026         }
16027     }
16028
16029     @Override
16030     @Deprecated
16031     public boolean isPermissionEnforced(String permission) {
16032         return true;
16033     }
16034
16035     @Override
16036     public boolean isStorageLow() {
16037         final long token = Binder.clearCallingIdentity();
16038         try {
16039             final DeviceStorageMonitorInternal
16040                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16041             if (dsm != null) {
16042                 return dsm.isMemoryLow();
16043             } else {
16044                 return false;
16045             }
16046         } finally {
16047             Binder.restoreCallingIdentity(token);
16048         }
16049     }
16050
16051     @Override
16052     public IPackageInstaller getPackageInstaller() {
16053         return mInstallerService;
16054     }
16055
16056     private boolean userNeedsBadging(int userId) {
16057         int index = mUserNeedsBadging.indexOfKey(userId);
16058         if (index < 0) {
16059             final UserInfo userInfo;
16060             final long token = Binder.clearCallingIdentity();
16061             try {
16062                 userInfo = sUserManager.getUserInfo(userId);
16063             } finally {
16064                 Binder.restoreCallingIdentity(token);
16065             }
16066             final boolean b;
16067             if (userInfo != null && userInfo.isManagedProfile()) {
16068                 b = true;
16069             } else {
16070                 b = false;
16071             }
16072             mUserNeedsBadging.put(userId, b);
16073             return b;
16074         }
16075         return mUserNeedsBadging.valueAt(index);
16076     }
16077
16078     @Override
16079     public KeySet getKeySetByAlias(String packageName, String alias) {
16080         if (packageName == null || alias == null) {
16081             return null;
16082         }
16083         synchronized(mPackages) {
16084             final PackageParser.Package pkg = mPackages.get(packageName);
16085             if (pkg == null) {
16086                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16087                 throw new IllegalArgumentException("Unknown package: " + packageName);
16088             }
16089             KeySetManagerService ksms = mSettings.mKeySetManagerService;
16090             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16091         }
16092     }
16093
16094     @Override
16095     public KeySet getSigningKeySet(String packageName) {
16096         if (packageName == null) {
16097             return null;
16098         }
16099         synchronized(mPackages) {
16100             final PackageParser.Package pkg = mPackages.get(packageName);
16101             if (pkg == null) {
16102                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16103                 throw new IllegalArgumentException("Unknown package: " + packageName);
16104             }
16105             if (pkg.applicationInfo.uid != Binder.getCallingUid()
16106                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
16107                 throw new SecurityException("May not access signing KeySet of other apps.");
16108             }
16109             KeySetManagerService ksms = mSettings.mKeySetManagerService;
16110             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16111         }
16112     }
16113
16114     @Override
16115     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16116         if (packageName == null || ks == null) {
16117             return false;
16118         }
16119         synchronized(mPackages) {
16120             final PackageParser.Package pkg = mPackages.get(packageName);
16121             if (pkg == null) {
16122                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16123                 throw new IllegalArgumentException("Unknown package: " + packageName);
16124             }
16125             IBinder ksh = ks.getToken();
16126             if (ksh instanceof KeySetHandle) {
16127                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16128                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16129             }
16130             return false;
16131         }
16132     }
16133
16134     @Override
16135     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16136         if (packageName == null || ks == null) {
16137             return false;
16138         }
16139         synchronized(mPackages) {
16140             final PackageParser.Package pkg = mPackages.get(packageName);
16141             if (pkg == null) {
16142                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16143                 throw new IllegalArgumentException("Unknown package: " + packageName);
16144             }
16145             IBinder ksh = ks.getToken();
16146             if (ksh instanceof KeySetHandle) {
16147                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16148                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16149             }
16150             return false;
16151         }
16152     }
16153
16154     public void getUsageStatsIfNoPackageUsageInfo() {
16155         if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16156             UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16157             if (usm == null) {
16158                 throw new IllegalStateException("UsageStatsManager must be initialized");
16159             }
16160             long now = System.currentTimeMillis();
16161             Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16162             for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16163                 String packageName = entry.getKey();
16164                 PackageParser.Package pkg = mPackages.get(packageName);
16165                 if (pkg == null) {
16166                     continue;
16167                 }
16168                 UsageStats usage = entry.getValue();
16169                 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16170                 mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16171             }
16172         }
16173     }
16174
16175     /**
16176      * Check and throw if the given before/after packages would be considered a
16177      * downgrade.
16178      */
16179     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16180             throws PackageManagerException {
16181         if (after.versionCode < before.mVersionCode) {
16182             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16183                     "Update version code " + after.versionCode + " is older than current "
16184                     + before.mVersionCode);
16185         } else if (after.versionCode == before.mVersionCode) {
16186             if (after.baseRevisionCode < before.baseRevisionCode) {
16187                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16188                         "Update base revision code " + after.baseRevisionCode
16189                         + " is older than current " + before.baseRevisionCode);
16190             }
16191
16192             if (!ArrayUtils.isEmpty(after.splitNames)) {
16193                 for (int i = 0; i < after.splitNames.length; i++) {
16194                     final String splitName = after.splitNames[i];
16195                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16196                     if (j != -1) {
16197                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16198                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16199                                     "Update split " + splitName + " revision code "
16200                                     + after.splitRevisionCodes[i] + " is older than current "
16201                                     + before.splitRevisionCodes[j]);
16202                         }
16203                     }
16204                 }
16205             }
16206         }
16207     }
16208
16209     private static class MoveCallbacks extends Handler {
16210         private static final int MSG_CREATED = 1;
16211         private static final int MSG_STATUS_CHANGED = 2;
16212
16213         private final RemoteCallbackList<IPackageMoveObserver>
16214                 mCallbacks = new RemoteCallbackList<>();
16215
16216         private final SparseIntArray mLastStatus = new SparseIntArray();
16217
16218         public MoveCallbacks(Looper looper) {
16219             super(looper);
16220         }
16221
16222         public void register(IPackageMoveObserver callback) {
16223             mCallbacks.register(callback);
16224         }
16225
16226         public void unregister(IPackageMoveObserver callback) {
16227             mCallbacks.unregister(callback);
16228         }
16229
16230         @Override
16231         public void handleMessage(Message msg) {
16232             final SomeArgs args = (SomeArgs) msg.obj;
16233             final int n = mCallbacks.beginBroadcast();
16234             for (int i = 0; i < n; i++) {
16235                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16236                 try {
16237                     invokeCallback(callback, msg.what, args);
16238                 } catch (RemoteException ignored) {
16239                 }
16240             }
16241             mCallbacks.finishBroadcast();
16242             args.recycle();
16243         }
16244
16245         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16246                 throws RemoteException {
16247             switch (what) {
16248                 case MSG_CREATED: {
16249                     callback.onCreated(args.argi1, (Bundle) args.arg2);
16250                     break;
16251                 }
16252                 case MSG_STATUS_CHANGED: {
16253                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16254                     break;
16255                 }
16256             }
16257         }
16258
16259         private void notifyCreated(int moveId, Bundle extras) {
16260             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16261
16262             final SomeArgs args = SomeArgs.obtain();
16263             args.argi1 = moveId;
16264             args.arg2 = extras;
16265             obtainMessage(MSG_CREATED, args).sendToTarget();
16266         }
16267
16268         private void notifyStatusChanged(int moveId, int status) {
16269             notifyStatusChanged(moveId, status, -1);
16270         }
16271
16272         private void notifyStatusChanged(int moveId, int status, long estMillis) {
16273             Slog.v(TAG, "Move " + moveId + " status " + status);
16274
16275             final SomeArgs args = SomeArgs.obtain();
16276             args.argi1 = moveId;
16277             args.argi2 = status;
16278             args.arg3 = estMillis;
16279             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16280
16281             synchronized (mLastStatus) {
16282                 mLastStatus.put(moveId, status);
16283             }
16284         }
16285     }
16286
16287     private final class OnPermissionChangeListeners extends Handler {
16288         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16289
16290         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16291                 new RemoteCallbackList<>();
16292
16293         public OnPermissionChangeListeners(Looper looper) {
16294             super(looper);
16295         }
16296
16297         @Override
16298         public void handleMessage(Message msg) {
16299             switch (msg.what) {
16300                 case MSG_ON_PERMISSIONS_CHANGED: {
16301                     final int uid = msg.arg1;
16302                     handleOnPermissionsChanged(uid);
16303                 } break;
16304             }
16305         }
16306
16307         public void addListenerLocked(IOnPermissionsChangeListener listener) {
16308             mPermissionListeners.register(listener);
16309
16310         }
16311
16312         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16313             mPermissionListeners.unregister(listener);
16314         }
16315
16316         public void onPermissionsChanged(int uid) {
16317             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16318                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16319             }
16320         }
16321
16322         private void handleOnPermissionsChanged(int uid) {
16323             final int count = mPermissionListeners.beginBroadcast();
16324             try {
16325                 for (int i = 0; i < count; i++) {
16326                     IOnPermissionsChangeListener callback = mPermissionListeners
16327                             .getBroadcastItem(i);
16328                     try {
16329                         callback.onPermissionsChanged(uid);
16330                     } catch (RemoteException e) {
16331                         Log.e(TAG, "Permission listener is dead", e);
16332                     }
16333                 }
16334             } finally {
16335                 mPermissionListeners.finishBroadcast();
16336             }
16337         }
16338     }
16339
16340     private class PackageManagerInternalImpl extends PackageManagerInternal {
16341         @Override
16342         public void setLocationPackagesProvider(PackagesProvider provider) {
16343             synchronized (mPackages) {
16344                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16345             }
16346         }
16347
16348         @Override
16349         public void setImePackagesProvider(PackagesProvider provider) {
16350             synchronized (mPackages) {
16351                 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16352             }
16353         }
16354
16355         @Override
16356         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16357             synchronized (mPackages) {
16358                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16359             }
16360         }
16361
16362         @Override
16363         public void setSmsAppPackagesProvider(PackagesProvider provider) {
16364             synchronized (mPackages) {
16365                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16366             }
16367         }
16368
16369         @Override
16370         public void setDialerAppPackagesProvider(PackagesProvider provider) {
16371             synchronized (mPackages) {
16372                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16373             }
16374         }
16375
16376         @Override
16377         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16378             synchronized (mPackages) {
16379                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16380             }
16381         }
16382
16383         @Override
16384         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16385             synchronized (mPackages) {
16386                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16387                         packageName, userId);
16388             }
16389         }
16390
16391         @Override
16392         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16393             synchronized (mPackages) {
16394                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16395                         packageName, userId);
16396             }
16397         }
16398     }
16399
16400     @Override
16401     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16402         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16403         synchronized (mPackages) {
16404             final long identity = Binder.clearCallingIdentity();
16405             try {
16406                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16407                         packageNames, userId);
16408             } finally {
16409                 Binder.restoreCallingIdentity(identity);
16410             }
16411         }
16412     }
16413
16414     private static void enforceSystemOrPhoneCaller(String tag) {
16415         int callingUid = Binder.getCallingUid();
16416         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16417             throw new SecurityException(
16418                     "Cannot call " + tag + " from UID " + callingUid);
16419         }
16420     }
16421 }