OSDN Git Service

DO NOT MERGE. Grant MMS Uri permissions as the calling UID. am: 6f754e48e9
[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.READ_EXTERNAL_STORAGE;
20 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
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_DENIED;
66 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67 import static android.content.pm.PackageParser.isApkFile;
68 import static android.os.Process.PACKAGE_INFO_GID;
69 import static android.os.Process.SYSTEM_UID;
70 import static android.system.OsConstants.O_CREAT;
71 import static android.system.OsConstants.O_RDWR;
72 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76 import static com.android.internal.util.ArrayUtils.appendInt;
77 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86 import android.Manifest;
87 import android.app.ActivityManager;
88 import android.app.ActivityManagerNative;
89 import android.app.AppGlobals;
90 import android.app.IActivityManager;
91 import android.app.admin.IDevicePolicyManager;
92 import android.app.backup.IBackupManager;
93 import android.app.usage.UsageStats;
94 import android.app.usage.UsageStatsManager;
95 import android.content.BroadcastReceiver;
96 import android.content.ComponentName;
97 import android.content.Context;
98 import android.content.IIntentReceiver;
99 import android.content.Intent;
100 import android.content.IntentFilter;
101 import android.content.IntentSender;
102 import android.content.IntentSender.SendIntentException;
103 import android.content.ServiceConnection;
104 import android.content.pm.ActivityInfo;
105 import android.content.pm.ApplicationInfo;
106 import android.content.pm.FeatureInfo;
107 import android.content.pm.IOnPermissionsChangeListener;
108 import android.content.pm.IPackageDataObserver;
109 import android.content.pm.IPackageDeleteObserver;
110 import android.content.pm.IPackageDeleteObserver2;
111 import android.content.pm.IPackageInstallObserver2;
112 import android.content.pm.IPackageInstaller;
113 import android.content.pm.IPackageManager;
114 import android.content.pm.IPackageMoveObserver;
115 import android.content.pm.IPackageStatsObserver;
116 import android.content.pm.InstrumentationInfo;
117 import android.content.pm.IntentFilterVerificationInfo;
118 import android.content.pm.KeySet;
119 import android.content.pm.ManifestDigest;
120 import android.content.pm.PackageCleanItem;
121 import android.content.pm.PackageInfo;
122 import android.content.pm.PackageInfoLite;
123 import android.content.pm.PackageInstaller;
124 import android.content.pm.PackageManager;
125 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126 import android.content.pm.PackageManagerInternal;
127 import android.content.pm.PackageParser;
128 import android.content.pm.PackageParser.ActivityIntentInfo;
129 import android.content.pm.PackageParser.PackageLite;
130 import android.content.pm.PackageParser.PackageParserException;
131 import android.content.pm.PackageStats;
132 import android.content.pm.PackageUserState;
133 import android.content.pm.ParceledListSlice;
134 import android.content.pm.PermissionGroupInfo;
135 import android.content.pm.PermissionInfo;
136 import android.content.pm.ProviderInfo;
137 import android.content.pm.ResolveInfo;
138 import android.content.pm.ServiceInfo;
139 import android.content.pm.Signature;
140 import android.content.pm.UserInfo;
141 import android.content.pm.VerificationParams;
142 import android.content.pm.VerifierDeviceIdentity;
143 import android.content.pm.VerifierInfo;
144 import android.content.res.Resources;
145 import android.hardware.display.DisplayManager;
146 import android.net.Uri;
147 import android.os.Debug;
148 import android.os.Binder;
149 import android.os.Build;
150 import android.os.Bundle;
151 import android.os.Environment;
152 import android.os.Environment.UserEnvironment;
153 import android.os.FileUtils;
154 import android.os.Handler;
155 import android.os.IBinder;
156 import android.os.Looper;
157 import android.os.Message;
158 import android.os.Parcel;
159 import android.os.ParcelFileDescriptor;
160 import android.os.Process;
161 import android.os.RemoteCallbackList;
162 import android.os.RemoteException;
163 import android.os.SELinux;
164 import android.os.ServiceManager;
165 import android.os.SystemClock;
166 import android.os.SystemProperties;
167 import android.os.UserHandle;
168 import android.os.UserManager;
169 import android.os.storage.IMountService;
170 import android.os.storage.MountServiceInternal;
171 import android.os.storage.StorageEventListener;
172 import android.os.storage.StorageManager;
173 import android.os.storage.VolumeInfo;
174 import android.os.storage.VolumeRecord;
175 import android.security.KeyStore;
176 import android.security.SystemKeyStore;
177 import android.system.ErrnoException;
178 import android.system.Os;
179 import android.system.StructStat;
180 import android.text.TextUtils;
181 import android.text.format.DateUtils;
182 import android.util.ArrayMap;
183 import android.util.ArraySet;
184 import android.util.AtomicFile;
185 import android.util.DisplayMetrics;
186 import android.util.EventLog;
187 import android.util.ExceptionUtils;
188 import android.util.Log;
189 import android.util.LogPrinter;
190 import android.util.MathUtils;
191 import android.util.PrintStreamPrinter;
192 import android.util.Slog;
193 import android.util.SparseArray;
194 import android.util.SparseBooleanArray;
195 import android.util.SparseIntArray;
196 import android.util.Xml;
197 import android.view.Display;
198
199 import dalvik.system.DexFile;
200 import dalvik.system.VMRuntime;
201
202 import libcore.io.IoUtils;
203 import libcore.util.EmptyArray;
204
205 import com.android.internal.R;
206 import com.android.internal.annotations.GuardedBy;
207 import com.android.internal.app.IMediaContainerService;
208 import com.android.internal.app.ResolverActivity;
209 import com.android.internal.content.NativeLibraryHelper;
210 import com.android.internal.content.PackageHelper;
211 import com.android.internal.os.IParcelFileDescriptorFactory;
212 import com.android.internal.os.SomeArgs;
213 import com.android.internal.os.Zygote;
214 import com.android.internal.util.ArrayUtils;
215 import com.android.internal.util.FastPrintWriter;
216 import com.android.internal.util.FastXmlSerializer;
217 import com.android.internal.util.IndentingPrintWriter;
218 import com.android.internal.util.Preconditions;
219 import com.android.server.EventLogTags;
220 import com.android.server.FgThread;
221 import com.android.server.IntentResolver;
222 import com.android.server.LocalServices;
223 import com.android.server.ServiceThread;
224 import com.android.server.SystemConfig;
225 import com.android.server.Watchdog;
226 import com.android.server.pm.PermissionsState.PermissionState;
227 import com.android.server.pm.Settings.DatabaseVersion;
228 import com.android.server.pm.Settings.VersionInfo;
229 import com.android.server.storage.DeviceStorageMonitorInternal;
230
231 import org.xmlpull.v1.XmlPullParser;
232 import org.xmlpull.v1.XmlPullParserException;
233 import org.xmlpull.v1.XmlSerializer;
234
235 import java.io.BufferedInputStream;
236 import java.io.BufferedOutputStream;
237 import java.io.BufferedReader;
238 import java.io.ByteArrayInputStream;
239 import java.io.ByteArrayOutputStream;
240 import java.io.File;
241 import java.io.FileDescriptor;
242 import java.io.FileNotFoundException;
243 import java.io.FileOutputStream;
244 import java.io.FileReader;
245 import java.io.FilenameFilter;
246 import java.io.IOException;
247 import java.io.InputStream;
248 import java.io.PrintWriter;
249 import java.nio.charset.StandardCharsets;
250 import java.security.NoSuchAlgorithmException;
251 import java.security.PublicKey;
252 import java.security.cert.CertificateEncodingException;
253 import java.security.cert.CertificateException;
254 import java.text.SimpleDateFormat;
255 import java.util.ArrayList;
256 import java.util.Arrays;
257 import java.util.Collection;
258 import java.util.Collections;
259 import java.util.Comparator;
260 import java.util.Date;
261 import java.util.Iterator;
262 import java.util.List;
263 import java.util.Map;
264 import java.util.Objects;
265 import java.util.Set;
266 import java.util.concurrent.CountDownLatch;
267 import java.util.concurrent.TimeUnit;
268 import java.util.concurrent.atomic.AtomicBoolean;
269 import java.util.concurrent.atomic.AtomicInteger;
270 import java.util.concurrent.atomic.AtomicLong;
271
272 /**
273  * Keep track of all those .apks everywhere.
274  *
275  * This is very central to the platform's security; please run the unit
276  * tests whenever making modifications here:
277  *
278 mmm frameworks/base/tests/AndroidTests
279 adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
280 adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
281  *
282  * {@hide}
283  */
284 public class PackageManagerService extends IPackageManager.Stub {
285     static final String TAG = "PackageManager";
286     static final boolean DEBUG_SETTINGS = false;
287     static final boolean DEBUG_PREFERRED = false;
288     static final boolean DEBUG_UPGRADE = false;
289     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290     private static final boolean DEBUG_BACKUP = false;
291     private static final boolean DEBUG_INSTALL = false;
292     private static final boolean DEBUG_REMOVE = false;
293     private static final boolean DEBUG_BROADCASTS = false;
294     private static final boolean DEBUG_SHOW_INFO = false;
295     private static final boolean DEBUG_PACKAGE_INFO = false;
296     private static final boolean DEBUG_INTENT_MATCHING = false;
297     private static final boolean DEBUG_PACKAGE_SCANNING = false;
298     private static final boolean DEBUG_VERIFY = false;
299     private static final boolean DEBUG_DEXOPT = false;
300     private static final boolean DEBUG_FILTERS = false;
301     private static final boolean DEBUG_ABI_SELECTION = false;
302
303     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
304
305     private static final int RADIO_UID = Process.PHONE_UID;
306     private static final int LOG_UID = Process.LOG_UID;
307     private static final int NFC_UID = Process.NFC_UID;
308     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
309     private static final int SHELL_UID = Process.SHELL_UID;
310
311     // Cap the size of permission trees that 3rd party apps can define
312     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
313
314     // Suffix used during package installation when copying/moving
315     // package apks to install directory.
316     private static final String INSTALL_PACKAGE_SUFFIX = "-";
317
318     static final int SCAN_NO_DEX = 1<<1;
319     static final int SCAN_FORCE_DEX = 1<<2;
320     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
321     static final int SCAN_NEW_INSTALL = 1<<4;
322     static final int SCAN_NO_PATHS = 1<<5;
323     static final int SCAN_UPDATE_TIME = 1<<6;
324     static final int SCAN_DEFER_DEX = 1<<7;
325     static final int SCAN_BOOTING = 1<<8;
326     static final int SCAN_TRUSTED_OVERLAY = 1<<9;
327     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
328     static final int SCAN_REPLACING = 1<<11;
329     static final int SCAN_REQUIRE_KNOWN = 1<<12;
330     static final int SCAN_MOVE = 1<<13;
331     static final int SCAN_INITIAL = 1<<14;
332
333     static final int REMOVE_CHATTY = 1<<16;
334
335     private static final int[] EMPTY_INT_ARRAY = new int[0];
336
337     /**
338      * Timeout (in milliseconds) after which the watchdog should declare that
339      * our handler thread is wedged.  The usual default for such things is one
340      * minute but we sometimes do very lengthy I/O operations on this thread,
341      * such as installing multi-gigabyte applications, so ours needs to be longer.
342      */
343     private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
344
345     /**
346      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
347      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
348      * settings entry if available, otherwise we use the hardcoded default.  If it's been
349      * more than this long since the last fstrim, we force one during the boot sequence.
350      *
351      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
352      * one gets run at the next available charging+idle time.  This final mandatory
353      * no-fstrim check kicks in only of the other scheduling criteria is never met.
354      */
355     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
356
357     /**
358      * Whether verification is enabled by default.
359      */
360     private static final boolean DEFAULT_VERIFY_ENABLE = true;
361
362     /**
363      * The default maximum time to wait for the verification agent to return in
364      * milliseconds.
365      */
366     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
367
368     /**
369      * The default response for package verification timeout.
370      *
371      * This can be either PackageManager.VERIFICATION_ALLOW or
372      * PackageManager.VERIFICATION_REJECT.
373      */
374     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
375
376     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
377
378     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
379             DEFAULT_CONTAINER_PACKAGE,
380             "com.android.defcontainer.DefaultContainerService");
381
382     private static final String KILL_APP_REASON_GIDS_CHANGED =
383             "permission grant or revoke changed gids";
384
385     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
386             "permissions revoked";
387
388     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
389
390     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
391
392     /** Permission grant: not grant the permission. */
393     private static final int GRANT_DENIED = 1;
394
395     /** Permission grant: grant the permission as an install permission. */
396     private static final int GRANT_INSTALL = 2;
397
398     /** Permission grant: grant the permission as an install permission for a legacy app. */
399     private static final int GRANT_INSTALL_LEGACY = 3;
400
401     /** Permission grant: grant the permission as a runtime one. */
402     private static final int GRANT_RUNTIME = 4;
403
404     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
405     private static final int GRANT_UPGRADE = 5;
406
407     /** Canonical intent used to identify what counts as a "web browser" app */
408     private static final Intent sBrowserIntent;
409     static {
410         sBrowserIntent = new Intent();
411         sBrowserIntent.setAction(Intent.ACTION_VIEW);
412         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
413         sBrowserIntent.setData(Uri.parse("http:"));
414     }
415
416     final ServiceThread mHandlerThread;
417
418     final PackageHandler mHandler;
419
420     /**
421      * Messages for {@link #mHandler} that need to wait for system ready before
422      * being dispatched.
423      */
424     private ArrayList<Message> mPostSystemReadyMessages;
425
426     final int mSdkVersion = Build.VERSION.SDK_INT;
427
428     final Context mContext;
429     final boolean mFactoryTest;
430     final boolean mOnlyCore;
431     final boolean mLazyDexOpt;
432     final long mDexOptLRUThresholdInMills;
433     final DisplayMetrics mMetrics;
434     final int mDefParseFlags;
435     final String[] mSeparateProcesses;
436     final boolean mIsUpgrade;
437
438     // This is where all application persistent data goes.
439     final File mAppDataDir;
440
441     // This is where all application persistent data goes for secondary users.
442     final File mUserAppDataDir;
443
444     /** The location for ASEC container files on internal storage. */
445     final String mAsecInternalPath;
446
447     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448     // LOCK HELD.  Can be called with mInstallLock held.
449     @GuardedBy("mInstallLock")
450     final Installer mInstaller;
451
452     /** Directory where installed third-party apps stored */
453     final File mAppInstallDir;
454
455     /**
456      * Directory to which applications installed internally have their
457      * 32 bit native libraries copied.
458      */
459     private File mAppLib32InstallDir;
460
461     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462     // apps.
463     final File mDrmAppPrivateInstallDir;
464
465     // ----------------------------------------------------------------
466
467     // Lock for state used when installing and doing other long running
468     // operations.  Methods that must be called with this lock held have
469     // the suffix "LI".
470     final Object mInstallLock = new Object();
471
472     // ----------------------------------------------------------------
473
474     // Keys are String (package name), values are Package.  This also serves
475     // as the lock for the global state.  Methods that must be called with
476     // this lock held have the prefix "LP".
477     @GuardedBy("mPackages")
478     final ArrayMap<String, PackageParser.Package> mPackages =
479             new ArrayMap<String, PackageParser.Package>();
480
481     // Tracks available target package names -> overlay package paths.
482     final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485     /**
486      * Tracks new system packages [received in an OTA] that we expect to
487      * find updated user-installed versions. Keys are package name, values
488      * are package location.
489      */
490     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492     /**
493      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494      */
495     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496     /**
497      * Whether or not system app permissions should be promoted from install to runtime.
498      */
499     boolean mPromoteSystemApps;
500
501     final Settings mSettings;
502     boolean mRestoredSettings;
503
504     // System configuration read by SystemConfig.
505     final int[] mGlobalGids;
506     final SparseArray<ArraySet<String>> mSystemPermissions;
507     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509     // If mac_permissions.xml was found for seinfo labeling.
510     boolean mFoundPolicyFile;
511
512     // If a recursive restorecon of /data/data/<pkg> is needed.
513     private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515     public static final class SharedLibraryEntry {
516         public final String path;
517         public final String apk;
518
519         SharedLibraryEntry(String _path, String _apk) {
520             path = _path;
521             apk = _apk;
522         }
523     }
524
525     // Currently known shared libraries.
526     final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527             new ArrayMap<String, SharedLibraryEntry>();
528
529     // All available activities, for your resolving pleasure.
530     final ActivityIntentResolver mActivities =
531             new ActivityIntentResolver();
532
533     // All available receivers, for your resolving pleasure.
534     final ActivityIntentResolver mReceivers =
535             new ActivityIntentResolver();
536
537     // All available services, for your resolving pleasure.
538     final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540     // All available providers, for your resolving pleasure.
541     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543     // Mapping from provider base names (first directory in content URI codePath)
544     // to the provider information.
545     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546             new ArrayMap<String, PackageParser.Provider>();
547
548     // Mapping from instrumentation class names to info about them.
549     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552     // Mapping from permission names to info about them.
553     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554             new ArrayMap<String, PackageParser.PermissionGroup>();
555
556     // Packages whose data we have transfered into another package, thus
557     // should no longer exist.
558     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560     // Broadcast actions that are only available to the system.
561     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563     /** List of packages waiting for verification. */
564     final SparseArray<PackageVerificationState> mPendingVerification
565             = new SparseArray<PackageVerificationState>();
566
567     /** Set of packages associated with each app op permission. */
568     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570     final PackageInstallerService mInstallerService;
571
572     private final PackageDexOptimizer mPackageDexOptimizer;
573
574     private AtomicInteger mNextMoveId = new AtomicInteger();
575     private final MoveCallbacks mMoveCallbacks;
576
577     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579     // Cache of users who need badging.
580     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582     /** Token for keys in mPendingVerification. */
583     private int mPendingVerificationToken = 0;
584
585     volatile boolean mSystemReady;
586     volatile boolean mSafeMode;
587     volatile boolean mHasSystemUidErrors;
588
589     ApplicationInfo mAndroidApplication;
590     final ActivityInfo mResolveActivity = new ActivityInfo();
591     final ResolveInfo mResolveInfo = new ResolveInfo();
592     ComponentName mResolveComponentName;
593     PackageParser.Package mPlatformPackage;
594     ComponentName mCustomResolverComponentName;
595
596     boolean mResolverReplaced = false;
597
598     private final ComponentName mIntentFilterVerifierComponent;
599     private int mIntentFilterVerificationToken = 0;
600
601     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602             = new SparseArray<IntentFilterVerificationState>();
603
604     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605             new DefaultPermissionGrantPolicy(this);
606
607     private static class IFVerificationParams {
608         PackageParser.Package pkg;
609         boolean replacing;
610         int userId;
611         int verifierUid;
612
613         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614                 int _userId, int _verifierUid) {
615             pkg = _pkg;
616             replacing = _replacing;
617             userId = _userId;
618             replacing = _replacing;
619             verifierUid = _verifierUid;
620         }
621     }
622
623     private interface IntentFilterVerifier<T extends IntentFilter> {
624         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625                                                T filter, String packageName);
626         void startVerifications(int userId);
627         void receiveVerificationResponse(int verificationId);
628     }
629
630     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631         private Context mContext;
632         private ComponentName mIntentFilterVerifierComponent;
633         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
634
635         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
636             mContext = context;
637             mIntentFilterVerifierComponent = verifierComponent;
638         }
639
640         private String getDefaultScheme() {
641             return IntentFilter.SCHEME_HTTPS;
642         }
643
644         @Override
645         public void startVerifications(int userId) {
646             // Launch verifications requests
647             int count = mCurrentIntentFilterVerifications.size();
648             for (int n=0; n<count; n++) {
649                 int verificationId = mCurrentIntentFilterVerifications.get(n);
650                 final IntentFilterVerificationState ivs =
651                         mIntentFilterVerificationStates.get(verificationId);
652
653                 String packageName = ivs.getPackageName();
654
655                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656                 final int filterCount = filters.size();
657                 ArraySet<String> domainsSet = new ArraySet<>();
658                 for (int m=0; m<filterCount; m++) {
659                     PackageParser.ActivityIntentInfo filter = filters.get(m);
660                     domainsSet.addAll(filter.getHostsList());
661                 }
662                 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663                 synchronized (mPackages) {
664                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
665                             packageName, domainsList) != null) {
666                         scheduleWriteSettingsLocked();
667                     }
668                 }
669                 sendVerificationRequest(userId, verificationId, ivs);
670             }
671             mCurrentIntentFilterVerifications.clear();
672         }
673
674         private void sendVerificationRequest(int userId, int verificationId,
675                 IntentFilterVerificationState ivs) {
676
677             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678             verificationIntent.putExtra(
679                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
680                     verificationId);
681             verificationIntent.putExtra(
682                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
683                     getDefaultScheme());
684             verificationIntent.putExtra(
685                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686                     ivs.getHostsString());
687             verificationIntent.putExtra(
688                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689                     ivs.getPackageName());
690             verificationIntent.setComponent(mIntentFilterVerifierComponent);
691             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
692
693             UserHandle user = new UserHandle(userId);
694             mContext.sendBroadcastAsUser(verificationIntent, user);
695             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696                     "Sending IntentFilter verification broadcast");
697         }
698
699         public void receiveVerificationResponse(int verificationId) {
700             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
701
702             final boolean verified = ivs.isVerified();
703
704             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705             final int count = filters.size();
706             if (DEBUG_DOMAIN_VERIFICATION) {
707                 Slog.i(TAG, "Received verification response " + verificationId
708                         + " for " + count + " filters, verified=" + verified);
709             }
710             for (int n=0; n<count; n++) {
711                 PackageParser.ActivityIntentInfo filter = filters.get(n);
712                 filter.setVerified(verified);
713
714                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715                         + " verified with result:" + verified + " and hosts:"
716                         + ivs.getHostsString());
717             }
718
719             mIntentFilterVerificationStates.remove(verificationId);
720
721             final String packageName = ivs.getPackageName();
722             IntentFilterVerificationInfo ivi = null;
723
724             synchronized (mPackages) {
725                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
726             }
727             if (ivi == null) {
728                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729                         + verificationId + " packageName:" + packageName);
730                 return;
731             }
732             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733                     "Updating IntentFilterVerificationInfo for package " + packageName
734                             +" verificationId:" + verificationId);
735
736             synchronized (mPackages) {
737                 if (verified) {
738                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
739                 } else {
740                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
741                 }
742                 scheduleWriteSettingsLocked();
743
744                 final int userId = ivs.getUserId();
745                 if (userId != UserHandle.USER_ALL) {
746                     final int userStatus =
747                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
748
749                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750                     boolean needUpdate = false;
751
752                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753                     // already been set by the User thru the Disambiguation dialog
754                     switch (userStatus) {
755                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
756                             if (verified) {
757                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
758                             } else {
759                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
760                             }
761                             needUpdate = true;
762                             break;
763
764                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
765                             if (verified) {
766                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
767                                 needUpdate = true;
768                             }
769                             break;
770
771                         default:
772                             // Nothing to do
773                     }
774
775                     if (needUpdate) {
776                         mSettings.updateIntentFilterVerificationStatusLPw(
777                                 packageName, updatedStatus, userId);
778                         scheduleWritePackageRestrictionsLocked(userId);
779                     }
780                 }
781             }
782         }
783
784         @Override
785         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786                     ActivityIntentInfo filter, String packageName) {
787             if (!hasValidDomains(filter)) {
788                 return false;
789             }
790             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
791             if (ivs == null) {
792                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
793                         packageName);
794             }
795             if (DEBUG_DOMAIN_VERIFICATION) {
796                 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
797             }
798             ivs.addFilter(filter);
799             return true;
800         }
801
802         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803                 int userId, int verificationId, String packageName) {
804             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805                     verifierUid, userId, packageName);
806             ivs.setPendingState();
807             synchronized (mPackages) {
808                 mIntentFilterVerificationStates.append(verificationId, ivs);
809                 mCurrentIntentFilterVerifications.add(verificationId);
810             }
811             return ivs;
812         }
813     }
814
815     private static boolean hasValidDomains(ActivityIntentInfo filter) {
816         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
819     }
820
821     private IntentFilterVerifier mIntentFilterVerifier;
822
823     // Set of pending broadcasts for aggregating enable/disable of components.
824     static class PendingPackageBroadcasts {
825         // for each user id, a map of <package name -> components within that package>
826         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
827
828         public PendingPackageBroadcasts() {
829             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
830         }
831
832         public ArrayList<String> get(int userId, String packageName) {
833             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834             return packages.get(packageName);
835         }
836
837         public void put(int userId, String packageName, ArrayList<String> components) {
838             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839             packages.put(packageName, components);
840         }
841
842         public void remove(int userId, String packageName) {
843             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844             if (packages != null) {
845                 packages.remove(packageName);
846             }
847         }
848
849         public void remove(int userId) {
850             mUidMap.remove(userId);
851         }
852
853         public int userIdCount() {
854             return mUidMap.size();
855         }
856
857         public int userIdAt(int n) {
858             return mUidMap.keyAt(n);
859         }
860
861         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862             return mUidMap.get(userId);
863         }
864
865         public int size() {
866             // total number of pending broadcast entries across all userIds
867             int num = 0;
868             for (int i = 0; i< mUidMap.size(); i++) {
869                 num += mUidMap.valueAt(i).size();
870             }
871             return num;
872         }
873
874         public void clear() {
875             mUidMap.clear();
876         }
877
878         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
880             if (map == null) {
881                 map = new ArrayMap<String, ArrayList<String>>();
882                 mUidMap.put(userId, map);
883             }
884             return map;
885         }
886     }
887     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
888
889     // Service Connection to remote media container service to copy
890     // package uri's from external media onto secure containers
891     // or internal storage.
892     private IMediaContainerService mContainerService = null;
893
894     static final int SEND_PENDING_BROADCAST = 1;
895     static final int MCS_BOUND = 3;
896     static final int END_COPY = 4;
897     static final int INIT_COPY = 5;
898     static final int MCS_UNBIND = 6;
899     static final int START_CLEANING_PACKAGE = 7;
900     static final int FIND_INSTALL_LOC = 8;
901     static final int POST_INSTALL = 9;
902     static final int MCS_RECONNECT = 10;
903     static final int MCS_GIVE_UP = 11;
904     static final int UPDATED_MEDIA_STATUS = 12;
905     static final int WRITE_SETTINGS = 13;
906     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907     static final int PACKAGE_VERIFIED = 15;
908     static final int CHECK_PENDING_VERIFICATION = 16;
909     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910     static final int INTENT_FILTER_VERIFIED = 18;
911
912     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
913
914     // Delay time in millisecs
915     static final int BROADCAST_DELAY = 10 * 1000;
916
917     static UserManagerService sUserManager;
918
919     // Stores a list of users whose package restrictions file needs to be updated
920     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
921
922     final private DefaultContainerConnection mDefContainerConn =
923             new DefaultContainerConnection();
924     class DefaultContainerConnection implements ServiceConnection {
925         public void onServiceConnected(ComponentName name, IBinder service) {
926             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927             IMediaContainerService imcs =
928                 IMediaContainerService.Stub.asInterface(service);
929             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
930         }
931
932         public void onServiceDisconnected(ComponentName name) {
933             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
934         }
935     }
936
937     // Recordkeeping of restore-after-install operations that are currently in flight
938     // between the Package Manager and the Backup Manager
939     class PostInstallData {
940         public InstallArgs args;
941         public PackageInstalledInfo res;
942
943         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
944             args = _a;
945             res = _r;
946         }
947     }
948
949     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
951
952     // XML tags for backup/restore of various bits of state
953     private static final String TAG_PREFERRED_BACKUP = "pa";
954     private static final String TAG_DEFAULT_APPS = "da";
955     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
956
957     final String mRequiredVerifierPackage;
958     final String mRequiredInstallerPackage;
959
960     private final PackageUsage mPackageUsage = new PackageUsage();
961
962     private class PackageUsage {
963         private static final int WRITE_INTERVAL
964             = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
965
966         private final Object mFileLock = new Object();
967         private final AtomicLong mLastWritten = new AtomicLong(0);
968         private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
969
970         private boolean mIsHistoricalPackageUsageAvailable = true;
971
972         boolean isHistoricalPackageUsageAvailable() {
973             return mIsHistoricalPackageUsageAvailable;
974         }
975
976         void write(boolean force) {
977             if (force) {
978                 writeInternal();
979                 return;
980             }
981             if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
982                 && !DEBUG_DEXOPT) {
983                 return;
984             }
985             if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986                 new Thread("PackageUsage_DiskWriter") {
987                     @Override
988                     public void run() {
989                         try {
990                             writeInternal();
991                         } finally {
992                             mBackgroundWriteRunning.set(false);
993                         }
994                     }
995                 }.start();
996             }
997         }
998
999         private void writeInternal() {
1000             synchronized (mPackages) {
1001                 synchronized (mFileLock) {
1002                     AtomicFile file = getFile();
1003                     FileOutputStream f = null;
1004                     try {
1005                         f = file.startWrite();
1006                         BufferedOutputStream out = new BufferedOutputStream(f);
1007                         FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008                         StringBuilder sb = new StringBuilder();
1009                         for (PackageParser.Package pkg : mPackages.values()) {
1010                             if (pkg.mLastPackageUsageTimeInMills == 0) {
1011                                 continue;
1012                             }
1013                             sb.setLength(0);
1014                             sb.append(pkg.packageName);
1015                             sb.append(' ');
1016                             sb.append((long)pkg.mLastPackageUsageTimeInMills);
1017                             sb.append('\n');
1018                             out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1019                         }
1020                         out.flush();
1021                         file.finishWrite(f);
1022                     } catch (IOException e) {
1023                         if (f != null) {
1024                             file.failWrite(f);
1025                         }
1026                         Log.e(TAG, "Failed to write package usage times", e);
1027                     }
1028                 }
1029             }
1030             mLastWritten.set(SystemClock.elapsedRealtime());
1031         }
1032
1033         void readLP() {
1034             synchronized (mFileLock) {
1035                 AtomicFile file = getFile();
1036                 BufferedInputStream in = null;
1037                 try {
1038                     in = new BufferedInputStream(file.openRead());
1039                     StringBuffer sb = new StringBuffer();
1040                     while (true) {
1041                         String packageName = readToken(in, sb, ' ');
1042                         if (packageName == null) {
1043                             break;
1044                         }
1045                         String timeInMillisString = readToken(in, sb, '\n');
1046                         if (timeInMillisString == null) {
1047                             throw new IOException("Failed to find last usage time for package "
1048                                                   + packageName);
1049                         }
1050                         PackageParser.Package pkg = mPackages.get(packageName);
1051                         if (pkg == null) {
1052                             continue;
1053                         }
1054                         long timeInMillis;
1055                         try {
1056                             timeInMillis = Long.parseLong(timeInMillisString.toString());
1057                         } catch (NumberFormatException e) {
1058                             throw new IOException("Failed to parse " + timeInMillisString
1059                                                   + " as a long.", e);
1060                         }
1061                         pkg.mLastPackageUsageTimeInMills = timeInMillis;
1062                     }
1063                 } catch (FileNotFoundException expected) {
1064                     mIsHistoricalPackageUsageAvailable = false;
1065                 } catch (IOException e) {
1066                     Log.w(TAG, "Failed to read package usage times", e);
1067                 } finally {
1068                     IoUtils.closeQuietly(in);
1069                 }
1070             }
1071             mLastWritten.set(SystemClock.elapsedRealtime());
1072         }
1073
1074         private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075                 throws IOException {
1076             sb.setLength(0);
1077             while (true) {
1078                 int ch = in.read();
1079                 if (ch == -1) {
1080                     if (sb.length() == 0) {
1081                         return null;
1082                     }
1083                     throw new IOException("Unexpected EOF");
1084                 }
1085                 if (ch == endOfToken) {
1086                     return sb.toString();
1087                 }
1088                 sb.append((char)ch);
1089             }
1090         }
1091
1092         private AtomicFile getFile() {
1093             File dataDir = Environment.getDataDirectory();
1094             File systemDir = new File(dataDir, "system");
1095             File fname = new File(systemDir, "package-usage.list");
1096             return new AtomicFile(fname);
1097         }
1098     }
1099
1100     class PackageHandler extends Handler {
1101         private boolean mBound = false;
1102         final ArrayList<HandlerParams> mPendingInstalls =
1103             new ArrayList<HandlerParams>();
1104
1105         private boolean connectToService() {
1106             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107                     " DefaultContainerService");
1108             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111                     Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1112                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                 mBound = true;
1114                 return true;
1115             }
1116             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117             return false;
1118         }
1119
1120         private void disconnectService() {
1121             mContainerService = null;
1122             mBound = false;
1123             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124             mContext.unbindService(mDefContainerConn);
1125             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126         }
1127
1128         PackageHandler(Looper looper) {
1129             super(looper);
1130         }
1131
1132         public void handleMessage(Message msg) {
1133             try {
1134                 doHandleMessage(msg);
1135             } finally {
1136                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137             }
1138         }
1139
1140         void doHandleMessage(Message msg) {
1141             switch (msg.what) {
1142                 case INIT_COPY: {
1143                     HandlerParams params = (HandlerParams) msg.obj;
1144                     int idx = mPendingInstalls.size();
1145                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146                     // If a bind was already initiated we dont really
1147                     // need to do anything. The pending install
1148                     // will be processed later on.
1149                     if (!mBound) {
1150                         // If this is the only one pending we might
1151                         // have to bind to the service again.
1152                         if (!connectToService()) {
1153                             Slog.e(TAG, "Failed to bind to media container service");
1154                             params.serviceError();
1155                             return;
1156                         } else {
1157                             // Once we bind to the service, the first
1158                             // pending request will be processed.
1159                             mPendingInstalls.add(idx, params);
1160                         }
1161                     } else {
1162                         mPendingInstalls.add(idx, params);
1163                         // Already bound to the service. Just make
1164                         // sure we trigger off processing the first request.
1165                         if (idx == 0) {
1166                             mHandler.sendEmptyMessage(MCS_BOUND);
1167                         }
1168                     }
1169                     break;
1170                 }
1171                 case MCS_BOUND: {
1172                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1173                     if (msg.obj != null) {
1174                         mContainerService = (IMediaContainerService) msg.obj;
1175                     }
1176                     if (mContainerService == null) {
1177                         if (!mBound) {
1178                             // Something seriously wrong since we are not bound and we are not
1179                             // waiting for connection. Bail out.
1180                             Slog.e(TAG, "Cannot bind to media container service");
1181                             for (HandlerParams params : mPendingInstalls) {
1182                                 // Indicate service bind error
1183                                 params.serviceError();
1184                             }
1185                             mPendingInstalls.clear();
1186                         } else {
1187                             Slog.w(TAG, "Waiting to connect to media container service");
1188                         }
1189                     } else if (mPendingInstalls.size() > 0) {
1190                         HandlerParams params = mPendingInstalls.get(0);
1191                         if (params != null) {
1192                             if (params.startCopy()) {
1193                                 // We are done...  look for more work or to
1194                                 // go idle.
1195                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1196                                         "Checking for more work or unbind...");
1197                                 // Delete pending install
1198                                 if (mPendingInstalls.size() > 0) {
1199                                     mPendingInstalls.remove(0);
1200                                 }
1201                                 if (mPendingInstalls.size() == 0) {
1202                                     if (mBound) {
1203                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                                 "Posting delayed MCS_UNBIND");
1205                                         removeMessages(MCS_UNBIND);
1206                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1207                                         // Unbind after a little delay, to avoid
1208                                         // continual thrashing.
1209                                         sendMessageDelayed(ubmsg, 10000);
1210                                     }
1211                                 } else {
1212                                     // There are more pending requests in queue.
1213                                     // Just post MCS_BOUND message to trigger processing
1214                                     // of next pending install.
1215                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                             "Posting MCS_BOUND for next work");
1217                                     mHandler.sendEmptyMessage(MCS_BOUND);
1218                                 }
1219                             }
1220                         }
1221                     } else {
1222                         // Should never happen ideally.
1223                         Slog.w(TAG, "Empty queue");
1224                     }
1225                     break;
1226                 }
1227                 case MCS_RECONNECT: {
1228                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1229                     if (mPendingInstalls.size() > 0) {
1230                         if (mBound) {
1231                             disconnectService();
1232                         }
1233                         if (!connectToService()) {
1234                             Slog.e(TAG, "Failed to bind to media container service");
1235                             for (HandlerParams params : mPendingInstalls) {
1236                                 // Indicate service bind error
1237                                 params.serviceError();
1238                             }
1239                             mPendingInstalls.clear();
1240                         }
1241                     }
1242                     break;
1243                 }
1244                 case MCS_UNBIND: {
1245                     // If there is no actual work left, then time to unbind.
1246                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1247
1248                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1249                         if (mBound) {
1250                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1251
1252                             disconnectService();
1253                         }
1254                     } else if (mPendingInstalls.size() > 0) {
1255                         // There are more pending requests in queue.
1256                         // Just post MCS_BOUND message to trigger processing
1257                         // of next pending install.
1258                         mHandler.sendEmptyMessage(MCS_BOUND);
1259                     }
1260
1261                     break;
1262                 }
1263                 case MCS_GIVE_UP: {
1264                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1265                     mPendingInstalls.remove(0);
1266                     break;
1267                 }
1268                 case SEND_PENDING_BROADCAST: {
1269                     String packages[];
1270                     ArrayList<String> components[];
1271                     int size = 0;
1272                     int uids[];
1273                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274                     synchronized (mPackages) {
1275                         if (mPendingBroadcasts == null) {
1276                             return;
1277                         }
1278                         size = mPendingBroadcasts.size();
1279                         if (size <= 0) {
1280                             // Nothing to be done. Just return
1281                             return;
1282                         }
1283                         packages = new String[size];
1284                         components = new ArrayList[size];
1285                         uids = new int[size];
1286                         int i = 0;  // filling out the above arrays
1287
1288                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1289                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1290                             Iterator<Map.Entry<String, ArrayList<String>>> it
1291                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1292                                             .entrySet().iterator();
1293                             while (it.hasNext() && i < size) {
1294                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1295                                 packages[i] = ent.getKey();
1296                                 components[i] = ent.getValue();
1297                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1298                                 uids[i] = (ps != null)
1299                                         ? UserHandle.getUid(packageUserId, ps.appId)
1300                                         : -1;
1301                                 i++;
1302                             }
1303                         }
1304                         size = i;
1305                         mPendingBroadcasts.clear();
1306                     }
1307                     // Send broadcasts
1308                     for (int i = 0; i < size; i++) {
1309                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1310                     }
1311                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1312                     break;
1313                 }
1314                 case START_CLEANING_PACKAGE: {
1315                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316                     final String packageName = (String)msg.obj;
1317                     final int userId = msg.arg1;
1318                     final boolean andCode = msg.arg2 != 0;
1319                     synchronized (mPackages) {
1320                         if (userId == UserHandle.USER_ALL) {
1321                             int[] users = sUserManager.getUserIds();
1322                             for (int user : users) {
1323                                 mSettings.addPackageToCleanLPw(
1324                                         new PackageCleanItem(user, packageName, andCode));
1325                             }
1326                         } else {
1327                             mSettings.addPackageToCleanLPw(
1328                                     new PackageCleanItem(userId, packageName, andCode));
1329                         }
1330                     }
1331                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1332                     startCleaningPackages();
1333                 } break;
1334                 case POST_INSTALL: {
1335                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1336                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1337                     mRunningInstalls.delete(msg.arg1);
1338                     boolean deleteOld = false;
1339
1340                     if (data != null) {
1341                         InstallArgs args = data.args;
1342                         PackageInstalledInfo res = data.res;
1343
1344                         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1345                             final String packageName = res.pkg.applicationInfo.packageName;
1346                             res.removedInfo.sendBroadcast(false, true, false);
1347                             Bundle extras = new Bundle(1);
1348                             extras.putInt(Intent.EXTRA_UID, res.uid);
1349
1350                             // Now that we successfully installed the package, grant runtime
1351                             // permissions if requested before broadcasting the install.
1352                             if ((args.installFlags
1353                                     & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1354                                 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1355                                         args.installGrantPermissions);
1356                             }
1357
1358                             // Determine the set of users who are adding this
1359                             // package for the first time vs. those who are seeing
1360                             // an update.
1361                             int[] firstUsers;
1362                             int[] updateUsers = new int[0];
1363                             if (res.origUsers == null || res.origUsers.length == 0) {
1364                                 firstUsers = res.newUsers;
1365                             } else {
1366                                 firstUsers = new int[0];
1367                                 for (int i=0; i<res.newUsers.length; i++) {
1368                                     int user = res.newUsers[i];
1369                                     boolean isNew = true;
1370                                     for (int j=0; j<res.origUsers.length; j++) {
1371                                         if (res.origUsers[j] == user) {
1372                                             isNew = false;
1373                                             break;
1374                                         }
1375                                     }
1376                                     if (isNew) {
1377                                         int[] newFirst = new int[firstUsers.length+1];
1378                                         System.arraycopy(firstUsers, 0, newFirst, 0,
1379                                                 firstUsers.length);
1380                                         newFirst[firstUsers.length] = user;
1381                                         firstUsers = newFirst;
1382                                     } else {
1383                                         int[] newUpdate = new int[updateUsers.length+1];
1384                                         System.arraycopy(updateUsers, 0, newUpdate, 0,
1385                                                 updateUsers.length);
1386                                         newUpdate[updateUsers.length] = user;
1387                                         updateUsers = newUpdate;
1388                                     }
1389                                 }
1390                             }
1391                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1392                                     packageName, extras, null, null, firstUsers);
1393                             final boolean update = res.removedInfo.removedPackage != null;
1394                             if (update) {
1395                                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1396                             }
1397                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1398                                     packageName, extras, null, null, updateUsers);
1399                             if (update) {
1400                                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1401                                         packageName, extras, null, null, updateUsers);
1402                                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1403                                         null, null, packageName, null, updateUsers);
1404
1405                                 // treat asec-hosted packages like removable media on upgrade
1406                                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1407                                     if (DEBUG_INSTALL) {
1408                                         Slog.i(TAG, "upgrading pkg " + res.pkg
1409                                                 + " is ASEC-hosted -> AVAILABLE");
1410                                     }
1411                                     int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1412                                     ArrayList<String> pkgList = new ArrayList<String>(1);
1413                                     pkgList.add(packageName);
1414                                     sendResourcesChangedBroadcast(true, true,
1415                                             pkgList,uidArray, null);
1416                                 }
1417                             }
1418                             if (res.removedInfo.args != null) {
1419                                 // Remove the replaced package's older resources safely now
1420                                 deleteOld = true;
1421                             }
1422
1423                             // If this app is a browser and it's newly-installed for some
1424                             // users, clear any default-browser state in those users
1425                             if (firstUsers.length > 0) {
1426                                 // the app's nature doesn't depend on the user, so we can just
1427                                 // check its browser nature in any user and generalize.
1428                                 if (packageIsBrowser(packageName, firstUsers[0])) {
1429                                     synchronized (mPackages) {
1430                                         for (int userId : firstUsers) {
1431                                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1432                                         }
1433                                     }
1434                                 }
1435                             }
1436                             // Log current value of "unknown sources" setting
1437                             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1438                                 getUnknownSourcesSettings());
1439                         }
1440                         // Force a gc to clear up things
1441                         Runtime.getRuntime().gc();
1442                         // We delete after a gc for applications  on sdcard.
1443                         if (deleteOld) {
1444                             synchronized (mInstallLock) {
1445                                 res.removedInfo.args.doPostDeleteLI(true);
1446                             }
1447                         }
1448                         if (args.observer != null) {
1449                             try {
1450                                 Bundle extras = extrasForInstallResult(res);
1451                                 args.observer.onPackageInstalled(res.name, res.returnCode,
1452                                         res.returnMsg, extras);
1453                             } catch (RemoteException e) {
1454                                 Slog.i(TAG, "Observer no longer exists.");
1455                             }
1456                         }
1457                     } else {
1458                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1459                     }
1460                 } break;
1461                 case UPDATED_MEDIA_STATUS: {
1462                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1463                     boolean reportStatus = msg.arg1 == 1;
1464                     boolean doGc = msg.arg2 == 1;
1465                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1466                     if (doGc) {
1467                         // Force a gc to clear up stale containers.
1468                         Runtime.getRuntime().gc();
1469                     }
1470                     if (msg.obj != null) {
1471                         @SuppressWarnings("unchecked")
1472                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1473                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1474                         // Unload containers
1475                         unloadAllContainers(args);
1476                     }
1477                     if (reportStatus) {
1478                         try {
1479                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1480                             PackageHelper.getMountService().finishMediaUpdate();
1481                         } catch (RemoteException e) {
1482                             Log.e(TAG, "MountService not running?");
1483                         }
1484                     }
1485                 } break;
1486                 case WRITE_SETTINGS: {
1487                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                     synchronized (mPackages) {
1489                         removeMessages(WRITE_SETTINGS);
1490                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1491                         mSettings.writeLPr();
1492                         mDirtyUsers.clear();
1493                     }
1494                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                 } break;
1496                 case WRITE_PACKAGE_RESTRICTIONS: {
1497                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                     synchronized (mPackages) {
1499                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1500                         for (int userId : mDirtyUsers) {
1501                             mSettings.writePackageRestrictionsLPr(userId);
1502                         }
1503                         mDirtyUsers.clear();
1504                     }
1505                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1506                 } break;
1507                 case CHECK_PENDING_VERIFICATION: {
1508                     final int verificationId = msg.arg1;
1509                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1510
1511                     if ((state != null) && !state.timeoutExtended()) {
1512                         final InstallArgs args = state.getInstallArgs();
1513                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1514
1515                         Slog.i(TAG, "Verification timed out for " + originUri);
1516                         mPendingVerification.remove(verificationId);
1517
1518                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1519
1520                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1521                             Slog.i(TAG, "Continuing with installation of " + originUri);
1522                             state.setVerifierResponse(Binder.getCallingUid(),
1523                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1524                             broadcastPackageVerified(verificationId, originUri,
1525                                     PackageManager.VERIFICATION_ALLOW,
1526                                     state.getInstallArgs().getUser());
1527                             try {
1528                                 ret = args.copyApk(mContainerService, true);
1529                             } catch (RemoteException e) {
1530                                 Slog.e(TAG, "Could not contact the ContainerService");
1531                             }
1532                         } else {
1533                             broadcastPackageVerified(verificationId, originUri,
1534                                     PackageManager.VERIFICATION_REJECT,
1535                                     state.getInstallArgs().getUser());
1536                         }
1537
1538                         processPendingInstall(args, ret);
1539                         mHandler.sendEmptyMessage(MCS_UNBIND);
1540                     }
1541                     break;
1542                 }
1543                 case PACKAGE_VERIFIED: {
1544                     final int verificationId = msg.arg1;
1545
1546                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1547                     if (state == null) {
1548                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1549                         break;
1550                     }
1551
1552                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1553
1554                     state.setVerifierResponse(response.callerUid, response.code);
1555
1556                     if (state.isVerificationComplete()) {
1557                         mPendingVerification.remove(verificationId);
1558
1559                         final InstallArgs args = state.getInstallArgs();
1560                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1561
1562                         int ret;
1563                         if (state.isInstallAllowed()) {
1564                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565                             broadcastPackageVerified(verificationId, originUri,
1566                                     response.code, state.getInstallArgs().getUser());
1567                             try {
1568                                 ret = args.copyApk(mContainerService, true);
1569                             } catch (RemoteException e) {
1570                                 Slog.e(TAG, "Could not contact the ContainerService");
1571                             }
1572                         } else {
1573                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1574                         }
1575
1576                         processPendingInstall(args, ret);
1577
1578                         mHandler.sendEmptyMessage(MCS_UNBIND);
1579                     }
1580
1581                     break;
1582                 }
1583                 case START_INTENT_FILTER_VERIFICATIONS: {
1584                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1585                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1586                             params.replacing, params.pkg);
1587                     break;
1588                 }
1589                 case INTENT_FILTER_VERIFIED: {
1590                     final int verificationId = msg.arg1;
1591
1592                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1593                             verificationId);
1594                     if (state == null) {
1595                         Slog.w(TAG, "Invalid IntentFilter verification token "
1596                                 + verificationId + " received");
1597                         break;
1598                     }
1599
1600                     final int userId = state.getUserId();
1601
1602                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1603                             "Processing IntentFilter verification with token:"
1604                             + verificationId + " and userId:" + userId);
1605
1606                     final IntentFilterVerificationResponse response =
1607                             (IntentFilterVerificationResponse) msg.obj;
1608
1609                     state.setVerifierResponse(response.callerUid, response.code);
1610
1611                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                             "IntentFilter verification with token:" + verificationId
1613                             + " and userId:" + userId
1614                             + " is settings verifier response with response code:"
1615                             + response.code);
1616
1617                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1618                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1619                                 + response.getFailedDomainsString());
1620                     }
1621
1622                     if (state.isVerificationComplete()) {
1623                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1624                     } else {
1625                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1626                                 "IntentFilter verification with token:" + verificationId
1627                                 + " was not said to be complete");
1628                     }
1629
1630                     break;
1631                 }
1632             }
1633         }
1634     }
1635
1636     private StorageEventListener mStorageListener = new StorageEventListener() {
1637         @Override
1638         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1639             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1640                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1641                     final String volumeUuid = vol.getFsUuid();
1642
1643                     // Clean up any users or apps that were removed or recreated
1644                     // while this volume was missing
1645                     reconcileUsers(volumeUuid);
1646                     reconcileApps(volumeUuid);
1647
1648                     // Clean up any install sessions that expired or were
1649                     // cancelled while this volume was missing
1650                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
1651
1652                     loadPrivatePackages(vol);
1653
1654                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1655                     unloadPrivatePackages(vol);
1656                 }
1657             }
1658
1659             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1660                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1661                     updateExternalMediaStatus(true, false);
1662                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1663                     updateExternalMediaStatus(false, false);
1664                 }
1665             }
1666         }
1667
1668         @Override
1669         public void onVolumeForgotten(String fsUuid) {
1670             if (TextUtils.isEmpty(fsUuid)) {
1671                 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1672                 return;
1673             }
1674
1675             // Remove any apps installed on the forgotten volume
1676             synchronized (mPackages) {
1677                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1678                 for (PackageSetting ps : packages) {
1679                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1680                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1681                             UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1682                 }
1683
1684                 mSettings.onVolumeForgotten(fsUuid);
1685                 mSettings.writeLPr();
1686             }
1687         }
1688     };
1689
1690     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1691             String[] grantedPermissions) {
1692         if (userId >= UserHandle.USER_OWNER) {
1693             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1694         } else if (userId == UserHandle.USER_ALL) {
1695             final int[] userIds;
1696             synchronized (mPackages) {
1697                 userIds = UserManagerService.getInstance().getUserIds();
1698             }
1699             for (int someUserId : userIds) {
1700                 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1701             }
1702         }
1703
1704         // We could have touched GID membership, so flush out packages.list
1705         synchronized (mPackages) {
1706             mSettings.writePackageListLPr();
1707         }
1708     }
1709
1710     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1711             String[] grantedPermissions) {
1712         SettingBase sb = (SettingBase) pkg.mExtras;
1713         if (sb == null) {
1714             return;
1715         }
1716
1717         PermissionsState permissionsState = sb.getPermissionsState();
1718
1719         for (String permission : pkg.requestedPermissions) {
1720             BasePermission bp = mSettings.mPermissions.get(permission);
1721             if (bp != null && bp.isRuntime() && (grantedPermissions == null
1722                     || ArrayUtils.contains(grantedPermissions, permission))) {
1723                 permissionsState.grantRuntimePermission(bp, userId);
1724             }
1725         }
1726     }
1727
1728     Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729         Bundle extras = null;
1730         switch (res.returnCode) {
1731             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732                 extras = new Bundle();
1733                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734                         res.origPermission);
1735                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1736                         res.origPackage);
1737                 break;
1738             }
1739             case PackageManager.INSTALL_SUCCEEDED: {
1740                 extras = new Bundle();
1741                 extras.putBoolean(Intent.EXTRA_REPLACING,
1742                         res.removedInfo != null && res.removedInfo.removedPackage != null);
1743                 break;
1744             }
1745         }
1746         return extras;
1747     }
1748
1749     void scheduleWriteSettingsLocked() {
1750         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1752         }
1753     }
1754
1755     void scheduleWritePackageRestrictionsLocked(int userId) {
1756         if (!sUserManager.exists(userId)) return;
1757         mDirtyUsers.add(userId);
1758         if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759             mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1760         }
1761     }
1762
1763     public static PackageManagerService main(Context context, Installer installer,
1764             boolean factoryTest, boolean onlyCore) {
1765         PackageManagerService m = new PackageManagerService(context, installer,
1766                 factoryTest, onlyCore);
1767         ServiceManager.addService("package", m);
1768         return m;
1769     }
1770
1771     static String[] splitString(String str, char sep) {
1772         int count = 1;
1773         int i = 0;
1774         while ((i=str.indexOf(sep, i)) >= 0) {
1775             count++;
1776             i++;
1777         }
1778
1779         String[] res = new String[count];
1780         i=0;
1781         count = 0;
1782         int lastI=0;
1783         while ((i=str.indexOf(sep, i)) >= 0) {
1784             res[count] = str.substring(lastI, i);
1785             count++;
1786             i++;
1787             lastI = i;
1788         }
1789         res[count] = str.substring(lastI, str.length());
1790         return res;
1791     }
1792
1793     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794         DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795                 Context.DISPLAY_SERVICE);
1796         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1797     }
1798
1799     public PackageManagerService(Context context, Installer installer,
1800             boolean factoryTest, boolean onlyCore) {
1801         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802                 SystemClock.uptimeMillis());
1803
1804         if (mSdkVersion <= 0) {
1805             Slog.w(TAG, "**** ro.build.version.sdk not set!");
1806         }
1807
1808         mContext = context;
1809         mFactoryTest = factoryTest;
1810         mOnlyCore = onlyCore;
1811         mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812         mMetrics = new DisplayMetrics();
1813         mSettings = new Settings(mPackages);
1814         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1826
1827         // TODO: add a property to control this?
1828         long dexOptLRUThresholdInMinutes;
1829         if (mLazyDexOpt) {
1830             dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1831         } else {
1832             dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1833         }
1834         mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1835
1836         String separateProcesses = SystemProperties.get("debug.separate_processes");
1837         if (separateProcesses != null && separateProcesses.length() > 0) {
1838             if ("*".equals(separateProcesses)) {
1839                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840                 mSeparateProcesses = null;
1841                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1842             } else {
1843                 mDefParseFlags = 0;
1844                 mSeparateProcesses = separateProcesses.split(",");
1845                 Slog.w(TAG, "Running with debug.separate_processes: "
1846                         + separateProcesses);
1847             }
1848         } else {
1849             mDefParseFlags = 0;
1850             mSeparateProcesses = null;
1851         }
1852
1853         mInstaller = installer;
1854         mPackageDexOptimizer = new PackageDexOptimizer(this);
1855         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1856
1857         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858                 FgThread.get().getLooper());
1859
1860         getDefaultDisplayMetrics(context, mMetrics);
1861
1862         SystemConfig systemConfig = SystemConfig.getInstance();
1863         mGlobalGids = systemConfig.getGlobalGids();
1864         mSystemPermissions = systemConfig.getSystemPermissions();
1865         mAvailableFeatures = systemConfig.getAvailableFeatures();
1866
1867         synchronized (mInstallLock) {
1868         // writer
1869         synchronized (mPackages) {
1870             mHandlerThread = new ServiceThread(TAG,
1871                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872             mHandlerThread.start();
1873             mHandler = new PackageHandler(mHandlerThread.getLooper());
1874             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1875
1876             File dataDir = Environment.getDataDirectory();
1877             mAppDataDir = new File(dataDir, "data");
1878             mAppInstallDir = new File(dataDir, "app");
1879             mAppLib32InstallDir = new File(dataDir, "app-lib");
1880             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881             mUserAppDataDir = new File(dataDir, "user");
1882             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1883
1884             sUserManager = new UserManagerService(context, this,
1885                     mInstallLock, mPackages);
1886
1887             // Propagate permission configuration in to package manager.
1888             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889                     = systemConfig.getPermissions();
1890             for (int i=0; i<permConfig.size(); i++) {
1891                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892                 BasePermission bp = mSettings.mPermissions.get(perm.name);
1893                 if (bp == null) {
1894                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895                     mSettings.mPermissions.put(perm.name, bp);
1896                 }
1897                 if (perm.gids != null) {
1898                     bp.setGids(perm.gids, perm.perUser);
1899                 }
1900             }
1901
1902             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903             for (int i=0; i<libConfig.size(); i++) {
1904                 mSharedLibraries.put(libConfig.keyAt(i),
1905                         new SharedLibraryEntry(libConfig.valueAt(i), null));
1906             }
1907
1908             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1909
1910             mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911                     mSdkVersion, mOnlyCore);
1912
1913             String customResolverActivity = Resources.getSystem().getString(
1914                     R.string.config_customResolverActivity);
1915             if (TextUtils.isEmpty(customResolverActivity)) {
1916                 customResolverActivity = null;
1917             } else {
1918                 mCustomResolverComponentName = ComponentName.unflattenFromString(
1919                         customResolverActivity);
1920             }
1921
1922             long startTime = SystemClock.uptimeMillis();
1923
1924             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1925                     startTime);
1926
1927             // Set flag to monitor and not change apk file paths when
1928             // scanning install directories.
1929             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1930
1931             final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1932
1933             /**
1934              * Add everything in the in the boot class path to the
1935              * list of process files because dexopt will have been run
1936              * if necessary during zygote startup.
1937              */
1938             final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1940
1941             if (bootClassPath != null) {
1942                 String[] bootClassPathElements = splitString(bootClassPath, ':');
1943                 for (String element : bootClassPathElements) {
1944                     alreadyDexOpted.add(element);
1945                 }
1946             } else {
1947                 Slog.w(TAG, "No BOOTCLASSPATH found!");
1948             }
1949
1950             if (systemServerClassPath != null) {
1951                 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952                 for (String element : systemServerClassPathElements) {
1953                     alreadyDexOpted.add(element);
1954                 }
1955             } else {
1956                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1957             }
1958
1959             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960             final String[] dexCodeInstructionSets =
1961                     getDexCodeInstructionSets(
1962                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
1963
1964             /**
1965              * Ensure all external libraries have had dexopt run on them.
1966              */
1967             if (mSharedLibraries.size() > 0) {
1968                 // NOTE: For now, we're compiling these system "shared libraries"
1969                 // (and framework jars) into all available architectures. It's possible
1970                 // to compile them only when we come across an app that uses them (there's
1971                 // already logic for that in scanPackageLI) but that adds some complexity.
1972                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974                         final String lib = libEntry.path;
1975                         if (lib == null) {
1976                             continue;
1977                         }
1978
1979                         try {
1980                             int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982                                 alreadyDexOpted.add(lib);
1983                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1984                             }
1985                         } catch (FileNotFoundException e) {
1986                             Slog.w(TAG, "Library not found: " + lib);
1987                         } catch (IOException e) {
1988                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1989                                     + e.getMessage());
1990                         }
1991                     }
1992                 }
1993             }
1994
1995             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1996
1997             // Gross hack for now: we know this file doesn't contain any
1998             // code, so don't dexopt it to avoid the resulting log spew.
1999             alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2000
2001             // Gross hack for now: we know this file is only part of
2002             // the boot class path for art, so don't dexopt it to
2003             // avoid the resulting log spew.
2004             alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2005
2006             /**
2007              * There are a number of commands implemented in Java, which
2008              * we currently need to do the dexopt on so that they can be
2009              * run from a non-root shell.
2010              */
2011             String[] frameworkFiles = frameworkDir.list();
2012             if (frameworkFiles != null) {
2013                 // TODO: We could compile these only for the most preferred ABI. We should
2014                 // first double check that the dex files for these commands are not referenced
2015                 // by other system apps.
2016                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2017                     for (int i=0; i<frameworkFiles.length; i++) {
2018                         File libPath = new File(frameworkDir, frameworkFiles[i]);
2019                         String path = libPath.getPath();
2020                         // Skip the file if we already did it.
2021                         if (alreadyDexOpted.contains(path)) {
2022                             continue;
2023                         }
2024                         // Skip the file if it is not a type we want to dexopt.
2025                         if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2026                             continue;
2027                         }
2028                         try {
2029                             int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2030                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2031                                 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2032                             }
2033                         } catch (FileNotFoundException e) {
2034                             Slog.w(TAG, "Jar not found: " + path);
2035                         } catch (IOException e) {
2036                             Slog.w(TAG, "Exception reading jar: " + path, e);
2037                         }
2038                     }
2039                 }
2040             }
2041
2042             final VersionInfo ver = mSettings.getInternalVersion();
2043             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2044             // when upgrading from pre-M, promote system app permissions from install to runtime
2045             mPromoteSystemApps =
2046                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2047
2048             // save off the names of pre-existing system packages prior to scanning; we don't
2049             // want to automatically grant runtime permissions for new system apps
2050             if (mPromoteSystemApps) {
2051                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2052                 while (pkgSettingIter.hasNext()) {
2053                     PackageSetting ps = pkgSettingIter.next();
2054                     if (isSystemApp(ps)) {
2055                         mExistingSystemPackages.add(ps.name);
2056                     }
2057                 }
2058             }
2059
2060             // Collect vendor overlay packages.
2061             // (Do this before scanning any apps.)
2062             // For security and version matching reason, only consider
2063             // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2064             File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2065             scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2066                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2067
2068             // Find base frameworks (resource packages without code).
2069             scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2070                     | PackageParser.PARSE_IS_SYSTEM_DIR
2071                     | PackageParser.PARSE_IS_PRIVILEGED,
2072                     scanFlags | SCAN_NO_DEX, 0);
2073
2074             // Collected privileged system packages.
2075             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2076             scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2077                     | PackageParser.PARSE_IS_SYSTEM_DIR
2078                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2079
2080             // Collect ordinary system packages.
2081             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2082             scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2083                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2084
2085             // Collect all vendor packages.
2086             File vendorAppDir = new File("/vendor/app");
2087             try {
2088                 vendorAppDir = vendorAppDir.getCanonicalFile();
2089             } catch (IOException e) {
2090                 // failed to look up canonical path, continue with original one
2091             }
2092             scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2093                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2094
2095             // Collect all OEM packages.
2096             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2097             scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2098                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2099
2100             if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2101             mInstaller.moveFiles();
2102
2103             // Prune any system packages that no longer exist.
2104             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2105             if (!mOnlyCore) {
2106                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2107                 while (psit.hasNext()) {
2108                     PackageSetting ps = psit.next();
2109
2110                     /*
2111                      * If this is not a system app, it can't be a
2112                      * disable system app.
2113                      */
2114                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2115                         continue;
2116                     }
2117
2118                     /*
2119                      * If the package is scanned, it's not erased.
2120                      */
2121                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2122                     if (scannedPkg != null) {
2123                         /*
2124                          * If the system app is both scanned and in the
2125                          * disabled packages list, then it must have been
2126                          * added via OTA. Remove it from the currently
2127                          * scanned package so the previously user-installed
2128                          * application can be scanned.
2129                          */
2130                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2131                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2132                                     + ps.name + "; removing system app.  Last known codePath="
2133                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2134                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2135                                     + scannedPkg.mVersionCode);
2136                             removePackageLI(ps, true);
2137                             mExpectingBetter.put(ps.name, ps.codePath);
2138                         }
2139
2140                         continue;
2141                     }
2142
2143                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2144                         psit.remove();
2145                         logCriticalInfo(Log.WARN, "System package " + ps.name
2146                                 + " no longer exists; wiping its data");
2147                         removeDataDirsLI(null, ps.name);
2148                     } else {
2149                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2150                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2151                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2152                         }
2153                     }
2154                 }
2155             }
2156
2157             //look for any incomplete package installations
2158             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2159             //clean up list
2160             for(int i = 0; i < deletePkgsList.size(); i++) {
2161                 //clean up here
2162                 cleanupInstallFailedPackage(deletePkgsList.get(i));
2163             }
2164             //delete tmp files
2165             deleteTempPackageFiles();
2166
2167             // Remove any shared userIDs that have no associated packages
2168             mSettings.pruneSharedUsersLPw();
2169
2170             if (!mOnlyCore) {
2171                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2172                         SystemClock.uptimeMillis());
2173                 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2174
2175                 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2176                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2177
2178                 /**
2179                  * Remove disable package settings for any updated system
2180                  * apps that were removed via an OTA. If they're not a
2181                  * previously-updated app, remove them completely.
2182                  * Otherwise, just revoke their system-level permissions.
2183                  */
2184                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2185                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2186                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2187
2188                     String msg;
2189                     if (deletedPkg == null) {
2190                         msg = "Updated system package " + deletedAppName
2191                                 + " no longer exists; wiping its data";
2192                         removeDataDirsLI(null, deletedAppName);
2193                     } else {
2194                         msg = "Updated system app + " + deletedAppName
2195                                 + " no longer present; removing system privileges for "
2196                                 + deletedAppName;
2197
2198                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2199
2200                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2201                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2202                     }
2203                     logCriticalInfo(Log.WARN, msg);
2204                 }
2205
2206                 /**
2207                  * Make sure all system apps that we expected to appear on
2208                  * the userdata partition actually showed up. If they never
2209                  * appeared, crawl back and revive the system version.
2210                  */
2211                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2212                     final String packageName = mExpectingBetter.keyAt(i);
2213                     if (!mPackages.containsKey(packageName)) {
2214                         final File scanFile = mExpectingBetter.valueAt(i);
2215
2216                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2217                                 + " but never showed up; reverting to system");
2218
2219                         final int reparseFlags;
2220                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2221                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2222                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2223                                     | PackageParser.PARSE_IS_PRIVILEGED;
2224                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2225                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2226                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2227                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2228                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2229                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2230                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2231                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2232                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2233                         } else {
2234                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2235                             continue;
2236                         }
2237
2238                         mSettings.enableSystemPackageLPw(packageName);
2239
2240                         try {
2241                             scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2242                         } catch (PackageManagerException e) {
2243                             Slog.e(TAG, "Failed to parse original system package: "
2244                                     + e.getMessage());
2245                         }
2246                     }
2247                 }
2248             }
2249             mExpectingBetter.clear();
2250
2251             // Now that we know all of the shared libraries, update all clients to have
2252             // the correct library paths.
2253             updateAllSharedLibrariesLPw();
2254
2255             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2256                 // NOTE: We ignore potential failures here during a system scan (like
2257                 // the rest of the commands above) because there's precious little we
2258                 // can do about it. A settings error is reported, though.
2259                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2260                         false /* force dexopt */, false /* defer dexopt */);
2261             }
2262
2263             // Now that we know all the packages we are keeping,
2264             // read and update their last usage times.
2265             mPackageUsage.readLP();
2266
2267             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2268                     SystemClock.uptimeMillis());
2269             Slog.i(TAG, "Time to scan packages: "
2270                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2271                     + " seconds");
2272
2273             // If the platform SDK has changed since the last time we booted,
2274             // we need to re-grant app permission to catch any new ones that
2275             // appear.  This is really a hack, and means that apps can in some
2276             // cases get permissions that the user didn't initially explicitly
2277             // allow...  it would be nice to have some better way to handle
2278             // this situation.
2279             int updateFlags = UPDATE_PERMISSIONS_ALL;
2280             if (ver.sdkVersion != mSdkVersion) {
2281                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2282                         + mSdkVersion + "; regranting permissions for internal storage");
2283                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2284             }
2285             updatePermissionsLPw(null, null, updateFlags);
2286             ver.sdkVersion = mSdkVersion;
2287
2288             // If this is the first boot or an update from pre-M, and it is a normal
2289             // boot, then we need to initialize the default preferred apps across
2290             // all defined users.
2291             if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2292                 for (UserInfo user : sUserManager.getUsers(true)) {
2293                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2294                     applyFactoryDefaultBrowserLPw(user.id);
2295                     primeDomainVerificationsLPw(user.id);
2296                 }
2297             }
2298
2299             // If this is first boot after an OTA, and a normal boot, then
2300             // we need to clear code cache directories.
2301             if (mIsUpgrade && !onlyCore) {
2302                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2303                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2304                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2305                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2306                         deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2307                     }
2308                 }
2309                 ver.fingerprint = Build.FINGERPRINT;
2310             }
2311
2312             checkDefaultBrowser();
2313
2314             // clear only after permissions and other defaults have been updated
2315             mExistingSystemPackages.clear();
2316             mPromoteSystemApps = false;
2317
2318             // All the changes are done during package scanning.
2319             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2320
2321             // can downgrade to reader
2322             mSettings.writeLPr();
2323
2324             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2325                     SystemClock.uptimeMillis());
2326
2327             mRequiredVerifierPackage = getRequiredVerifierLPr();
2328             mRequiredInstallerPackage = getRequiredInstallerLPr();
2329
2330             mInstallerService = new PackageInstallerService(context, this);
2331
2332             mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2333             mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2334                     mIntentFilterVerifierComponent);
2335
2336         } // synchronized (mPackages)
2337         } // synchronized (mInstallLock)
2338
2339         // Now after opening every single application zip, make sure they
2340         // are all flushed.  Not really needed, but keeps things nice and
2341         // tidy.
2342         Runtime.getRuntime().gc();
2343
2344         // Expose private service for system components to use.
2345         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2346     }
2347
2348     @Override
2349     public boolean isFirstBoot() {
2350         return !mRestoredSettings;
2351     }
2352
2353     @Override
2354     public boolean isOnlyCoreApps() {
2355         return mOnlyCore;
2356     }
2357
2358     @Override
2359     public boolean isUpgrade() {
2360         return mIsUpgrade;
2361     }
2362
2363     private String getRequiredVerifierLPr() {
2364         final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2365         final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2366                 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2367
2368         String requiredVerifier = null;
2369
2370         final int N = receivers.size();
2371         for (int i = 0; i < N; i++) {
2372             final ResolveInfo info = receivers.get(i);
2373
2374             if (info.activityInfo == null) {
2375                 continue;
2376             }
2377
2378             final String packageName = info.activityInfo.packageName;
2379
2380             if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2381                     packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2382                 continue;
2383             }
2384
2385             if (requiredVerifier != null) {
2386                 throw new RuntimeException("There can be only one required verifier");
2387             }
2388
2389             requiredVerifier = packageName;
2390         }
2391
2392         return requiredVerifier;
2393     }
2394
2395     private String getRequiredInstallerLPr() {
2396         Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2397         installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2398         installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2399
2400         final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2401                 PACKAGE_MIME_TYPE, 0, 0);
2402
2403         String requiredInstaller = null;
2404
2405         final int N = installers.size();
2406         for (int i = 0; i < N; i++) {
2407             final ResolveInfo info = installers.get(i);
2408             final String packageName = info.activityInfo.packageName;
2409
2410             if (!info.activityInfo.applicationInfo.isSystemApp()) {
2411                 continue;
2412             }
2413
2414             if (requiredInstaller != null) {
2415                 throw new RuntimeException("There must be one required installer");
2416             }
2417
2418             requiredInstaller = packageName;
2419         }
2420
2421         if (requiredInstaller == null) {
2422             throw new RuntimeException("There must be one required installer");
2423         }
2424
2425         return requiredInstaller;
2426     }
2427
2428     private ComponentName getIntentFilterVerifierComponentNameLPr() {
2429         final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2430         final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2431                 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2432
2433         ComponentName verifierComponentName = null;
2434
2435         int priority = -1000;
2436         final int N = receivers.size();
2437         for (int i = 0; i < N; i++) {
2438             final ResolveInfo info = receivers.get(i);
2439
2440             if (info.activityInfo == null) {
2441                 continue;
2442             }
2443
2444             final String packageName = info.activityInfo.packageName;
2445
2446             final PackageSetting ps = mSettings.mPackages.get(packageName);
2447             if (ps == null) {
2448                 continue;
2449             }
2450
2451             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2452                     packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2453                 continue;
2454             }
2455
2456             // Select the IntentFilterVerifier with the highest priority
2457             if (priority < info.priority) {
2458                 priority = info.priority;
2459                 verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2460                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2461                         + verifierComponentName + " with priority: " + info.priority);
2462             }
2463         }
2464
2465         return verifierComponentName;
2466     }
2467
2468     private void primeDomainVerificationsLPw(int userId) {
2469         if (DEBUG_DOMAIN_VERIFICATION) {
2470             Slog.d(TAG, "Priming domain verifications in user " + userId);
2471         }
2472
2473         SystemConfig systemConfig = SystemConfig.getInstance();
2474         ArraySet<String> packages = systemConfig.getLinkedApps();
2475         ArraySet<String> domains = new ArraySet<String>();
2476
2477         for (String packageName : packages) {
2478             PackageParser.Package pkg = mPackages.get(packageName);
2479             if (pkg != null) {
2480                 if (!pkg.isSystemApp()) {
2481                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2482                     continue;
2483                 }
2484
2485                 domains.clear();
2486                 for (PackageParser.Activity a : pkg.activities) {
2487                     for (ActivityIntentInfo filter : a.intents) {
2488                         if (hasValidDomains(filter)) {
2489                             domains.addAll(filter.getHostsList());
2490                         }
2491                     }
2492                 }
2493
2494                 if (domains.size() > 0) {
2495                     if (DEBUG_DOMAIN_VERIFICATION) {
2496                         Slog.v(TAG, "      + " + packageName);
2497                     }
2498                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2499                     // state w.r.t. the formal app-linkage "no verification attempted" state;
2500                     // and then 'always' in the per-user state actually used for intent resolution.
2501                     final IntentFilterVerificationInfo ivi;
2502                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2503                             new ArrayList<String>(domains));
2504                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2505                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2506                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2507                 } else {
2508                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2509                             + "' does not handle web links");
2510                 }
2511             } else {
2512                 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2513             }
2514         }
2515
2516         scheduleWritePackageRestrictionsLocked(userId);
2517         scheduleWriteSettingsLocked();
2518     }
2519
2520     private void applyFactoryDefaultBrowserLPw(int userId) {
2521         // The default browser app's package name is stored in a string resource,
2522         // with a product-specific overlay used for vendor customization.
2523         String browserPkg = mContext.getResources().getString(
2524                 com.android.internal.R.string.default_browser);
2525         if (!TextUtils.isEmpty(browserPkg)) {
2526             // non-empty string => required to be a known package
2527             PackageSetting ps = mSettings.mPackages.get(browserPkg);
2528             if (ps == null) {
2529                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2530                 browserPkg = null;
2531             } else {
2532                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2533             }
2534         }
2535
2536         // Nothing valid explicitly set? Make the factory-installed browser the explicit
2537         // default.  If there's more than one, just leave everything alone.
2538         if (browserPkg == null) {
2539             calculateDefaultBrowserLPw(userId);
2540         }
2541     }
2542
2543     private void calculateDefaultBrowserLPw(int userId) {
2544         List<String> allBrowsers = resolveAllBrowserApps(userId);
2545         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2546         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2547     }
2548
2549     private List<String> resolveAllBrowserApps(int userId) {
2550         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2551         List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2552                 PackageManager.MATCH_ALL, userId);
2553
2554         final int count = list.size();
2555         List<String> result = new ArrayList<String>(count);
2556         for (int i=0; i<count; i++) {
2557             ResolveInfo info = list.get(i);
2558             if (info.activityInfo == null
2559                     || !info.handleAllWebDataURI
2560                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2561                     || result.contains(info.activityInfo.packageName)) {
2562                 continue;
2563             }
2564             result.add(info.activityInfo.packageName);
2565         }
2566
2567         return result;
2568     }
2569
2570     private boolean packageIsBrowser(String packageName, int userId) {
2571         List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2572                 PackageManager.MATCH_ALL, userId);
2573         final int N = list.size();
2574         for (int i = 0; i < N; i++) {
2575             ResolveInfo info = list.get(i);
2576             if (packageName.equals(info.activityInfo.packageName)) {
2577                 return true;
2578             }
2579         }
2580         return false;
2581     }
2582
2583     private void checkDefaultBrowser() {
2584         final int myUserId = UserHandle.myUserId();
2585         final String packageName = getDefaultBrowserPackageName(myUserId);
2586         if (packageName != null) {
2587             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2588             if (info == null) {
2589                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
2590                 synchronized (mPackages) {
2591                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2592                 }
2593             }
2594         }
2595     }
2596
2597     @Override
2598     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2599             throws RemoteException {
2600         try {
2601             return super.onTransact(code, data, reply, flags);
2602         } catch (RuntimeException e) {
2603             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2604                 Slog.wtf(TAG, "Package Manager Crash", e);
2605             }
2606             throw e;
2607         }
2608     }
2609
2610     void cleanupInstallFailedPackage(PackageSetting ps) {
2611         logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2612
2613         removeDataDirsLI(ps.volumeUuid, ps.name);
2614         if (ps.codePath != null) {
2615             if (ps.codePath.isDirectory()) {
2616                 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2617             } else {
2618                 ps.codePath.delete();
2619             }
2620         }
2621         if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2622             if (ps.resourcePath.isDirectory()) {
2623                 FileUtils.deleteContents(ps.resourcePath);
2624             }
2625             ps.resourcePath.delete();
2626         }
2627         mSettings.removePackageLPw(ps.name);
2628     }
2629
2630     static int[] appendInts(int[] cur, int[] add) {
2631         if (add == null) return cur;
2632         if (cur == null) return add;
2633         final int N = add.length;
2634         for (int i=0; i<N; i++) {
2635             cur = appendInt(cur, add[i]);
2636         }
2637         return cur;
2638     }
2639
2640     PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2641         if (!sUserManager.exists(userId)) return null;
2642         final PackageSetting ps = (PackageSetting) p.mExtras;
2643         if (ps == null) {
2644             return null;
2645         }
2646
2647         final PermissionsState permissionsState = ps.getPermissionsState();
2648
2649         final int[] gids = permissionsState.computeGids(userId);
2650         final Set<String> permissions = permissionsState.getPermissions(userId);
2651         final PackageUserState state = ps.readUserState(userId);
2652
2653         return PackageParser.generatePackageInfo(p, gids, flags,
2654                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2655     }
2656
2657     @Override
2658     public boolean isPackageFrozen(String packageName) {
2659         synchronized (mPackages) {
2660             final PackageSetting ps = mSettings.mPackages.get(packageName);
2661             if (ps != null) {
2662                 return ps.frozen;
2663             }
2664         }
2665         Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2666         return true;
2667     }
2668
2669     @Override
2670     public boolean isPackageAvailable(String packageName, int userId) {
2671         if (!sUserManager.exists(userId)) return false;
2672         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2673         synchronized (mPackages) {
2674             PackageParser.Package p = mPackages.get(packageName);
2675             if (p != null) {
2676                 final PackageSetting ps = (PackageSetting) p.mExtras;
2677                 if (ps != null) {
2678                     final PackageUserState state = ps.readUserState(userId);
2679                     if (state != null) {
2680                         return PackageParser.isAvailable(state);
2681                     }
2682                 }
2683             }
2684         }
2685         return false;
2686     }
2687
2688     @Override
2689     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2690         if (!sUserManager.exists(userId)) return null;
2691         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2692         // reader
2693         synchronized (mPackages) {
2694             PackageParser.Package p = mPackages.get(packageName);
2695             if (DEBUG_PACKAGE_INFO)
2696                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2697             if (p != null) {
2698                 return generatePackageInfo(p, flags, userId);
2699             }
2700             if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2701                 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2702             }
2703         }
2704         return null;
2705     }
2706
2707     @Override
2708     public String[] currentToCanonicalPackageNames(String[] names) {
2709         String[] out = new String[names.length];
2710         // reader
2711         synchronized (mPackages) {
2712             for (int i=names.length-1; i>=0; i--) {
2713                 PackageSetting ps = mSettings.mPackages.get(names[i]);
2714                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2715             }
2716         }
2717         return out;
2718     }
2719
2720     @Override
2721     public String[] canonicalToCurrentPackageNames(String[] names) {
2722         String[] out = new String[names.length];
2723         // reader
2724         synchronized (mPackages) {
2725             for (int i=names.length-1; i>=0; i--) {
2726                 String cur = mSettings.mRenamedPackages.get(names[i]);
2727                 out[i] = cur != null ? cur : names[i];
2728             }
2729         }
2730         return out;
2731     }
2732
2733     @Override
2734     public int getPackageUid(String packageName, int userId) {
2735         if (!sUserManager.exists(userId)) return -1;
2736         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2737
2738         // reader
2739         synchronized (mPackages) {
2740             PackageParser.Package p = mPackages.get(packageName);
2741             if(p != null) {
2742                 return UserHandle.getUid(userId, p.applicationInfo.uid);
2743             }
2744             PackageSetting ps = mSettings.mPackages.get(packageName);
2745             if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2746                 return -1;
2747             }
2748             p = ps.pkg;
2749             return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2750         }
2751     }
2752
2753     @Override
2754     public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2755         if (!sUserManager.exists(userId)) {
2756             return null;
2757         }
2758
2759         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2760                 "getPackageGids");
2761
2762         // reader
2763         synchronized (mPackages) {
2764             PackageParser.Package p = mPackages.get(packageName);
2765             if (DEBUG_PACKAGE_INFO) {
2766                 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2767             }
2768             if (p != null) {
2769                 PackageSetting ps = (PackageSetting) p.mExtras;
2770                 return ps.getPermissionsState().computeGids(userId);
2771             }
2772         }
2773
2774         return null;
2775     }
2776
2777     static PermissionInfo generatePermissionInfo(
2778             BasePermission bp, int flags) {
2779         if (bp.perm != null) {
2780             return PackageParser.generatePermissionInfo(bp.perm, flags);
2781         }
2782         PermissionInfo pi = new PermissionInfo();
2783         pi.name = bp.name;
2784         pi.packageName = bp.sourcePackage;
2785         pi.nonLocalizedLabel = bp.name;
2786         pi.protectionLevel = bp.protectionLevel;
2787         return pi;
2788     }
2789
2790     @Override
2791     public PermissionInfo getPermissionInfo(String name, int flags) {
2792         // reader
2793         synchronized (mPackages) {
2794             final BasePermission p = mSettings.mPermissions.get(name);
2795             if (p != null) {
2796                 return generatePermissionInfo(p, flags);
2797             }
2798             return null;
2799         }
2800     }
2801
2802     @Override
2803     public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2804         // reader
2805         synchronized (mPackages) {
2806             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2807             for (BasePermission p : mSettings.mPermissions.values()) {
2808                 if (group == null) {
2809                     if (p.perm == null || p.perm.info.group == null) {
2810                         out.add(generatePermissionInfo(p, flags));
2811                     }
2812                 } else {
2813                     if (p.perm != null && group.equals(p.perm.info.group)) {
2814                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2815                     }
2816                 }
2817             }
2818
2819             if (out.size() > 0) {
2820                 return out;
2821             }
2822             return mPermissionGroups.containsKey(group) ? out : null;
2823         }
2824     }
2825
2826     @Override
2827     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2828         // reader
2829         synchronized (mPackages) {
2830             return PackageParser.generatePermissionGroupInfo(
2831                     mPermissionGroups.get(name), flags);
2832         }
2833     }
2834
2835     @Override
2836     public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2837         // reader
2838         synchronized (mPackages) {
2839             final int N = mPermissionGroups.size();
2840             ArrayList<PermissionGroupInfo> out
2841                     = new ArrayList<PermissionGroupInfo>(N);
2842             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2843                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2844             }
2845             return out;
2846         }
2847     }
2848
2849     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2850             int userId) {
2851         if (!sUserManager.exists(userId)) return null;
2852         PackageSetting ps = mSettings.mPackages.get(packageName);
2853         if (ps != null) {
2854             if (ps.pkg == null) {
2855                 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2856                         flags, userId);
2857                 if (pInfo != null) {
2858                     return pInfo.applicationInfo;
2859                 }
2860                 return null;
2861             }
2862             return PackageParser.generateApplicationInfo(ps.pkg, flags,
2863                     ps.readUserState(userId), userId);
2864         }
2865         return null;
2866     }
2867
2868     private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2869             int userId) {
2870         if (!sUserManager.exists(userId)) return null;
2871         PackageSetting ps = mSettings.mPackages.get(packageName);
2872         if (ps != null) {
2873             PackageParser.Package pkg = ps.pkg;
2874             if (pkg == null) {
2875                 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2876                     return null;
2877                 }
2878                 // Only data remains, so we aren't worried about code paths
2879                 pkg = new PackageParser.Package(packageName);
2880                 pkg.applicationInfo.packageName = packageName;
2881                 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2882                 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2883                 pkg.applicationInfo.dataDir = Environment
2884                         .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2885                         .getAbsolutePath();
2886                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2887                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2888             }
2889             return generatePackageInfo(pkg, flags, userId);
2890         }
2891         return null;
2892     }
2893
2894     @Override
2895     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2896         if (!sUserManager.exists(userId)) return null;
2897         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2898         // writer
2899         synchronized (mPackages) {
2900             PackageParser.Package p = mPackages.get(packageName);
2901             if (DEBUG_PACKAGE_INFO) Log.v(
2902                     TAG, "getApplicationInfo " + packageName
2903                     + ": " + p);
2904             if (p != null) {
2905                 PackageSetting ps = mSettings.mPackages.get(packageName);
2906                 if (ps == null) return null;
2907                 // Note: isEnabledLP() does not apply here - always return info
2908                 return PackageParser.generateApplicationInfo(
2909                         p, flags, ps.readUserState(userId), userId);
2910             }
2911             if ("android".equals(packageName)||"system".equals(packageName)) {
2912                 return mAndroidApplication;
2913             }
2914             if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2915                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2916             }
2917         }
2918         return null;
2919     }
2920
2921     @Override
2922     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2923             final IPackageDataObserver observer) {
2924         mContext.enforceCallingOrSelfPermission(
2925                 android.Manifest.permission.CLEAR_APP_CACHE, null);
2926         // Queue up an async operation since clearing cache may take a little while.
2927         mHandler.post(new Runnable() {
2928             public void run() {
2929                 mHandler.removeCallbacks(this);
2930                 int retCode = -1;
2931                 synchronized (mInstallLock) {
2932                     retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2933                     if (retCode < 0) {
2934                         Slog.w(TAG, "Couldn't clear application caches");
2935                     }
2936                 }
2937                 if (observer != null) {
2938                     try {
2939                         observer.onRemoveCompleted(null, (retCode >= 0));
2940                     } catch (RemoteException e) {
2941                         Slog.w(TAG, "RemoveException when invoking call back");
2942                     }
2943                 }
2944             }
2945         });
2946     }
2947
2948     @Override
2949     public void freeStorage(final String volumeUuid, final long freeStorageSize,
2950             final IntentSender pi) {
2951         mContext.enforceCallingOrSelfPermission(
2952                 android.Manifest.permission.CLEAR_APP_CACHE, null);
2953         // Queue up an async operation since clearing cache may take a little while.
2954         mHandler.post(new Runnable() {
2955             public void run() {
2956                 mHandler.removeCallbacks(this);
2957                 int retCode = -1;
2958                 synchronized (mInstallLock) {
2959                     retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2960                     if (retCode < 0) {
2961                         Slog.w(TAG, "Couldn't clear application caches");
2962                     }
2963                 }
2964                 if(pi != null) {
2965                     try {
2966                         // Callback via pending intent
2967                         int code = (retCode >= 0) ? 1 : 0;
2968                         pi.sendIntent(null, code, null,
2969                                 null, null);
2970                     } catch (SendIntentException e1) {
2971                         Slog.i(TAG, "Failed to send pending intent");
2972                     }
2973                 }
2974             }
2975         });
2976     }
2977
2978     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2979         synchronized (mInstallLock) {
2980             if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2981                 throw new IOException("Failed to free enough space");
2982             }
2983         }
2984     }
2985
2986     @Override
2987     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2988         if (!sUserManager.exists(userId)) return null;
2989         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2990         synchronized (mPackages) {
2991             PackageParser.Activity a = mActivities.mActivities.get(component);
2992
2993             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2994             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2995                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2996                 if (ps == null) return null;
2997                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2998                         userId);
2999             }
3000             if (mResolveComponentName.equals(component)) {
3001                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3002                         new PackageUserState(), userId);
3003             }
3004         }
3005         return null;
3006     }
3007
3008     @Override
3009     public boolean activitySupportsIntent(ComponentName component, Intent intent,
3010             String resolvedType) {
3011         synchronized (mPackages) {
3012             if (component.equals(mResolveComponentName)) {
3013                 // The resolver supports EVERYTHING!
3014                 return true;
3015             }
3016             PackageParser.Activity a = mActivities.mActivities.get(component);
3017             if (a == null) {
3018                 return false;
3019             }
3020             for (int i=0; i<a.intents.size(); i++) {
3021                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3022                         intent.getData(), intent.getCategories(), TAG) >= 0) {
3023                     return true;
3024                 }
3025             }
3026             return false;
3027         }
3028     }
3029
3030     @Override
3031     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3032         if (!sUserManager.exists(userId)) return null;
3033         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3034         synchronized (mPackages) {
3035             PackageParser.Activity a = mReceivers.mActivities.get(component);
3036             if (DEBUG_PACKAGE_INFO) Log.v(
3037                 TAG, "getReceiverInfo " + component + ": " + a);
3038             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3039                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                 if (ps == null) return null;
3041                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3042                         userId);
3043             }
3044         }
3045         return null;
3046     }
3047
3048     @Override
3049     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3050         if (!sUserManager.exists(userId)) return null;
3051         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3052         synchronized (mPackages) {
3053             PackageParser.Service s = mServices.mServices.get(component);
3054             if (DEBUG_PACKAGE_INFO) Log.v(
3055                 TAG, "getServiceInfo " + component + ": " + s);
3056             if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3057                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3058                 if (ps == null) return null;
3059                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3060                         userId);
3061             }
3062         }
3063         return null;
3064     }
3065
3066     @Override
3067     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3068         if (!sUserManager.exists(userId)) return null;
3069         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3070         synchronized (mPackages) {
3071             PackageParser.Provider p = mProviders.mProviders.get(component);
3072             if (DEBUG_PACKAGE_INFO) Log.v(
3073                 TAG, "getProviderInfo " + component + ": " + p);
3074             if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3075                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3076                 if (ps == null) return null;
3077                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3078                         userId);
3079             }
3080         }
3081         return null;
3082     }
3083
3084     @Override
3085     public String[] getSystemSharedLibraryNames() {
3086         Set<String> libSet;
3087         synchronized (mPackages) {
3088             libSet = mSharedLibraries.keySet();
3089             int size = libSet.size();
3090             if (size > 0) {
3091                 String[] libs = new String[size];
3092                 libSet.toArray(libs);
3093                 return libs;
3094             }
3095         }
3096         return null;
3097     }
3098
3099     /**
3100      * @hide
3101      */
3102     PackageParser.Package findSharedNonSystemLibrary(String libName) {
3103         synchronized (mPackages) {
3104             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3105             if (lib != null && lib.apk != null) {
3106                 return mPackages.get(lib.apk);
3107             }
3108         }
3109         return null;
3110     }
3111
3112     @Override
3113     public FeatureInfo[] getSystemAvailableFeatures() {
3114         Collection<FeatureInfo> featSet;
3115         synchronized (mPackages) {
3116             featSet = mAvailableFeatures.values();
3117             int size = featSet.size();
3118             if (size > 0) {
3119                 FeatureInfo[] features = new FeatureInfo[size+1];
3120                 featSet.toArray(features);
3121                 FeatureInfo fi = new FeatureInfo();
3122                 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3123                         FeatureInfo.GL_ES_VERSION_UNDEFINED);
3124                 features[size] = fi;
3125                 return features;
3126             }
3127         }
3128         return null;
3129     }
3130
3131     @Override
3132     public boolean hasSystemFeature(String name) {
3133         synchronized (mPackages) {
3134             return mAvailableFeatures.containsKey(name);
3135         }
3136     }
3137
3138     private void checkValidCaller(int uid, int userId) {
3139         if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3140             return;
3141
3142         throw new SecurityException("Caller uid=" + uid
3143                 + " is not privileged to communicate with user=" + userId);
3144     }
3145
3146     @Override
3147     public int checkPermission(String permName, String pkgName, int userId) {
3148         if (!sUserManager.exists(userId)) {
3149             return PackageManager.PERMISSION_DENIED;
3150         }
3151
3152         synchronized (mPackages) {
3153             final PackageParser.Package p = mPackages.get(pkgName);
3154             if (p != null && p.mExtras != null) {
3155                 final PackageSetting ps = (PackageSetting) p.mExtras;
3156                 final PermissionsState permissionsState = ps.getPermissionsState();
3157                 if (permissionsState.hasPermission(permName, userId)) {
3158                     return PackageManager.PERMISSION_GRANTED;
3159                 }
3160                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3161                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3162                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3163                     return PackageManager.PERMISSION_GRANTED;
3164                 }
3165             }
3166         }
3167
3168         return PackageManager.PERMISSION_DENIED;
3169     }
3170
3171     @Override
3172     public int checkUidPermission(String permName, int uid) {
3173         final int userId = UserHandle.getUserId(uid);
3174
3175         if (!sUserManager.exists(userId)) {
3176             return PackageManager.PERMISSION_DENIED;
3177         }
3178
3179         synchronized (mPackages) {
3180             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3181             if (obj != null) {
3182                 final SettingBase ps = (SettingBase) obj;
3183                 final PermissionsState permissionsState = ps.getPermissionsState();
3184                 if (permissionsState.hasPermission(permName, userId)) {
3185                     return PackageManager.PERMISSION_GRANTED;
3186                 }
3187                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3188                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3189                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3190                     return PackageManager.PERMISSION_GRANTED;
3191                 }
3192             } else {
3193                 ArraySet<String> perms = mSystemPermissions.get(uid);
3194                 if (perms != null) {
3195                     if (perms.contains(permName)) {
3196                         return PackageManager.PERMISSION_GRANTED;
3197                     }
3198                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3199                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3200                         return PackageManager.PERMISSION_GRANTED;
3201                     }
3202                 }
3203             }
3204         }
3205
3206         return PackageManager.PERMISSION_DENIED;
3207     }
3208
3209     @Override
3210     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3211         if (UserHandle.getCallingUserId() != userId) {
3212             mContext.enforceCallingPermission(
3213                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3214                     "isPermissionRevokedByPolicy for user " + userId);
3215         }
3216
3217         if (checkPermission(permission, packageName, userId)
3218                 == PackageManager.PERMISSION_GRANTED) {
3219             return false;
3220         }
3221
3222         final long identity = Binder.clearCallingIdentity();
3223         try {
3224             final int flags = getPermissionFlags(permission, packageName, userId);
3225             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3226         } finally {
3227             Binder.restoreCallingIdentity(identity);
3228         }
3229     }
3230
3231     @Override
3232     public String getPermissionControllerPackageName() {
3233         synchronized (mPackages) {
3234             return mRequiredInstallerPackage;
3235         }
3236     }
3237
3238     /**
3239      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3240      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3241      * @param checkShell TODO(yamasani):
3242      * @param message the message to log on security exception
3243      */
3244     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3245             boolean checkShell, String message) {
3246         if (userId < 0) {
3247             throw new IllegalArgumentException("Invalid userId " + userId);
3248         }
3249         if (checkShell) {
3250             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3251         }
3252         if (userId == UserHandle.getUserId(callingUid)) return;
3253         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3254             if (requireFullPermission) {
3255                 mContext.enforceCallingOrSelfPermission(
3256                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3257             } else {
3258                 try {
3259                     mContext.enforceCallingOrSelfPermission(
3260                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3261                 } catch (SecurityException se) {
3262                     mContext.enforceCallingOrSelfPermission(
3263                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3264                 }
3265             }
3266         }
3267     }
3268
3269     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3270         if (callingUid == Process.SHELL_UID) {
3271             if (userHandle >= 0
3272                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3273                 throw new SecurityException("Shell does not have permission to access user "
3274                         + userHandle);
3275             } else if (userHandle < 0) {
3276                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3277                         + Debug.getCallers(3));
3278             }
3279         }
3280     }
3281
3282     private BasePermission findPermissionTreeLP(String permName) {
3283         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3284             if (permName.startsWith(bp.name) &&
3285                     permName.length() > bp.name.length() &&
3286                     permName.charAt(bp.name.length()) == '.') {
3287                 return bp;
3288             }
3289         }
3290         return null;
3291     }
3292
3293     private BasePermission checkPermissionTreeLP(String permName) {
3294         if (permName != null) {
3295             BasePermission bp = findPermissionTreeLP(permName);
3296             if (bp != null) {
3297                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3298                     return bp;
3299                 }
3300                 throw new SecurityException("Calling uid "
3301                         + Binder.getCallingUid()
3302                         + " is not allowed to add to permission tree "
3303                         + bp.name + " owned by uid " + bp.uid);
3304             }
3305         }
3306         throw new SecurityException("No permission tree found for " + permName);
3307     }
3308
3309     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3310         if (s1 == null) {
3311             return s2 == null;
3312         }
3313         if (s2 == null) {
3314             return false;
3315         }
3316         if (s1.getClass() != s2.getClass()) {
3317             return false;
3318         }
3319         return s1.equals(s2);
3320     }
3321
3322     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3323         if (pi1.icon != pi2.icon) return false;
3324         if (pi1.logo != pi2.logo) return false;
3325         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3326         if (!compareStrings(pi1.name, pi2.name)) return false;
3327         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3328         // We'll take care of setting this one.
3329         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3330         // These are not currently stored in settings.
3331         //if (!compareStrings(pi1.group, pi2.group)) return false;
3332         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3333         //if (pi1.labelRes != pi2.labelRes) return false;
3334         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3335         return true;
3336     }
3337
3338     int permissionInfoFootprint(PermissionInfo info) {
3339         int size = info.name.length();
3340         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3341         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3342         return size;
3343     }
3344
3345     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3346         int size = 0;
3347         for (BasePermission perm : mSettings.mPermissions.values()) {
3348             if (perm.uid == tree.uid) {
3349                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3350             }
3351         }
3352         return size;
3353     }
3354
3355     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3356         // We calculate the max size of permissions defined by this uid and throw
3357         // if that plus the size of 'info' would exceed our stated maximum.
3358         if (tree.uid != Process.SYSTEM_UID) {
3359             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3360             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3361                 throw new SecurityException("Permission tree size cap exceeded");
3362             }
3363         }
3364     }
3365
3366     boolean addPermissionLocked(PermissionInfo info, boolean async) {
3367         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3368             throw new SecurityException("Label must be specified in permission");
3369         }
3370         BasePermission tree = checkPermissionTreeLP(info.name);
3371         BasePermission bp = mSettings.mPermissions.get(info.name);
3372         boolean added = bp == null;
3373         boolean changed = true;
3374         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3375         if (added) {
3376             enforcePermissionCapLocked(info, tree);
3377             bp = new BasePermission(info.name, tree.sourcePackage,
3378                     BasePermission.TYPE_DYNAMIC);
3379         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3380             throw new SecurityException(
3381                     "Not allowed to modify non-dynamic permission "
3382                     + info.name);
3383         } else {
3384             if (bp.protectionLevel == fixedLevel
3385                     && bp.perm.owner.equals(tree.perm.owner)
3386                     && bp.uid == tree.uid
3387                     && comparePermissionInfos(bp.perm.info, info)) {
3388                 changed = false;
3389             }
3390         }
3391         bp.protectionLevel = fixedLevel;
3392         info = new PermissionInfo(info);
3393         info.protectionLevel = fixedLevel;
3394         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3395         bp.perm.info.packageName = tree.perm.info.packageName;
3396         bp.uid = tree.uid;
3397         if (added) {
3398             mSettings.mPermissions.put(info.name, bp);
3399         }
3400         if (changed) {
3401             if (!async) {
3402                 mSettings.writeLPr();
3403             } else {
3404                 scheduleWriteSettingsLocked();
3405             }
3406         }
3407         return added;
3408     }
3409
3410     @Override
3411     public boolean addPermission(PermissionInfo info) {
3412         synchronized (mPackages) {
3413             return addPermissionLocked(info, false);
3414         }
3415     }
3416
3417     @Override
3418     public boolean addPermissionAsync(PermissionInfo info) {
3419         synchronized (mPackages) {
3420             return addPermissionLocked(info, true);
3421         }
3422     }
3423
3424     @Override
3425     public void removePermission(String name) {
3426         synchronized (mPackages) {
3427             checkPermissionTreeLP(name);
3428             BasePermission bp = mSettings.mPermissions.get(name);
3429             if (bp != null) {
3430                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
3431                     throw new SecurityException(
3432                             "Not allowed to modify non-dynamic permission "
3433                             + name);
3434                 }
3435                 mSettings.mPermissions.remove(name);
3436                 mSettings.writeLPr();
3437             }
3438         }
3439     }
3440
3441     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3442             BasePermission bp) {
3443         int index = pkg.requestedPermissions.indexOf(bp.name);
3444         if (index == -1) {
3445             throw new SecurityException("Package " + pkg.packageName
3446                     + " has not requested permission " + bp.name);
3447         }
3448         if (!bp.isRuntime() && !bp.isDevelopment()) {
3449             throw new SecurityException("Permission " + bp.name
3450                     + " is not a changeable permission type");
3451         }
3452     }
3453
3454     @Override
3455     public void grantRuntimePermission(String packageName, String name, final int userId) {
3456         if (!sUserManager.exists(userId)) {
3457             Log.e(TAG, "No such user:" + userId);
3458             return;
3459         }
3460
3461         mContext.enforceCallingOrSelfPermission(
3462                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3463                 "grantRuntimePermission");
3464
3465         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3466                 "grantRuntimePermission");
3467
3468         final int uid;
3469         final SettingBase sb;
3470
3471         synchronized (mPackages) {
3472             final PackageParser.Package pkg = mPackages.get(packageName);
3473             if (pkg == null) {
3474                 throw new IllegalArgumentException("Unknown package: " + packageName);
3475             }
3476
3477             final BasePermission bp = mSettings.mPermissions.get(name);
3478             if (bp == null) {
3479                 throw new IllegalArgumentException("Unknown permission: " + name);
3480             }
3481
3482             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3483
3484             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3485             sb = (SettingBase) pkg.mExtras;
3486             if (sb == null) {
3487                 throw new IllegalArgumentException("Unknown package: " + packageName);
3488             }
3489
3490             final PermissionsState permissionsState = sb.getPermissionsState();
3491
3492             final int flags = permissionsState.getPermissionFlags(name, userId);
3493             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3494                 throw new SecurityException("Cannot grant system fixed permission: "
3495                         + name + " for package: " + packageName);
3496             }
3497
3498             if (bp.isDevelopment()) {
3499                 // Development permissions must be handled specially, since they are not
3500                 // normal runtime permissions.  For now they apply to all users.
3501                 if (permissionsState.grantInstallPermission(bp) !=
3502                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
3503                     scheduleWriteSettingsLocked();
3504                 }
3505                 return;
3506             }
3507
3508             final int result = permissionsState.grantRuntimePermission(bp, userId);
3509             switch (result) {
3510                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3511                     return;
3512                 }
3513
3514                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3515                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3516                     mHandler.post(new Runnable() {
3517                         @Override
3518                         public void run() {
3519                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3520                         }
3521                     });
3522                 } break;
3523             }
3524
3525             mOnPermissionChangeListeners.onPermissionsChanged(uid);
3526
3527             // Not critical if that is lost - app has to request again.
3528             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3529         }
3530
3531         // Only need to do this if user is initialized. Otherwise it's a new user
3532         // and there are no processes running as the user yet and there's no need
3533         // to make an expensive call to remount processes for the changed permissions.
3534         if (READ_EXTERNAL_STORAGE.equals(name)
3535                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
3536             final long token = Binder.clearCallingIdentity();
3537             try {
3538                 if (sUserManager.isInitialized(userId)) {
3539                     MountServiceInternal mountServiceInternal = LocalServices.getService(
3540                             MountServiceInternal.class);
3541                     mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3542                 }
3543             } finally {
3544                 Binder.restoreCallingIdentity(token);
3545             }
3546         }
3547     }
3548
3549     @Override
3550     public void revokeRuntimePermission(String packageName, String name, int userId) {
3551         if (!sUserManager.exists(userId)) {
3552             Log.e(TAG, "No such user:" + userId);
3553             return;
3554         }
3555
3556         mContext.enforceCallingOrSelfPermission(
3557                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3558                 "revokeRuntimePermission");
3559
3560         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3561                 "revokeRuntimePermission");
3562
3563         final int appId;
3564
3565         synchronized (mPackages) {
3566             final PackageParser.Package pkg = mPackages.get(packageName);
3567             if (pkg == null) {
3568                 throw new IllegalArgumentException("Unknown package: " + packageName);
3569             }
3570
3571             final BasePermission bp = mSettings.mPermissions.get(name);
3572             if (bp == null) {
3573                 throw new IllegalArgumentException("Unknown permission: " + name);
3574             }
3575
3576             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3577
3578             SettingBase sb = (SettingBase) pkg.mExtras;
3579             if (sb == null) {
3580                 throw new IllegalArgumentException("Unknown package: " + packageName);
3581             }
3582
3583             final PermissionsState permissionsState = sb.getPermissionsState();
3584
3585             final int flags = permissionsState.getPermissionFlags(name, userId);
3586             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3587                 throw new SecurityException("Cannot revoke system fixed permission: "
3588                         + name + " for package: " + packageName);
3589             }
3590
3591             if (bp.isDevelopment()) {
3592                 // Development permissions must be handled specially, since they are not
3593                 // normal runtime permissions.  For now they apply to all users.
3594                 if (permissionsState.revokeInstallPermission(bp) !=
3595                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
3596                     scheduleWriteSettingsLocked();
3597                 }
3598                 return;
3599             }
3600
3601             if (permissionsState.revokeRuntimePermission(bp, userId) ==
3602                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
3603                 return;
3604             }
3605
3606             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3607
3608             // Critical, after this call app should never have the permission.
3609             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3610
3611             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3612         }
3613
3614         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3615     }
3616
3617     @Override
3618     public void resetRuntimePermissions() {
3619         mContext.enforceCallingOrSelfPermission(
3620                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3621                 "revokeRuntimePermission");
3622
3623         int callingUid = Binder.getCallingUid();
3624         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3625             mContext.enforceCallingOrSelfPermission(
3626                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3627                     "resetRuntimePermissions");
3628         }
3629
3630         synchronized (mPackages) {
3631             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3632             for (int userId : UserManagerService.getInstance().getUserIds()) {
3633                 final int packageCount = mPackages.size();
3634                 for (int i = 0; i < packageCount; i++) {
3635                     PackageParser.Package pkg = mPackages.valueAt(i);
3636                     if (!(pkg.mExtras instanceof PackageSetting)) {
3637                         continue;
3638                     }
3639                     PackageSetting ps = (PackageSetting) pkg.mExtras;
3640                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3641                 }
3642             }
3643         }
3644     }
3645
3646     @Override
3647     public int getPermissionFlags(String name, String packageName, int userId) {
3648         if (!sUserManager.exists(userId)) {
3649             return 0;
3650         }
3651
3652         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3653
3654         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3655                 "getPermissionFlags");
3656
3657         synchronized (mPackages) {
3658             final PackageParser.Package pkg = mPackages.get(packageName);
3659             if (pkg == null) {
3660                 throw new IllegalArgumentException("Unknown package: " + packageName);
3661             }
3662
3663             final BasePermission bp = mSettings.mPermissions.get(name);
3664             if (bp == null) {
3665                 throw new IllegalArgumentException("Unknown permission: " + name);
3666             }
3667
3668             SettingBase sb = (SettingBase) pkg.mExtras;
3669             if (sb == null) {
3670                 throw new IllegalArgumentException("Unknown package: " + packageName);
3671             }
3672
3673             PermissionsState permissionsState = sb.getPermissionsState();
3674             return permissionsState.getPermissionFlags(name, userId);
3675         }
3676     }
3677
3678     @Override
3679     public void updatePermissionFlags(String name, String packageName, int flagMask,
3680             int flagValues, int userId) {
3681         if (!sUserManager.exists(userId)) {
3682             return;
3683         }
3684
3685         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3686
3687         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3688                 "updatePermissionFlags");
3689
3690         // Only the system can change these flags and nothing else.
3691         if (getCallingUid() != Process.SYSTEM_UID) {
3692             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3694             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3696         }
3697
3698         synchronized (mPackages) {
3699             final PackageParser.Package pkg = mPackages.get(packageName);
3700             if (pkg == null) {
3701                 throw new IllegalArgumentException("Unknown package: " + packageName);
3702             }
3703
3704             final BasePermission bp = mSettings.mPermissions.get(name);
3705             if (bp == null) {
3706                 throw new IllegalArgumentException("Unknown permission: " + name);
3707             }
3708
3709             SettingBase sb = (SettingBase) pkg.mExtras;
3710             if (sb == null) {
3711                 throw new IllegalArgumentException("Unknown package: " + packageName);
3712             }
3713
3714             PermissionsState permissionsState = sb.getPermissionsState();
3715
3716             // Only the package manager can change flags for system component permissions.
3717             final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3718             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3719                 return;
3720             }
3721
3722             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3723
3724             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3725                 // Install and runtime permissions are stored in different places,
3726                 // so figure out what permission changed and persist the change.
3727                 if (permissionsState.getInstallPermissionState(name) != null) {
3728                     scheduleWriteSettingsLocked();
3729                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3730                         || hadState) {
3731                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3732                 }
3733             }
3734         }
3735     }
3736
3737     /**
3738      * Update the permission flags for all packages and runtime permissions of a user in order
3739      * to allow device or profile owner to remove POLICY_FIXED.
3740      */
3741     @Override
3742     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3743         if (!sUserManager.exists(userId)) {
3744             return;
3745         }
3746
3747         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3748
3749         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3750                 "updatePermissionFlagsForAllApps");
3751
3752         // Only the system can change system fixed flags.
3753         if (getCallingUid() != Process.SYSTEM_UID) {
3754             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3756         }
3757
3758         synchronized (mPackages) {
3759             boolean changed = false;
3760             final int packageCount = mPackages.size();
3761             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3762                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3763                 SettingBase sb = (SettingBase) pkg.mExtras;
3764                 if (sb == null) {
3765                     continue;
3766                 }
3767                 PermissionsState permissionsState = sb.getPermissionsState();
3768                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3769                         userId, flagMask, flagValues);
3770             }
3771             if (changed) {
3772                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3773             }
3774         }
3775     }
3776
3777     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3778         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3779                 != PackageManager.PERMISSION_GRANTED
3780             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3781                 != PackageManager.PERMISSION_GRANTED) {
3782             throw new SecurityException(message + " requires "
3783                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3784                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3785         }
3786     }
3787
3788     @Override
3789     public boolean shouldShowRequestPermissionRationale(String permissionName,
3790             String packageName, int userId) {
3791         if (UserHandle.getCallingUserId() != userId) {
3792             mContext.enforceCallingPermission(
3793                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3794                     "canShowRequestPermissionRationale for user " + userId);
3795         }
3796
3797         final int uid = getPackageUid(packageName, userId);
3798         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3799             return false;
3800         }
3801
3802         if (checkPermission(permissionName, packageName, userId)
3803                 == PackageManager.PERMISSION_GRANTED) {
3804             return false;
3805         }
3806
3807         final int flags;
3808
3809         final long identity = Binder.clearCallingIdentity();
3810         try {
3811             flags = getPermissionFlags(permissionName,
3812                     packageName, userId);
3813         } finally {
3814             Binder.restoreCallingIdentity(identity);
3815         }
3816
3817         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3818                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3819                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
3820
3821         if ((flags & fixedFlags) != 0) {
3822             return false;
3823         }
3824
3825         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3826     }
3827
3828     @Override
3829     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3830         mContext.enforceCallingOrSelfPermission(
3831                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3832                 "addOnPermissionsChangeListener");
3833
3834         synchronized (mPackages) {
3835             mOnPermissionChangeListeners.addListenerLocked(listener);
3836         }
3837     }
3838
3839     @Override
3840     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3841         synchronized (mPackages) {
3842             mOnPermissionChangeListeners.removeListenerLocked(listener);
3843         }
3844     }
3845
3846     @Override
3847     public boolean isProtectedBroadcast(String actionName) {
3848         synchronized (mPackages) {
3849             return mProtectedBroadcasts.contains(actionName);
3850         }
3851     }
3852
3853     @Override
3854     public int checkSignatures(String pkg1, String pkg2) {
3855         synchronized (mPackages) {
3856             final PackageParser.Package p1 = mPackages.get(pkg1);
3857             final PackageParser.Package p2 = mPackages.get(pkg2);
3858             if (p1 == null || p1.mExtras == null
3859                     || p2 == null || p2.mExtras == null) {
3860                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3861             }
3862             return compareSignatures(p1.mSignatures, p2.mSignatures);
3863         }
3864     }
3865
3866     @Override
3867     public int checkUidSignatures(int uid1, int uid2) {
3868         // Map to base uids.
3869         uid1 = UserHandle.getAppId(uid1);
3870         uid2 = UserHandle.getAppId(uid2);
3871         // reader
3872         synchronized (mPackages) {
3873             Signature[] s1;
3874             Signature[] s2;
3875             Object obj = mSettings.getUserIdLPr(uid1);
3876             if (obj != null) {
3877                 if (obj instanceof SharedUserSetting) {
3878                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3879                 } else if (obj instanceof PackageSetting) {
3880                     s1 = ((PackageSetting)obj).signatures.mSignatures;
3881                 } else {
3882                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3883                 }
3884             } else {
3885                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3886             }
3887             obj = mSettings.getUserIdLPr(uid2);
3888             if (obj != null) {
3889                 if (obj instanceof SharedUserSetting) {
3890                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3891                 } else if (obj instanceof PackageSetting) {
3892                     s2 = ((PackageSetting)obj).signatures.mSignatures;
3893                 } else {
3894                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3895                 }
3896             } else {
3897                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3898             }
3899             return compareSignatures(s1, s2);
3900         }
3901     }
3902
3903     private void killUid(int appId, int userId, String reason) {
3904         final long identity = Binder.clearCallingIdentity();
3905         try {
3906             IActivityManager am = ActivityManagerNative.getDefault();
3907             if (am != null) {
3908                 try {
3909                     am.killUid(appId, userId, reason);
3910                 } catch (RemoteException e) {
3911                     /* ignore - same process */
3912                 }
3913             }
3914         } finally {
3915             Binder.restoreCallingIdentity(identity);
3916         }
3917     }
3918
3919     /**
3920      * Compares two sets of signatures. Returns:
3921      * <br />
3922      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3923      * <br />
3924      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3925      * <br />
3926      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3927      * <br />
3928      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3929      * <br />
3930      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3931      */
3932     static int compareSignatures(Signature[] s1, Signature[] s2) {
3933         if (s1 == null) {
3934             return s2 == null
3935                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
3936                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3937         }
3938
3939         if (s2 == null) {
3940             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3941         }
3942
3943         if (s1.length != s2.length) {
3944             return PackageManager.SIGNATURE_NO_MATCH;
3945         }
3946
3947         // Since both signature sets are of size 1, we can compare without HashSets.
3948         if (s1.length == 1) {
3949             return s1[0].equals(s2[0]) ?
3950                     PackageManager.SIGNATURE_MATCH :
3951                     PackageManager.SIGNATURE_NO_MATCH;
3952         }
3953
3954         ArraySet<Signature> set1 = new ArraySet<Signature>();
3955         for (Signature sig : s1) {
3956             set1.add(sig);
3957         }
3958         ArraySet<Signature> set2 = new ArraySet<Signature>();
3959         for (Signature sig : s2) {
3960             set2.add(sig);
3961         }
3962         // Make sure s2 contains all signatures in s1.
3963         if (set1.equals(set2)) {
3964             return PackageManager.SIGNATURE_MATCH;
3965         }
3966         return PackageManager.SIGNATURE_NO_MATCH;
3967     }
3968
3969     /**
3970      * If the database version for this type of package (internal storage or
3971      * external storage) is less than the version where package signatures
3972      * were updated, return true.
3973      */
3974     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3975         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3976         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3977     }
3978
3979     /**
3980      * Used for backward compatibility to make sure any packages with
3981      * certificate chains get upgraded to the new style. {@code existingSigs}
3982      * will be in the old format (since they were stored on disk from before the
3983      * system upgrade) and {@code scannedSigs} will be in the newer format.
3984      */
3985     private int compareSignaturesCompat(PackageSignatures existingSigs,
3986             PackageParser.Package scannedPkg) {
3987         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3988             return PackageManager.SIGNATURE_NO_MATCH;
3989         }
3990
3991         ArraySet<Signature> existingSet = new ArraySet<Signature>();
3992         for (Signature sig : existingSigs.mSignatures) {
3993             existingSet.add(sig);
3994         }
3995         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3996         for (Signature sig : scannedPkg.mSignatures) {
3997             try {
3998                 Signature[] chainSignatures = sig.getChainSignatures();
3999                 for (Signature chainSig : chainSignatures) {
4000                     scannedCompatSet.add(chainSig);
4001                 }
4002             } catch (CertificateEncodingException e) {
4003                 scannedCompatSet.add(sig);
4004             }
4005         }
4006         /*
4007          * Make sure the expanded scanned set contains all signatures in the
4008          * existing one.
4009          */
4010         if (scannedCompatSet.equals(existingSet)) {
4011             // Migrate the old signatures to the new scheme.
4012             existingSigs.assignSignatures(scannedPkg.mSignatures);
4013             // The new KeySets will be re-added later in the scanning process.
4014             synchronized (mPackages) {
4015                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4016             }
4017             return PackageManager.SIGNATURE_MATCH;
4018         }
4019         return PackageManager.SIGNATURE_NO_MATCH;
4020     }
4021
4022     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4023         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4024         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4025     }
4026
4027     private int compareSignaturesRecover(PackageSignatures existingSigs,
4028             PackageParser.Package scannedPkg) {
4029         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4030             return PackageManager.SIGNATURE_NO_MATCH;
4031         }
4032
4033         String msg = null;
4034         try {
4035             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4036                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4037                         + scannedPkg.packageName);
4038                 return PackageManager.SIGNATURE_MATCH;
4039             }
4040         } catch (CertificateException e) {
4041             msg = e.getMessage();
4042         }
4043
4044         logCriticalInfo(Log.INFO,
4045                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4046         return PackageManager.SIGNATURE_NO_MATCH;
4047     }
4048
4049     @Override
4050     public String[] getPackagesForUid(int uid) {
4051         uid = UserHandle.getAppId(uid);
4052         // reader
4053         synchronized (mPackages) {
4054             Object obj = mSettings.getUserIdLPr(uid);
4055             if (obj instanceof SharedUserSetting) {
4056                 final SharedUserSetting sus = (SharedUserSetting) obj;
4057                 final int N = sus.packages.size();
4058                 final String[] res = new String[N];
4059                 final Iterator<PackageSetting> it = sus.packages.iterator();
4060                 int i = 0;
4061                 while (it.hasNext()) {
4062                     res[i++] = it.next().name;
4063                 }
4064                 return res;
4065             } else if (obj instanceof PackageSetting) {
4066                 final PackageSetting ps = (PackageSetting) obj;
4067                 return new String[] { ps.name };
4068             }
4069         }
4070         return null;
4071     }
4072
4073     @Override
4074     public String getNameForUid(int uid) {
4075         // reader
4076         synchronized (mPackages) {
4077             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4078             if (obj instanceof SharedUserSetting) {
4079                 final SharedUserSetting sus = (SharedUserSetting) obj;
4080                 return sus.name + ":" + sus.userId;
4081             } else if (obj instanceof PackageSetting) {
4082                 final PackageSetting ps = (PackageSetting) obj;
4083                 return ps.name;
4084             }
4085         }
4086         return null;
4087     }
4088
4089     @Override
4090     public int getUidForSharedUser(String sharedUserName) {
4091         if(sharedUserName == null) {
4092             return -1;
4093         }
4094         // reader
4095         synchronized (mPackages) {
4096             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4097             if (suid == null) {
4098                 return -1;
4099             }
4100             return suid.userId;
4101         }
4102     }
4103
4104     @Override
4105     public int getFlagsForUid(int uid) {
4106         synchronized (mPackages) {
4107             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4108             if (obj instanceof SharedUserSetting) {
4109                 final SharedUserSetting sus = (SharedUserSetting) obj;
4110                 return sus.pkgFlags;
4111             } else if (obj instanceof PackageSetting) {
4112                 final PackageSetting ps = (PackageSetting) obj;
4113                 return ps.pkgFlags;
4114             }
4115         }
4116         return 0;
4117     }
4118
4119     @Override
4120     public int getPrivateFlagsForUid(int uid) {
4121         synchronized (mPackages) {
4122             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4123             if (obj instanceof SharedUserSetting) {
4124                 final SharedUserSetting sus = (SharedUserSetting) obj;
4125                 return sus.pkgPrivateFlags;
4126             } else if (obj instanceof PackageSetting) {
4127                 final PackageSetting ps = (PackageSetting) obj;
4128                 return ps.pkgPrivateFlags;
4129             }
4130         }
4131         return 0;
4132     }
4133
4134     @Override
4135     public boolean isUidPrivileged(int uid) {
4136         uid = UserHandle.getAppId(uid);
4137         // reader
4138         synchronized (mPackages) {
4139             Object obj = mSettings.getUserIdLPr(uid);
4140             if (obj instanceof SharedUserSetting) {
4141                 final SharedUserSetting sus = (SharedUserSetting) obj;
4142                 final Iterator<PackageSetting> it = sus.packages.iterator();
4143                 while (it.hasNext()) {
4144                     if (it.next().isPrivileged()) {
4145                         return true;
4146                     }
4147                 }
4148             } else if (obj instanceof PackageSetting) {
4149                 final PackageSetting ps = (PackageSetting) obj;
4150                 return ps.isPrivileged();
4151             }
4152         }
4153         return false;
4154     }
4155
4156     @Override
4157     public String[] getAppOpPermissionPackages(String permissionName) {
4158         synchronized (mPackages) {
4159             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4160             if (pkgs == null) {
4161                 return null;
4162             }
4163             return pkgs.toArray(new String[pkgs.size()]);
4164         }
4165     }
4166
4167     @Override
4168     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4169             int flags, int userId) {
4170         if (!sUserManager.exists(userId)) return null;
4171         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4172         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4173         return chooseBestActivity(intent, resolvedType, flags, query, userId);
4174     }
4175
4176     @Override
4177     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4178             IntentFilter filter, int match, ComponentName activity) {
4179         final int userId = UserHandle.getCallingUserId();
4180         if (DEBUG_PREFERRED) {
4181             Log.v(TAG, "setLastChosenActivity intent=" + intent
4182                 + " resolvedType=" + resolvedType
4183                 + " flags=" + flags
4184                 + " filter=" + filter
4185                 + " match=" + match
4186                 + " activity=" + activity);
4187             filter.dump(new PrintStreamPrinter(System.out), "    ");
4188         }
4189         intent.setComponent(null);
4190         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4191         // Find any earlier preferred or last chosen entries and nuke them
4192         findPreferredActivity(intent, resolvedType,
4193                 flags, query, 0, false, true, false, userId);
4194         // Add the new activity as the last chosen for this filter
4195         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4196                 "Setting last chosen");
4197     }
4198
4199     @Override
4200     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4201         final int userId = UserHandle.getCallingUserId();
4202         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4203         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4204         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4205                 false, false, false, userId);
4206     }
4207
4208     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4209             int flags, List<ResolveInfo> query, int userId) {
4210         if (query != null) {
4211             final int N = query.size();
4212             if (N == 1) {
4213                 return query.get(0);
4214             } else if (N > 1) {
4215                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4216                 // If there is more than one activity with the same priority,
4217                 // then let the user decide between them.
4218                 ResolveInfo r0 = query.get(0);
4219                 ResolveInfo r1 = query.get(1);
4220                 if (DEBUG_INTENT_MATCHING || debug) {
4221                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4222                             + r1.activityInfo.name + "=" + r1.priority);
4223                 }
4224                 // If the first activity has a higher priority, or a different
4225                 // default, then it is always desireable to pick it.
4226                 if (r0.priority != r1.priority
4227                         || r0.preferredOrder != r1.preferredOrder
4228                         || r0.isDefault != r1.isDefault) {
4229                     return query.get(0);
4230                 }
4231                 // If we have saved a preference for a preferred activity for
4232                 // this Intent, use that.
4233                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4234                         flags, query, r0.priority, true, false, debug, userId);
4235                 if (ri != null) {
4236                     return ri;
4237                 }
4238                 ri = new ResolveInfo(mResolveInfo);
4239                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
4240                 ri.activityInfo.applicationInfo = new ApplicationInfo(
4241                         ri.activityInfo.applicationInfo);
4242                 if (userId != 0) {
4243                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4244                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4245                 }
4246                 // Make sure that the resolver is displayable in car mode
4247                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4248                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4249                 return ri;
4250             }
4251         }
4252         return null;
4253     }
4254
4255     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4256             int flags, List<ResolveInfo> query, boolean debug, int userId) {
4257         final int N = query.size();
4258         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4259                 .get(userId);
4260         // Get the list of persistent preferred activities that handle the intent
4261         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4262         List<PersistentPreferredActivity> pprefs = ppir != null
4263                 ? ppir.queryIntent(intent, resolvedType,
4264                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4265                 : null;
4266         if (pprefs != null && pprefs.size() > 0) {
4267             final int M = pprefs.size();
4268             for (int i=0; i<M; i++) {
4269                 final PersistentPreferredActivity ppa = pprefs.get(i);
4270                 if (DEBUG_PREFERRED || debug) {
4271                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4272                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4273                             + "\n  component=" + ppa.mComponent);
4274                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4275                 }
4276                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4277                         flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4278                 if (DEBUG_PREFERRED || debug) {
4279                     Slog.v(TAG, "Found persistent preferred activity:");
4280                     if (ai != null) {
4281                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4282                     } else {
4283                         Slog.v(TAG, "  null");
4284                     }
4285                 }
4286                 if (ai == null) {
4287                     // This previously registered persistent preferred activity
4288                     // component is no longer known. Ignore it and do NOT remove it.
4289                     continue;
4290                 }
4291                 for (int j=0; j<N; j++) {
4292                     final ResolveInfo ri = query.get(j);
4293                     if (!ri.activityInfo.applicationInfo.packageName
4294                             .equals(ai.applicationInfo.packageName)) {
4295                         continue;
4296                     }
4297                     if (!ri.activityInfo.name.equals(ai.name)) {
4298                         continue;
4299                     }
4300                     //  Found a persistent preference that can handle the intent.
4301                     if (DEBUG_PREFERRED || debug) {
4302                         Slog.v(TAG, "Returning persistent preferred activity: " +
4303                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4304                     }
4305                     return ri;
4306                 }
4307             }
4308         }
4309         return null;
4310     }
4311
4312     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4313             List<ResolveInfo> query, int priority, boolean always,
4314             boolean removeMatches, boolean debug, int userId) {
4315         if (!sUserManager.exists(userId)) return null;
4316         // writer
4317         synchronized (mPackages) {
4318             if (intent.getSelector() != null) {
4319                 intent = intent.getSelector();
4320             }
4321             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4322
4323             // Try to find a matching persistent preferred activity.
4324             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4325                     debug, userId);
4326
4327             // If a persistent preferred activity matched, use it.
4328             if (pri != null) {
4329                 return pri;
4330             }
4331
4332             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4333             // Get the list of preferred activities that handle the intent
4334             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4335             List<PreferredActivity> prefs = pir != null
4336                     ? pir.queryIntent(intent, resolvedType,
4337                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4338                     : null;
4339             if (prefs != null && prefs.size() > 0) {
4340                 boolean changed = false;
4341                 try {
4342                     // First figure out how good the original match set is.
4343                     // We will only allow preferred activities that came
4344                     // from the same match quality.
4345                     int match = 0;
4346
4347                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4348
4349                     final int N = query.size();
4350                     for (int j=0; j<N; j++) {
4351                         final ResolveInfo ri = query.get(j);
4352                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4353                                 + ": 0x" + Integer.toHexString(match));
4354                         if (ri.match > match) {
4355                             match = ri.match;
4356                         }
4357                     }
4358
4359                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4360                             + Integer.toHexString(match));
4361
4362                     match &= IntentFilter.MATCH_CATEGORY_MASK;
4363                     final int M = prefs.size();
4364                     for (int i=0; i<M; i++) {
4365                         final PreferredActivity pa = prefs.get(i);
4366                         if (DEBUG_PREFERRED || debug) {
4367                             Slog.v(TAG, "Checking PreferredActivity ds="
4368                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4369                                     + "\n  component=" + pa.mPref.mComponent);
4370                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4371                         }
4372                         if (pa.mPref.mMatch != match) {
4373                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4374                                     + Integer.toHexString(pa.mPref.mMatch));
4375                             continue;
4376                         }
4377                         // If it's not an "always" type preferred activity and that's what we're
4378                         // looking for, skip it.
4379                         if (always && !pa.mPref.mAlways) {
4380                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4381                             continue;
4382                         }
4383                         final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4384                                 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4385                         if (DEBUG_PREFERRED || debug) {
4386                             Slog.v(TAG, "Found preferred activity:");
4387                             if (ai != null) {
4388                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4389                             } else {
4390                                 Slog.v(TAG, "  null");
4391                             }
4392                         }
4393                         if (ai == null) {
4394                             // This previously registered preferred activity
4395                             // component is no longer known.  Most likely an update
4396                             // to the app was installed and in the new version this
4397                             // component no longer exists.  Clean it up by removing
4398                             // it from the preferred activities list, and skip it.
4399                             Slog.w(TAG, "Removing dangling preferred activity: "
4400                                     + pa.mPref.mComponent);
4401                             pir.removeFilter(pa);
4402                             changed = true;
4403                             continue;
4404                         }
4405                         for (int j=0; j<N; j++) {
4406                             final ResolveInfo ri = query.get(j);
4407                             if (!ri.activityInfo.applicationInfo.packageName
4408                                     .equals(ai.applicationInfo.packageName)) {
4409                                 continue;
4410                             }
4411                             if (!ri.activityInfo.name.equals(ai.name)) {
4412                                 continue;
4413                             }
4414
4415                             if (removeMatches) {
4416                                 pir.removeFilter(pa);
4417                                 changed = true;
4418                                 if (DEBUG_PREFERRED) {
4419                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4420                                 }
4421                                 break;
4422                             }
4423
4424                             // Okay we found a previously set preferred or last chosen app.
4425                             // If the result set is different from when this
4426                             // was created, we need to clear it and re-ask the
4427                             // user their preference, if we're looking for an "always" type entry.
4428                             if (always && !pa.mPref.sameSet(query)) {
4429                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
4430                                         + intent + " type " + resolvedType);
4431                                 if (DEBUG_PREFERRED) {
4432                                     Slog.v(TAG, "Removing preferred activity since set changed "
4433                                             + pa.mPref.mComponent);
4434                                 }
4435                                 pir.removeFilter(pa);
4436                                 // Re-add the filter as a "last chosen" entry (!always)
4437                                 PreferredActivity lastChosen = new PreferredActivity(
4438                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4439                                 pir.addFilter(lastChosen);
4440                                 changed = true;
4441                                 return null;
4442                             }
4443
4444                             // Yay! Either the set matched or we're looking for the last chosen
4445                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4446                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4447                             return ri;
4448                         }
4449                     }
4450                 } finally {
4451                     if (changed) {
4452                         if (DEBUG_PREFERRED) {
4453                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4454                         }
4455                         scheduleWritePackageRestrictionsLocked(userId);
4456                     }
4457                 }
4458             }
4459         }
4460         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4461         return null;
4462     }
4463
4464     /*
4465      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4466      */
4467     @Override
4468     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4469             int targetUserId) {
4470         mContext.enforceCallingOrSelfPermission(
4471                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4472         List<CrossProfileIntentFilter> matches =
4473                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4474         if (matches != null) {
4475             int size = matches.size();
4476             for (int i = 0; i < size; i++) {
4477                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
4478             }
4479         }
4480         if (hasWebURI(intent)) {
4481             // cross-profile app linking works only towards the parent.
4482             final UserInfo parent = getProfileParent(sourceUserId);
4483             synchronized(mPackages) {
4484                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4485                         intent, resolvedType, 0, sourceUserId, parent.id);
4486                 return xpDomainInfo != null;
4487             }
4488         }
4489         return false;
4490     }
4491
4492     private UserInfo getProfileParent(int userId) {
4493         final long identity = Binder.clearCallingIdentity();
4494         try {
4495             return sUserManager.getProfileParent(userId);
4496         } finally {
4497             Binder.restoreCallingIdentity(identity);
4498         }
4499     }
4500
4501     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4502             String resolvedType, int userId) {
4503         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4504         if (resolver != null) {
4505             return resolver.queryIntent(intent, resolvedType, false, userId);
4506         }
4507         return null;
4508     }
4509
4510     @Override
4511     public List<ResolveInfo> queryIntentActivities(Intent intent,
4512             String resolvedType, int flags, int userId) {
4513         if (!sUserManager.exists(userId)) return Collections.emptyList();
4514         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4515         ComponentName comp = intent.getComponent();
4516         if (comp == null) {
4517             if (intent.getSelector() != null) {
4518                 intent = intent.getSelector();
4519                 comp = intent.getComponent();
4520             }
4521         }
4522
4523         if (comp != null) {
4524             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4525             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4526             if (ai != null) {
4527                 final ResolveInfo ri = new ResolveInfo();
4528                 ri.activityInfo = ai;
4529                 list.add(ri);
4530             }
4531             return list;
4532         }
4533
4534         // reader
4535         synchronized (mPackages) {
4536             final String pkgName = intent.getPackage();
4537             if (pkgName == null) {
4538                 List<CrossProfileIntentFilter> matchingFilters =
4539                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4540                 // Check for results that need to skip the current profile.
4541                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4542                         resolvedType, flags, userId);
4543                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4544                     List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4545                     result.add(xpResolveInfo);
4546                     return filterIfNotPrimaryUser(result, userId);
4547                 }
4548
4549                 // Check for results in the current profile.
4550                 List<ResolveInfo> result = mActivities.queryIntent(
4551                         intent, resolvedType, flags, userId);
4552
4553                 // Check for cross profile results.
4554                 xpResolveInfo = queryCrossProfileIntents(
4555                         matchingFilters, intent, resolvedType, flags, userId);
4556                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4557                     result.add(xpResolveInfo);
4558                     Collections.sort(result, mResolvePrioritySorter);
4559                 }
4560                 result = filterIfNotPrimaryUser(result, userId);
4561                 if (hasWebURI(intent)) {
4562                     CrossProfileDomainInfo xpDomainInfo = null;
4563                     final UserInfo parent = getProfileParent(userId);
4564                     if (parent != null) {
4565                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4566                                 flags, userId, parent.id);
4567                     }
4568                     if (xpDomainInfo != null) {
4569                         if (xpResolveInfo != null) {
4570                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
4571                             // in the result.
4572                             result.remove(xpResolveInfo);
4573                         }
4574                         if (result.size() == 0) {
4575                             result.add(xpDomainInfo.resolveInfo);
4576                             return result;
4577                         }
4578                     } else if (result.size() <= 1) {
4579                         return result;
4580                     }
4581                     result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4582                             xpDomainInfo, userId);
4583                     Collections.sort(result, mResolvePrioritySorter);
4584                 }
4585                 return result;
4586             }
4587             final PackageParser.Package pkg = mPackages.get(pkgName);
4588             if (pkg != null) {
4589                 return filterIfNotPrimaryUser(
4590                         mActivities.queryIntentForPackage(
4591                                 intent, resolvedType, flags, pkg.activities, userId),
4592                         userId);
4593             }
4594             return new ArrayList<ResolveInfo>();
4595         }
4596     }
4597
4598     private static class CrossProfileDomainInfo {
4599         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4600         ResolveInfo resolveInfo;
4601         /* Best domain verification status of the activities found in the other profile */
4602         int bestDomainVerificationStatus;
4603     }
4604
4605     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4606             String resolvedType, int flags, int sourceUserId, int parentUserId) {
4607         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4608                 sourceUserId)) {
4609             return null;
4610         }
4611         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4612                 resolvedType, flags, parentUserId);
4613
4614         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4615             return null;
4616         }
4617         CrossProfileDomainInfo result = null;
4618         int size = resultTargetUser.size();
4619         for (int i = 0; i < size; i++) {
4620             ResolveInfo riTargetUser = resultTargetUser.get(i);
4621             // Intent filter verification is only for filters that specify a host. So don't return
4622             // those that handle all web uris.
4623             if (riTargetUser.handleAllWebDataURI) {
4624                 continue;
4625             }
4626             String packageName = riTargetUser.activityInfo.packageName;
4627             PackageSetting ps = mSettings.mPackages.get(packageName);
4628             if (ps == null) {
4629                 continue;
4630             }
4631             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4632             int status = (int)(verificationState >> 32);
4633             if (result == null) {
4634                 result = new CrossProfileDomainInfo();
4635                 result.resolveInfo =
4636                         createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4637                 result.bestDomainVerificationStatus = status;
4638             } else {
4639                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4640                         result.bestDomainVerificationStatus);
4641             }
4642         }
4643         // Don't consider matches with status NEVER across profiles.
4644         if (result != null && result.bestDomainVerificationStatus
4645                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4646             return null;
4647         }
4648         return result;
4649     }
4650
4651     /**
4652      * Verification statuses are ordered from the worse to the best, except for
4653      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4654      */
4655     private int bestDomainVerificationStatus(int status1, int status2) {
4656         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4657             return status2;
4658         }
4659         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4660             return status1;
4661         }
4662         return (int) MathUtils.max(status1, status2);
4663     }
4664
4665     private boolean isUserEnabled(int userId) {
4666         long callingId = Binder.clearCallingIdentity();
4667         try {
4668             UserInfo userInfo = sUserManager.getUserInfo(userId);
4669             return userInfo != null && userInfo.isEnabled();
4670         } finally {
4671             Binder.restoreCallingIdentity(callingId);
4672         }
4673     }
4674
4675     /**
4676      * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4677      *
4678      * @return filtered list
4679      */
4680     private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4681         if (userId == UserHandle.USER_OWNER) {
4682             return resolveInfos;
4683         }
4684         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4685             ResolveInfo info = resolveInfos.get(i);
4686             if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4687                 resolveInfos.remove(i);
4688             }
4689         }
4690         return resolveInfos;
4691     }
4692
4693     private static boolean hasWebURI(Intent intent) {
4694         if (intent.getData() == null) {
4695             return false;
4696         }
4697         final String scheme = intent.getScheme();
4698         if (TextUtils.isEmpty(scheme)) {
4699             return false;
4700         }
4701         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4702     }
4703
4704     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4705             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4706             int userId) {
4707         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4708
4709         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4710             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4711                     candidates.size());
4712         }
4713
4714         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4715         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4716         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4717         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4718         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4719         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4720
4721         synchronized (mPackages) {
4722             final int count = candidates.size();
4723             // First, try to use linked apps. Partition the candidates into four lists:
4724             // one for the final results, one for the "do not use ever", one for "undefined status"
4725             // and finally one for "browser app type".
4726             for (int n=0; n<count; n++) {
4727                 ResolveInfo info = candidates.get(n);
4728                 String packageName = info.activityInfo.packageName;
4729                 PackageSetting ps = mSettings.mPackages.get(packageName);
4730                 if (ps != null) {
4731                     // Add to the special match all list (Browser use case)
4732                     if (info.handleAllWebDataURI) {
4733                         matchAllList.add(info);
4734                         continue;
4735                     }
4736                     // Try to get the status from User settings first
4737                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4738                     int status = (int)(packedStatus >> 32);
4739                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4740                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4741                         if (DEBUG_DOMAIN_VERIFICATION) {
4742                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4743                                     + " : linkgen=" + linkGeneration);
4744                         }
4745                         // Use link-enabled generation as preferredOrder, i.e.
4746                         // prefer newly-enabled over earlier-enabled.
4747                         info.preferredOrder = linkGeneration;
4748                         alwaysList.add(info);
4749                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4750                         if (DEBUG_DOMAIN_VERIFICATION) {
4751                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4752                         }
4753                         neverList.add(info);
4754                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4755                         if (DEBUG_DOMAIN_VERIFICATION) {
4756                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4757                         }
4758                         alwaysAskList.add(info);
4759                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4760                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4761                         if (DEBUG_DOMAIN_VERIFICATION) {
4762                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4763                         }
4764                         undefinedList.add(info);
4765                     }
4766                 }
4767             }
4768
4769             // We'll want to include browser possibilities in a few cases
4770             boolean includeBrowser = false;
4771
4772             // First try to add the "always" resolution(s) for the current user, if any
4773             if (alwaysList.size() > 0) {
4774                 result.addAll(alwaysList);
4775             // if there is an "always" for the parent user, add it.
4776             } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4777                     == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4778                 result.add(xpDomainInfo.resolveInfo);
4779             } else {
4780                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
4781                 result.addAll(undefinedList);
4782                 if (xpDomainInfo != null && (
4783                         xpDomainInfo.bestDomainVerificationStatus
4784                         == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4785                         || xpDomainInfo.bestDomainVerificationStatus
4786                         == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4787                     result.add(xpDomainInfo.resolveInfo);
4788                 }
4789                 includeBrowser = true;
4790             }
4791
4792             // The presence of any 'always ask' alternatives means we'll also offer browsers.
4793             // If there were 'always' entries their preferred order has been set, so we also
4794             // back that off to make the alternatives equivalent
4795             if (alwaysAskList.size() > 0) {
4796                 for (ResolveInfo i : result) {
4797                     i.preferredOrder = 0;
4798                 }
4799                 result.addAll(alwaysAskList);
4800                 includeBrowser = true;
4801             }
4802
4803             if (includeBrowser) {
4804                 // Also add browsers (all of them or only the default one)
4805                 if (DEBUG_DOMAIN_VERIFICATION) {
4806                     Slog.v(TAG, "   ...including browsers in candidate set");
4807                 }
4808                 if ((matchFlags & MATCH_ALL) != 0) {
4809                     result.addAll(matchAllList);
4810                 } else {
4811                     // Browser/generic handling case.  If there's a default browser, go straight
4812                     // to that (but only if there is no other higher-priority match).
4813                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4814                     int maxMatchPrio = 0;
4815                     ResolveInfo defaultBrowserMatch = null;
4816                     final int numCandidates = matchAllList.size();
4817                     for (int n = 0; n < numCandidates; n++) {
4818                         ResolveInfo info = matchAllList.get(n);
4819                         // track the highest overall match priority...
4820                         if (info.priority > maxMatchPrio) {
4821                             maxMatchPrio = info.priority;
4822                         }
4823                         // ...and the highest-priority default browser match
4824                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4825                             if (defaultBrowserMatch == null
4826                                     || (defaultBrowserMatch.priority < info.priority)) {
4827                                 if (debug) {
4828                                     Slog.v(TAG, "Considering default browser match " + info);
4829                                 }
4830                                 defaultBrowserMatch = info;
4831                             }
4832                         }
4833                     }
4834                     if (defaultBrowserMatch != null
4835                             && defaultBrowserMatch.priority >= maxMatchPrio
4836                             && !TextUtils.isEmpty(defaultBrowserPackageName))
4837                     {
4838                         if (debug) {
4839                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4840                         }
4841                         result.add(defaultBrowserMatch);
4842                     } else {
4843                         result.addAll(matchAllList);
4844                     }
4845                 }
4846
4847                 // If there is nothing selected, add all candidates and remove the ones that the user
4848                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4849                 if (result.size() == 0) {
4850                     result.addAll(candidates);
4851                     result.removeAll(neverList);
4852                 }
4853             }
4854         }
4855         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4856             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4857                     result.size());
4858             for (ResolveInfo info : result) {
4859                 Slog.v(TAG, "  + " + info.activityInfo);
4860             }
4861         }
4862         return result;
4863     }
4864
4865     // Returns a packed value as a long:
4866     //
4867     // high 'int'-sized word: link status: undefined/ask/never/always.
4868     // low 'int'-sized word: relative priority among 'always' results.
4869     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4870         long result = ps.getDomainVerificationStatusForUser(userId);
4871         // if none available, get the master status
4872         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4873             if (ps.getIntentFilterVerificationInfo() != null) {
4874                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4875             }
4876         }
4877         return result;
4878     }
4879
4880     private ResolveInfo querySkipCurrentProfileIntents(
4881             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4882             int flags, int sourceUserId) {
4883         if (matchingFilters != null) {
4884             int size = matchingFilters.size();
4885             for (int i = 0; i < size; i ++) {
4886                 CrossProfileIntentFilter filter = matchingFilters.get(i);
4887                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4888                     // Checking if there are activities in the target user that can handle the
4889                     // intent.
4890                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4891                             flags, sourceUserId);
4892                     if (resolveInfo != null) {
4893                         return resolveInfo;
4894                     }
4895                 }
4896             }
4897         }
4898         return null;
4899     }
4900
4901     // Return matching ResolveInfo if any for skip current profile intent filters.
4902     private ResolveInfo queryCrossProfileIntents(
4903             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4904             int flags, int sourceUserId) {
4905         if (matchingFilters != null) {
4906             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4907             // match the same intent. For performance reasons, it is better not to
4908             // run queryIntent twice for the same userId
4909             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4910             int size = matchingFilters.size();
4911             for (int i = 0; i < size; i++) {
4912                 CrossProfileIntentFilter filter = matchingFilters.get(i);
4913                 int targetUserId = filter.getTargetUserId();
4914                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4915                         && !alreadyTriedUserIds.get(targetUserId)) {
4916                     // Checking if there are activities in the target user that can handle the
4917                     // intent.
4918                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4919                             flags, sourceUserId);
4920                     if (resolveInfo != null) return resolveInfo;
4921                     alreadyTriedUserIds.put(targetUserId, true);
4922                 }
4923             }
4924         }
4925         return null;
4926     }
4927
4928     private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4929             String resolvedType, int flags, int sourceUserId) {
4930         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4931                 resolvedType, flags, filter.getTargetUserId());
4932         if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4933             return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4934         }
4935         return null;
4936     }
4937
4938     private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4939             int sourceUserId, int targetUserId) {
4940         ResolveInfo forwardingResolveInfo = new ResolveInfo();
4941         String className;
4942         if (targetUserId == UserHandle.USER_OWNER) {
4943             className = FORWARD_INTENT_TO_USER_OWNER;
4944         } else {
4945             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4946         }
4947         ComponentName forwardingActivityComponentName = new ComponentName(
4948                 mAndroidApplication.packageName, className);
4949         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4950                 sourceUserId);
4951         if (targetUserId == UserHandle.USER_OWNER) {
4952             forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4953             forwardingResolveInfo.noResourceId = true;
4954         }
4955         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4956         forwardingResolveInfo.priority = 0;
4957         forwardingResolveInfo.preferredOrder = 0;
4958         forwardingResolveInfo.match = 0;
4959         forwardingResolveInfo.isDefault = true;
4960         forwardingResolveInfo.filter = filter;
4961         forwardingResolveInfo.targetUserId = targetUserId;
4962         return forwardingResolveInfo;
4963     }
4964
4965     @Override
4966     public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4967             Intent[] specifics, String[] specificTypes, Intent intent,
4968             String resolvedType, int flags, int userId) {
4969         if (!sUserManager.exists(userId)) return Collections.emptyList();
4970         enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4971                 false, "query intent activity options");
4972         final String resultsAction = intent.getAction();
4973
4974         List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4975                 | PackageManager.GET_RESOLVED_FILTER, userId);
4976
4977         if (DEBUG_INTENT_MATCHING) {
4978             Log.v(TAG, "Query " + intent + ": " + results);
4979         }
4980
4981         int specificsPos = 0;
4982         int N;
4983
4984         // todo: note that the algorithm used here is O(N^2).  This
4985         // isn't a problem in our current environment, but if we start running
4986         // into situations where we have more than 5 or 10 matches then this
4987         // should probably be changed to something smarter...
4988
4989         // First we go through and resolve each of the specific items
4990         // that were supplied, taking care of removing any corresponding
4991         // duplicate items in the generic resolve list.
4992         if (specifics != null) {
4993             for (int i=0; i<specifics.length; i++) {
4994                 final Intent sintent = specifics[i];
4995                 if (sintent == null) {
4996                     continue;
4997                 }
4998
4999                 if (DEBUG_INTENT_MATCHING) {
5000                     Log.v(TAG, "Specific #" + i + ": " + sintent);
5001                 }
5002
5003                 String action = sintent.getAction();
5004                 if (resultsAction != null && resultsAction.equals(action)) {
5005                     // If this action was explicitly requested, then don't
5006                     // remove things that have it.
5007                     action = null;
5008                 }
5009
5010                 ResolveInfo ri = null;
5011                 ActivityInfo ai = null;
5012
5013                 ComponentName comp = sintent.getComponent();
5014                 if (comp == null) {
5015                     ri = resolveIntent(
5016                         sintent,
5017                         specificTypes != null ? specificTypes[i] : null,
5018                             flags, userId);
5019                     if (ri == null) {
5020                         continue;
5021                     }
5022                     if (ri == mResolveInfo) {
5023                         // ACK!  Must do something better with this.
5024                     }
5025                     ai = ri.activityInfo;
5026                     comp = new ComponentName(ai.applicationInfo.packageName,
5027                             ai.name);
5028                 } else {
5029                     ai = getActivityInfo(comp, flags, userId);
5030                     if (ai == null) {
5031                         continue;
5032                     }
5033                 }
5034
5035                 // Look for any generic query activities that are duplicates
5036                 // of this specific one, and remove them from the results.
5037                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5038                 N = results.size();
5039                 int j;
5040                 for (j=specificsPos; j<N; j++) {
5041                     ResolveInfo sri = results.get(j);
5042                     if ((sri.activityInfo.name.equals(comp.getClassName())
5043                             && sri.activityInfo.applicationInfo.packageName.equals(
5044                                     comp.getPackageName()))
5045                         || (action != null && sri.filter.matchAction(action))) {
5046                         results.remove(j);
5047                         if (DEBUG_INTENT_MATCHING) Log.v(
5048                             TAG, "Removing duplicate item from " + j
5049                             + " due to specific " + specificsPos);
5050                         if (ri == null) {
5051                             ri = sri;
5052                         }
5053                         j--;
5054                         N--;
5055                     }
5056                 }
5057
5058                 // Add this specific item to its proper place.
5059                 if (ri == null) {
5060                     ri = new ResolveInfo();
5061                     ri.activityInfo = ai;
5062                 }
5063                 results.add(specificsPos, ri);
5064                 ri.specificIndex = i;
5065                 specificsPos++;
5066             }
5067         }
5068
5069         // Now we go through the remaining generic results and remove any
5070         // duplicate actions that are found here.
5071         N = results.size();
5072         for (int i=specificsPos; i<N-1; i++) {
5073             final ResolveInfo rii = results.get(i);
5074             if (rii.filter == null) {
5075                 continue;
5076             }
5077
5078             // Iterate over all of the actions of this result's intent
5079             // filter...  typically this should be just one.
5080             final Iterator<String> it = rii.filter.actionsIterator();
5081             if (it == null) {
5082                 continue;
5083             }
5084             while (it.hasNext()) {
5085                 final String action = it.next();
5086                 if (resultsAction != null && resultsAction.equals(action)) {
5087                     // If this action was explicitly requested, then don't
5088                     // remove things that have it.
5089                     continue;
5090                 }
5091                 for (int j=i+1; j<N; j++) {
5092                     final ResolveInfo rij = results.get(j);
5093                     if (rij.filter != null && rij.filter.hasAction(action)) {
5094                         results.remove(j);
5095                         if (DEBUG_INTENT_MATCHING) Log.v(
5096                             TAG, "Removing duplicate item from " + j
5097                             + " due to action " + action + " at " + i);
5098                         j--;
5099                         N--;
5100                     }
5101                 }
5102             }
5103
5104             // If the caller didn't request filter information, drop it now
5105             // so we don't have to marshall/unmarshall it.
5106             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5107                 rii.filter = null;
5108             }
5109         }
5110
5111         // Filter out the caller activity if so requested.
5112         if (caller != null) {
5113             N = results.size();
5114             for (int i=0; i<N; i++) {
5115                 ActivityInfo ainfo = results.get(i).activityInfo;
5116                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5117                         && caller.getClassName().equals(ainfo.name)) {
5118                     results.remove(i);
5119                     break;
5120                 }
5121             }
5122         }
5123
5124         // If the caller didn't request filter information,
5125         // drop them now so we don't have to
5126         // marshall/unmarshall it.
5127         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5128             N = results.size();
5129             for (int i=0; i<N; i++) {
5130                 results.get(i).filter = null;
5131             }
5132         }
5133
5134         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5135         return results;
5136     }
5137
5138     @Override
5139     public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5140             int userId) {
5141         if (!sUserManager.exists(userId)) return Collections.emptyList();
5142         ComponentName comp = intent.getComponent();
5143         if (comp == null) {
5144             if (intent.getSelector() != null) {
5145                 intent = intent.getSelector();
5146                 comp = intent.getComponent();
5147             }
5148         }
5149         if (comp != null) {
5150             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5151             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5152             if (ai != null) {
5153                 ResolveInfo ri = new ResolveInfo();
5154                 ri.activityInfo = ai;
5155                 list.add(ri);
5156             }
5157             return list;
5158         }
5159
5160         // reader
5161         synchronized (mPackages) {
5162             String pkgName = intent.getPackage();
5163             if (pkgName == null) {
5164                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5165             }
5166             final PackageParser.Package pkg = mPackages.get(pkgName);
5167             if (pkg != null) {
5168                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5169                         userId);
5170             }
5171             return null;
5172         }
5173     }
5174
5175     @Override
5176     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5177         List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5178         if (!sUserManager.exists(userId)) return null;
5179         if (query != null) {
5180             if (query.size() >= 1) {
5181                 // If there is more than one service with the same priority,
5182                 // just arbitrarily pick the first one.
5183                 return query.get(0);
5184             }
5185         }
5186         return null;
5187     }
5188
5189     @Override
5190     public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5191             int userId) {
5192         if (!sUserManager.exists(userId)) return Collections.emptyList();
5193         ComponentName comp = intent.getComponent();
5194         if (comp == null) {
5195             if (intent.getSelector() != null) {
5196                 intent = intent.getSelector();
5197                 comp = intent.getComponent();
5198             }
5199         }
5200         if (comp != null) {
5201             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5202             final ServiceInfo si = getServiceInfo(comp, flags, userId);
5203             if (si != null) {
5204                 final ResolveInfo ri = new ResolveInfo();
5205                 ri.serviceInfo = si;
5206                 list.add(ri);
5207             }
5208             return list;
5209         }
5210
5211         // reader
5212         synchronized (mPackages) {
5213             String pkgName = intent.getPackage();
5214             if (pkgName == null) {
5215                 return mServices.queryIntent(intent, resolvedType, flags, userId);
5216             }
5217             final PackageParser.Package pkg = mPackages.get(pkgName);
5218             if (pkg != null) {
5219                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5220                         userId);
5221             }
5222             return null;
5223         }
5224     }
5225
5226     @Override
5227     public List<ResolveInfo> queryIntentContentProviders(
5228             Intent intent, String resolvedType, int flags, int userId) {
5229         if (!sUserManager.exists(userId)) return Collections.emptyList();
5230         ComponentName comp = intent.getComponent();
5231         if (comp == null) {
5232             if (intent.getSelector() != null) {
5233                 intent = intent.getSelector();
5234                 comp = intent.getComponent();
5235             }
5236         }
5237         if (comp != null) {
5238             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5239             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5240             if (pi != null) {
5241                 final ResolveInfo ri = new ResolveInfo();
5242                 ri.providerInfo = pi;
5243                 list.add(ri);
5244             }
5245             return list;
5246         }
5247
5248         // reader
5249         synchronized (mPackages) {
5250             String pkgName = intent.getPackage();
5251             if (pkgName == null) {
5252                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
5253             }
5254             final PackageParser.Package pkg = mPackages.get(pkgName);
5255             if (pkg != null) {
5256                 return mProviders.queryIntentForPackage(
5257                         intent, resolvedType, flags, pkg.providers, userId);
5258             }
5259             return null;
5260         }
5261     }
5262
5263     @Override
5264     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5265         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5266
5267         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5268
5269         // writer
5270         synchronized (mPackages) {
5271             ArrayList<PackageInfo> list;
5272             if (listUninstalled) {
5273                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5274                 for (PackageSetting ps : mSettings.mPackages.values()) {
5275                     PackageInfo pi;
5276                     if (ps.pkg != null) {
5277                         pi = generatePackageInfo(ps.pkg, flags, userId);
5278                     } else {
5279                         pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5280                     }
5281                     if (pi != null) {
5282                         list.add(pi);
5283                     }
5284                 }
5285             } else {
5286                 list = new ArrayList<PackageInfo>(mPackages.size());
5287                 for (PackageParser.Package p : mPackages.values()) {
5288                     PackageInfo pi = generatePackageInfo(p, flags, userId);
5289                     if (pi != null) {
5290                         list.add(pi);
5291                     }
5292                 }
5293             }
5294
5295             return new ParceledListSlice<PackageInfo>(list);
5296         }
5297     }
5298
5299     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5300             String[] permissions, boolean[] tmp, int flags, int userId) {
5301         int numMatch = 0;
5302         final PermissionsState permissionsState = ps.getPermissionsState();
5303         for (int i=0; i<permissions.length; i++) {
5304             final String permission = permissions[i];
5305             if (permissionsState.hasPermission(permission, userId)) {
5306                 tmp[i] = true;
5307                 numMatch++;
5308             } else {
5309                 tmp[i] = false;
5310             }
5311         }
5312         if (numMatch == 0) {
5313             return;
5314         }
5315         PackageInfo pi;
5316         if (ps.pkg != null) {
5317             pi = generatePackageInfo(ps.pkg, flags, userId);
5318         } else {
5319             pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5320         }
5321         // The above might return null in cases of uninstalled apps or install-state
5322         // skew across users/profiles.
5323         if (pi != null) {
5324             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5325                 if (numMatch == permissions.length) {
5326                     pi.requestedPermissions = permissions;
5327                 } else {
5328                     pi.requestedPermissions = new String[numMatch];
5329                     numMatch = 0;
5330                     for (int i=0; i<permissions.length; i++) {
5331                         if (tmp[i]) {
5332                             pi.requestedPermissions[numMatch] = permissions[i];
5333                             numMatch++;
5334                         }
5335                     }
5336                 }
5337             }
5338             list.add(pi);
5339         }
5340     }
5341
5342     @Override
5343     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5344             String[] permissions, int flags, int userId) {
5345         if (!sUserManager.exists(userId)) return null;
5346         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5347
5348         // writer
5349         synchronized (mPackages) {
5350             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5351             boolean[] tmpBools = new boolean[permissions.length];
5352             if (listUninstalled) {
5353                 for (PackageSetting ps : mSettings.mPackages.values()) {
5354                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5355                 }
5356             } else {
5357                 for (PackageParser.Package pkg : mPackages.values()) {
5358                     PackageSetting ps = (PackageSetting)pkg.mExtras;
5359                     if (ps != null) {
5360                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5361                                 userId);
5362                     }
5363                 }
5364             }
5365
5366             return new ParceledListSlice<PackageInfo>(list);
5367         }
5368     }
5369
5370     @Override
5371     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5372         if (!sUserManager.exists(userId)) return null;
5373         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5374
5375         // writer
5376         synchronized (mPackages) {
5377             ArrayList<ApplicationInfo> list;
5378             if (listUninstalled) {
5379                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5380                 for (PackageSetting ps : mSettings.mPackages.values()) {
5381                     ApplicationInfo ai;
5382                     if (ps.pkg != null) {
5383                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5384                                 ps.readUserState(userId), userId);
5385                     } else {
5386                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5387                     }
5388                     if (ai != null) {
5389                         list.add(ai);
5390                     }
5391                 }
5392             } else {
5393                 list = new ArrayList<ApplicationInfo>(mPackages.size());
5394                 for (PackageParser.Package p : mPackages.values()) {
5395                     if (p.mExtras != null) {
5396                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5397                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
5398                         if (ai != null) {
5399                             list.add(ai);
5400                         }
5401                     }
5402                 }
5403             }
5404
5405             return new ParceledListSlice<ApplicationInfo>(list);
5406         }
5407     }
5408
5409     public List<ApplicationInfo> getPersistentApplications(int flags) {
5410         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5411
5412         // reader
5413         synchronized (mPackages) {
5414             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5415             final int userId = UserHandle.getCallingUserId();
5416             while (i.hasNext()) {
5417                 final PackageParser.Package p = i.next();
5418                 if (p.applicationInfo != null
5419                         && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5420                         && (!mSafeMode || isSystemApp(p))) {
5421                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
5422                     if (ps != null) {
5423                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5424                                 ps.readUserState(userId), userId);
5425                         if (ai != null) {
5426                             finalList.add(ai);
5427                         }
5428                     }
5429                 }
5430             }
5431         }
5432
5433         return finalList;
5434     }
5435
5436     @Override
5437     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5438         if (!sUserManager.exists(userId)) return null;
5439         // reader
5440         synchronized (mPackages) {
5441             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5442             PackageSetting ps = provider != null
5443                     ? mSettings.mPackages.get(provider.owner.packageName)
5444                     : null;
5445             return ps != null
5446                     && mSettings.isEnabledLPr(provider.info, flags, userId)
5447                     && (!mSafeMode || (provider.info.applicationInfo.flags
5448                             &ApplicationInfo.FLAG_SYSTEM) != 0)
5449                     ? PackageParser.generateProviderInfo(provider, flags,
5450                             ps.readUserState(userId), userId)
5451                     : null;
5452         }
5453     }
5454
5455     /**
5456      * @deprecated
5457      */
5458     @Deprecated
5459     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5460         // reader
5461         synchronized (mPackages) {
5462             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5463                     .entrySet().iterator();
5464             final int userId = UserHandle.getCallingUserId();
5465             while (i.hasNext()) {
5466                 Map.Entry<String, PackageParser.Provider> entry = i.next();
5467                 PackageParser.Provider p = entry.getValue();
5468                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5469
5470                 if (ps != null && p.syncable
5471                         && (!mSafeMode || (p.info.applicationInfo.flags
5472                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5473                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5474                             ps.readUserState(userId), userId);
5475                     if (info != null) {
5476                         outNames.add(entry.getKey());
5477                         outInfo.add(info);
5478                     }
5479                 }
5480             }
5481         }
5482     }
5483
5484     @Override
5485     public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5486             int uid, int flags) {
5487         ArrayList<ProviderInfo> finalList = null;
5488         // reader
5489         synchronized (mPackages) {
5490             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5491             final int userId = processName != null ?
5492                     UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5493             while (i.hasNext()) {
5494                 final PackageParser.Provider p = i.next();
5495                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5496                 if (ps != null && p.info.authority != null
5497                         && (processName == null
5498                                 || (p.info.processName.equals(processName)
5499                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5500                         && mSettings.isEnabledLPr(p.info, flags, userId)
5501                         && (!mSafeMode
5502                                 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5503                     if (finalList == null) {
5504                         finalList = new ArrayList<ProviderInfo>(3);
5505                     }
5506                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5507                             ps.readUserState(userId), userId);
5508                     if (info != null) {
5509                         finalList.add(info);
5510                     }
5511                 }
5512             }
5513         }
5514
5515         if (finalList != null) {
5516             Collections.sort(finalList, mProviderInitOrderSorter);
5517             return new ParceledListSlice<ProviderInfo>(finalList);
5518         }
5519
5520         return null;
5521     }
5522
5523     @Override
5524     public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5525             int flags) {
5526         // reader
5527         synchronized (mPackages) {
5528             final PackageParser.Instrumentation i = mInstrumentation.get(name);
5529             return PackageParser.generateInstrumentationInfo(i, flags);
5530         }
5531     }
5532
5533     @Override
5534     public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5535             int flags) {
5536         ArrayList<InstrumentationInfo> finalList =
5537             new ArrayList<InstrumentationInfo>();
5538
5539         // reader
5540         synchronized (mPackages) {
5541             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5542             while (i.hasNext()) {
5543                 final PackageParser.Instrumentation p = i.next();
5544                 if (targetPackage == null
5545                         || targetPackage.equals(p.info.targetPackage)) {
5546                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5547                             flags);
5548                     if (ii != null) {
5549                         finalList.add(ii);
5550                     }
5551                 }
5552             }
5553         }
5554
5555         return finalList;
5556     }
5557
5558     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5559         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5560         if (overlays == null) {
5561             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5562             return;
5563         }
5564         for (PackageParser.Package opkg : overlays.values()) {
5565             // Not much to do if idmap fails: we already logged the error
5566             // and we certainly don't want to abort installation of pkg simply
5567             // because an overlay didn't fit properly. For these reasons,
5568             // ignore the return value of createIdmapForPackagePairLI.
5569             createIdmapForPackagePairLI(pkg, opkg);
5570         }
5571     }
5572
5573     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5574             PackageParser.Package opkg) {
5575         if (!opkg.mTrustedOverlay) {
5576             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5577                     opkg.baseCodePath + ": overlay not trusted");
5578             return false;
5579         }
5580         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5581         if (overlaySet == null) {
5582             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5583                     opkg.baseCodePath + " but target package has no known overlays");
5584             return false;
5585         }
5586         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5587         // TODO: generate idmap for split APKs
5588         if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5589             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5590                     + opkg.baseCodePath);
5591             return false;
5592         }
5593         PackageParser.Package[] overlayArray =
5594             overlaySet.values().toArray(new PackageParser.Package[0]);
5595         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5596             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5597                 return p1.mOverlayPriority - p2.mOverlayPriority;
5598             }
5599         };
5600         Arrays.sort(overlayArray, cmp);
5601
5602         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5603         int i = 0;
5604         for (PackageParser.Package p : overlayArray) {
5605             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5606         }
5607         return true;
5608     }
5609
5610     private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5611         final File[] files = dir.listFiles();
5612         if (ArrayUtils.isEmpty(files)) {
5613             Log.d(TAG, "No files in app dir " + dir);
5614             return;
5615         }
5616
5617         if (DEBUG_PACKAGE_SCANNING) {
5618             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5619                     + " flags=0x" + Integer.toHexString(parseFlags));
5620         }
5621
5622         for (File file : files) {
5623             final boolean isPackage = (isApkFile(file) || file.isDirectory())
5624                     && !PackageInstallerService.isStageName(file.getName());
5625             if (!isPackage) {
5626                 // Ignore entries which are not packages
5627                 continue;
5628             }
5629             try {
5630                 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5631                         scanFlags, currentTime, null);
5632             } catch (PackageManagerException e) {
5633                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5634
5635                 // Delete invalid userdata apps
5636                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5637                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5638                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5639                     if (file.isDirectory()) {
5640                         mInstaller.rmPackageDir(file.getAbsolutePath());
5641                     } else {
5642                         file.delete();
5643                     }
5644                 }
5645             }
5646         }
5647     }
5648
5649     private static File getSettingsProblemFile() {
5650         File dataDir = Environment.getDataDirectory();
5651         File systemDir = new File(dataDir, "system");
5652         File fname = new File(systemDir, "uiderrors.txt");
5653         return fname;
5654     }
5655
5656     static void reportSettingsProblem(int priority, String msg) {
5657         logCriticalInfo(priority, msg);
5658     }
5659
5660     static void logCriticalInfo(int priority, String msg) {
5661         Slog.println(priority, TAG, msg);
5662         EventLogTags.writePmCriticalInfo(msg);
5663         try {
5664             File fname = getSettingsProblemFile();
5665             FileOutputStream out = new FileOutputStream(fname, true);
5666             PrintWriter pw = new FastPrintWriter(out);
5667             SimpleDateFormat formatter = new SimpleDateFormat();
5668             String dateString = formatter.format(new Date(System.currentTimeMillis()));
5669             pw.println(dateString + ": " + msg);
5670             pw.close();
5671             FileUtils.setPermissions(
5672                     fname.toString(),
5673                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5674                     -1, -1);
5675         } catch (java.io.IOException e) {
5676         }
5677     }
5678
5679     private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5680             PackageParser.Package pkg, File srcFile, int parseFlags)
5681             throws PackageManagerException {
5682         if (ps != null
5683                 && ps.codePath.equals(srcFile)
5684                 && ps.timeStamp == srcFile.lastModified()
5685                 && !isCompatSignatureUpdateNeeded(pkg)
5686                 && !isRecoverSignatureUpdateNeeded(pkg)) {
5687             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5688             KeySetManagerService ksms = mSettings.mKeySetManagerService;
5689             ArraySet<PublicKey> signingKs;
5690             synchronized (mPackages) {
5691                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5692             }
5693             if (ps.signatures.mSignatures != null
5694                     && ps.signatures.mSignatures.length != 0
5695                     && signingKs != null) {
5696                 // Optimization: reuse the existing cached certificates
5697                 // if the package appears to be unchanged.
5698                 pkg.mSignatures = ps.signatures.mSignatures;
5699                 pkg.mSigningKeys = signingKs;
5700                 return;
5701             }
5702
5703             Slog.w(TAG, "PackageSetting for " + ps.name
5704                     + " is missing signatures.  Collecting certs again to recover them.");
5705         } else {
5706             Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5707         }
5708
5709         try {
5710             pp.collectCertificates(pkg, parseFlags);
5711             pp.collectManifestDigest(pkg);
5712         } catch (PackageParserException e) {
5713             throw PackageManagerException.from(e);
5714         }
5715     }
5716
5717     /*
5718      *  Scan a package and return the newly parsed package.
5719      *  Returns null in case of errors and the error code is stored in mLastScanError
5720      */
5721     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5722             long currentTime, UserHandle user) throws PackageManagerException {
5723         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5724         parseFlags |= mDefParseFlags;
5725         PackageParser pp = new PackageParser();
5726         pp.setSeparateProcesses(mSeparateProcesses);
5727         pp.setOnlyCoreApps(mOnlyCore);
5728         pp.setDisplayMetrics(mMetrics);
5729
5730         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5731             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5732         }
5733
5734         final PackageParser.Package pkg;
5735         try {
5736             pkg = pp.parsePackage(scanFile, parseFlags);
5737         } catch (PackageParserException e) {
5738             throw PackageManagerException.from(e);
5739         }
5740
5741         PackageSetting ps = null;
5742         PackageSetting updatedPkg;
5743         // reader
5744         synchronized (mPackages) {
5745             // Look to see if we already know about this package.
5746             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5747             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5748                 // This package has been renamed to its original name.  Let's
5749                 // use that.
5750                 ps = mSettings.peekPackageLPr(oldName);
5751             }
5752             // If there was no original package, see one for the real package name.
5753             if (ps == null) {
5754                 ps = mSettings.peekPackageLPr(pkg.packageName);
5755             }
5756             // Check to see if this package could be hiding/updating a system
5757             // package.  Must look for it either under the original or real
5758             // package name depending on our state.
5759             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5760             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5761         }
5762         boolean updatedPkgBetter = false;
5763         // First check if this is a system package that may involve an update
5764         if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5765             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5766             // it needs to drop FLAG_PRIVILEGED.
5767             if (locationIsPrivileged(scanFile)) {
5768                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5769             } else {
5770                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5771             }
5772
5773             if (ps != null && !ps.codePath.equals(scanFile)) {
5774                 // The path has changed from what was last scanned...  check the
5775                 // version of the new path against what we have stored to determine
5776                 // what to do.
5777                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5778                 if (pkg.mVersionCode <= ps.versionCode) {
5779                     // The system package has been updated and the code path does not match
5780                     // Ignore entry. Skip it.
5781                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5782                             + " ignored: updated version " + ps.versionCode
5783                             + " better than this " + pkg.mVersionCode);
5784                     if (!updatedPkg.codePath.equals(scanFile)) {
5785                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5786                                 + ps.name + " changing from " + updatedPkg.codePathString
5787                                 + " to " + scanFile);
5788                         updatedPkg.codePath = scanFile;
5789                         updatedPkg.codePathString = scanFile.toString();
5790                         updatedPkg.resourcePath = scanFile;
5791                         updatedPkg.resourcePathString = scanFile.toString();
5792                     }
5793                     updatedPkg.pkg = pkg;
5794                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5795                             "Package " + ps.name + " at " + scanFile
5796                                     + " ignored: updated version " + ps.versionCode
5797                                     + " better than this " + pkg.mVersionCode);
5798                 } else {
5799                     // The current app on the system partition is better than
5800                     // what we have updated to on the data partition; switch
5801                     // back to the system partition version.
5802                     // At this point, its safely assumed that package installation for
5803                     // apps in system partition will go through. If not there won't be a working
5804                     // version of the app
5805                     // writer
5806                     synchronized (mPackages) {
5807                         // Just remove the loaded entries from package lists.
5808                         mPackages.remove(ps.name);
5809                     }
5810
5811                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5812                             + " reverting from " + ps.codePathString
5813                             + ": new version " + pkg.mVersionCode
5814                             + " better than installed " + ps.versionCode);
5815
5816                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5817                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5818                     synchronized (mInstallLock) {
5819                         args.cleanUpResourcesLI();
5820                     }
5821                     synchronized (mPackages) {
5822                         mSettings.enableSystemPackageLPw(ps.name);
5823                     }
5824                     updatedPkgBetter = true;
5825                 }
5826             }
5827         }
5828
5829         if (updatedPkg != null) {
5830             // An updated system app will not have the PARSE_IS_SYSTEM flag set
5831             // initially
5832             parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5833
5834             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5835             // flag set initially
5836             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5837                 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5838             }
5839         }
5840
5841         // Verify certificates against what was last scanned
5842         collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5843
5844         /*
5845          * A new system app appeared, but we already had a non-system one of the
5846          * same name installed earlier.
5847          */
5848         boolean shouldHideSystemApp = false;
5849         if (updatedPkg == null && ps != null
5850                 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5851             /*
5852              * Check to make sure the signatures match first. If they don't,
5853              * wipe the installed application and its data.
5854              */
5855             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5856                     != PackageManager.SIGNATURE_MATCH) {
5857                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5858                         + " signatures don't match existing userdata copy; removing");
5859                 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5860                 ps = null;
5861             } else {
5862                 /*
5863                  * If the newly-added system app is an older version than the
5864                  * already installed version, hide it. It will be scanned later
5865                  * and re-added like an update.
5866                  */
5867                 if (pkg.mVersionCode <= ps.versionCode) {
5868                     shouldHideSystemApp = true;
5869                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5870                             + " but new version " + pkg.mVersionCode + " better than installed "
5871                             + ps.versionCode + "; hiding system");
5872                 } else {
5873                     /*
5874                      * The newly found system app is a newer version that the
5875                      * one previously installed. Simply remove the
5876                      * already-installed application and replace it with our own
5877                      * while keeping the application data.
5878                      */
5879                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5880                             + " reverting from " + ps.codePathString + ": new version "
5881                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
5882                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5883                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5884                     synchronized (mInstallLock) {
5885                         args.cleanUpResourcesLI();
5886                     }
5887                 }
5888             }
5889         }
5890
5891         // The apk is forward locked (not public) if its code and resources
5892         // are kept in different files. (except for app in either system or
5893         // vendor path).
5894         // TODO grab this value from PackageSettings
5895         if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5896             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5897                 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5898             }
5899         }
5900
5901         // TODO: extend to support forward-locked splits
5902         String resourcePath = null;
5903         String baseResourcePath = null;
5904         if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5905             if (ps != null && ps.resourcePathString != null) {
5906                 resourcePath = ps.resourcePathString;
5907                 baseResourcePath = ps.resourcePathString;
5908             } else {
5909                 // Should not happen at all. Just log an error.
5910                 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5911             }
5912         } else {
5913             resourcePath = pkg.codePath;
5914             baseResourcePath = pkg.baseCodePath;
5915         }
5916
5917         // Set application objects path explicitly.
5918         pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5919         pkg.applicationInfo.setCodePath(pkg.codePath);
5920         pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5921         pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5922         pkg.applicationInfo.setResourcePath(resourcePath);
5923         pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5924         pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5925
5926         // Note that we invoke the following method only if we are about to unpack an application
5927         PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5928                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
5929
5930         /*
5931          * If the system app should be overridden by a previously installed
5932          * data, hide the system app now and let the /data/app scan pick it up
5933          * again.
5934          */
5935         if (shouldHideSystemApp) {
5936             synchronized (mPackages) {
5937                 mSettings.disableSystemPackageLPw(pkg.packageName);
5938             }
5939         }
5940
5941         return scannedPkg;
5942     }
5943
5944     private static String fixProcessName(String defProcessName,
5945             String processName, int uid) {
5946         if (processName == null) {
5947             return defProcessName;
5948         }
5949         return processName;
5950     }
5951
5952     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5953             throws PackageManagerException {
5954         if (pkgSetting.signatures.mSignatures != null) {
5955             // Already existing package. Make sure signatures match
5956             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5957                     == PackageManager.SIGNATURE_MATCH;
5958             if (!match) {
5959                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5960                         == PackageManager.SIGNATURE_MATCH;
5961             }
5962             if (!match) {
5963                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5964                         == PackageManager.SIGNATURE_MATCH;
5965             }
5966             if (!match) {
5967                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5968                         + pkg.packageName + " signatures do not match the "
5969                         + "previously installed version; ignoring!");
5970             }
5971         }
5972
5973         // Check for shared user signatures
5974         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5975             // Already existing package. Make sure signatures match
5976             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5977                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5978             if (!match) {
5979                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5980                         == PackageManager.SIGNATURE_MATCH;
5981             }
5982             if (!match) {
5983                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5984                         == PackageManager.SIGNATURE_MATCH;
5985             }
5986             if (!match) {
5987                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5988                         "Package " + pkg.packageName
5989                         + " has no signatures that match those in shared user "
5990                         + pkgSetting.sharedUser.name + "; ignoring!");
5991             }
5992         }
5993     }
5994
5995     /**
5996      * Enforces that only the system UID or root's UID can call a method exposed
5997      * via Binder.
5998      *
5999      * @param message used as message if SecurityException is thrown
6000      * @throws SecurityException if the caller is not system or root
6001      */
6002     private static final void enforceSystemOrRoot(String message) {
6003         final int uid = Binder.getCallingUid();
6004         if (uid != Process.SYSTEM_UID && uid != 0) {
6005             throw new SecurityException(message);
6006         }
6007     }
6008
6009     @Override
6010     public void performBootDexOpt() {
6011         enforceSystemOrRoot("Only the system can request dexopt be performed");
6012
6013         // Before everything else, see whether we need to fstrim.
6014         try {
6015             IMountService ms = PackageHelper.getMountService();
6016             if (ms != null) {
6017                 final boolean isUpgrade = isUpgrade();
6018                 boolean doTrim = isUpgrade;
6019                 if (doTrim) {
6020                     Slog.w(TAG, "Running disk maintenance immediately due to system update");
6021                 } else {
6022                     final long interval = android.provider.Settings.Global.getLong(
6023                             mContext.getContentResolver(),
6024                             android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6025                             DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6026                     if (interval > 0) {
6027                         final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6028                         if (timeSinceLast > interval) {
6029                             doTrim = true;
6030                             Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6031                                     + "; running immediately");
6032                         }
6033                     }
6034                 }
6035                 if (doTrim) {
6036                     if (!isFirstBoot()) {
6037                         try {
6038                             ActivityManagerNative.getDefault().showBootMessage(
6039                                     mContext.getResources().getString(
6040                                             R.string.android_upgrading_fstrim), true);
6041                         } catch (RemoteException e) {
6042                         }
6043                     }
6044                     ms.runMaintenance();
6045                 }
6046             } else {
6047                 Slog.e(TAG, "Mount service unavailable!");
6048             }
6049         } catch (RemoteException e) {
6050             // Can't happen; MountService is local
6051         }
6052
6053         final ArraySet<PackageParser.Package> pkgs;
6054         synchronized (mPackages) {
6055             pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6056         }
6057
6058         if (pkgs != null) {
6059             // Sort apps by importance for dexopt ordering. Important apps are given more priority
6060             // in case the device runs out of space.
6061             ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6062             // Give priority to core apps.
6063             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6064                 PackageParser.Package pkg = it.next();
6065                 if (pkg.coreApp) {
6066                     if (DEBUG_DEXOPT) {
6067                         Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6068                     }
6069                     sortedPkgs.add(pkg);
6070                     it.remove();
6071                 }
6072             }
6073             // Give priority to system apps that listen for pre boot complete.
6074             Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6075             ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6076             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6077                 PackageParser.Package pkg = it.next();
6078                 if (pkgNames.contains(pkg.packageName)) {
6079                     if (DEBUG_DEXOPT) {
6080                         Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6081                     }
6082                     sortedPkgs.add(pkg);
6083                     it.remove();
6084                 }
6085             }
6086             // Give priority to system apps.
6087             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6088                 PackageParser.Package pkg = it.next();
6089                 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6090                     if (DEBUG_DEXOPT) {
6091                         Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6092                     }
6093                     sortedPkgs.add(pkg);
6094                     it.remove();
6095                 }
6096             }
6097             // Give priority to updated system apps.
6098             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6099                 PackageParser.Package pkg = it.next();
6100                 if (pkg.isUpdatedSystemApp()) {
6101                     if (DEBUG_DEXOPT) {
6102                         Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6103                     }
6104                     sortedPkgs.add(pkg);
6105                     it.remove();
6106                 }
6107             }
6108             // Give priority to apps that listen for boot complete.
6109             intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6110             pkgNames = getPackageNamesForIntent(intent);
6111             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6112                 PackageParser.Package pkg = it.next();
6113                 if (pkgNames.contains(pkg.packageName)) {
6114                     if (DEBUG_DEXOPT) {
6115                         Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6116                     }
6117                     sortedPkgs.add(pkg);
6118                     it.remove();
6119                 }
6120             }
6121             // Filter out packages that aren't recently used.
6122             filterRecentlyUsedApps(pkgs);
6123             // Add all remaining apps.
6124             for (PackageParser.Package pkg : pkgs) {
6125                 if (DEBUG_DEXOPT) {
6126                     Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6127                 }
6128                 sortedPkgs.add(pkg);
6129             }
6130
6131             // If we want to be lazy, filter everything that wasn't recently used.
6132             if (mLazyDexOpt) {
6133                 filterRecentlyUsedApps(sortedPkgs);
6134             }
6135
6136             int i = 0;
6137             int total = sortedPkgs.size();
6138             File dataDir = Environment.getDataDirectory();
6139             long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6140             if (lowThreshold == 0) {
6141                 throw new IllegalStateException("Invalid low memory threshold");
6142             }
6143             for (PackageParser.Package pkg : sortedPkgs) {
6144                 long usableSpace = dataDir.getUsableSpace();
6145                 if (usableSpace < lowThreshold) {
6146                     Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6147                     break;
6148                 }
6149                 performBootDexOpt(pkg, ++i, total);
6150             }
6151         }
6152     }
6153
6154     private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6155         // Filter out packages that aren't recently used.
6156         //
6157         // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6158         // should do a full dexopt.
6159         if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6160             int total = pkgs.size();
6161             int skipped = 0;
6162             long now = System.currentTimeMillis();
6163             for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6164                 PackageParser.Package pkg = i.next();
6165                 long then = pkg.mLastPackageUsageTimeInMills;
6166                 if (then + mDexOptLRUThresholdInMills < now) {
6167                     if (DEBUG_DEXOPT) {
6168                         Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6169                               ((then == 0) ? "never" : new Date(then)));
6170                     }
6171                     i.remove();
6172                     skipped++;
6173                 }
6174             }
6175             if (DEBUG_DEXOPT) {
6176                 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6177             }
6178         }
6179     }
6180
6181     private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6182         List<ResolveInfo> ris = null;
6183         try {
6184             ris = AppGlobals.getPackageManager().queryIntentReceivers(
6185                     intent, null, 0, UserHandle.USER_OWNER);
6186         } catch (RemoteException e) {
6187         }
6188         ArraySet<String> pkgNames = new ArraySet<String>();
6189         if (ris != null) {
6190             for (ResolveInfo ri : ris) {
6191                 pkgNames.add(ri.activityInfo.packageName);
6192             }
6193         }
6194         return pkgNames;
6195     }
6196
6197     private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6198         if (DEBUG_DEXOPT) {
6199             Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6200         }
6201         if (!isFirstBoot()) {
6202             try {
6203                 ActivityManagerNative.getDefault().showBootMessage(
6204                         mContext.getResources().getString(R.string.android_upgrading_apk,
6205                                 curr, total), true);
6206             } catch (RemoteException e) {
6207             }
6208         }
6209         PackageParser.Package p = pkg;
6210         synchronized (mInstallLock) {
6211             mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6212                     false /* force dex */, false /* defer */, true /* include dependencies */);
6213         }
6214     }
6215
6216     @Override
6217     public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6218         return performDexOpt(packageName, instructionSet, false);
6219     }
6220
6221     public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6222         boolean dexopt = mLazyDexOpt || backgroundDexopt;
6223         boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6224         if (!dexopt && !updateUsage) {
6225             // We aren't going to dexopt or update usage, so bail early.
6226             return false;
6227         }
6228         PackageParser.Package p;
6229         final String targetInstructionSet;
6230         synchronized (mPackages) {
6231             p = mPackages.get(packageName);
6232             if (p == null) {
6233                 return false;
6234             }
6235             if (updateUsage) {
6236                 p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6237             }
6238             mPackageUsage.write(false);
6239             if (!dexopt) {
6240                 // We aren't going to dexopt, so bail early.
6241                 return false;
6242             }
6243
6244             targetInstructionSet = instructionSet != null ? instructionSet :
6245                     getPrimaryInstructionSet(p.applicationInfo);
6246             if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6247                 return false;
6248             }
6249         }
6250         long callingId = Binder.clearCallingIdentity();
6251         try {
6252             synchronized (mInstallLock) {
6253                 final String[] instructionSets = new String[] { targetInstructionSet };
6254                 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6255                         false /* forceDex */, false /* defer */, true /* inclDependencies */);
6256                 return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6257             }
6258         } finally {
6259             Binder.restoreCallingIdentity(callingId);
6260         }
6261     }
6262
6263     public ArraySet<String> getPackagesThatNeedDexOpt() {
6264         ArraySet<String> pkgs = null;
6265         synchronized (mPackages) {
6266             for (PackageParser.Package p : mPackages.values()) {
6267                 if (DEBUG_DEXOPT) {
6268                     Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6269                 }
6270                 if (!p.mDexOptPerformed.isEmpty()) {
6271                     continue;
6272                 }
6273                 if (pkgs == null) {
6274                     pkgs = new ArraySet<String>();
6275                 }
6276                 pkgs.add(p.packageName);
6277             }
6278         }
6279         return pkgs;
6280     }
6281
6282     public void shutdown() {
6283         mPackageUsage.write(true);
6284     }
6285
6286     @Override
6287     public void forceDexOpt(String packageName) {
6288         enforceSystemOrRoot("forceDexOpt");
6289
6290         PackageParser.Package pkg;
6291         synchronized (mPackages) {
6292             pkg = mPackages.get(packageName);
6293             if (pkg == null) {
6294                 throw new IllegalArgumentException("Missing package: " + packageName);
6295             }
6296         }
6297
6298         synchronized (mInstallLock) {
6299             final String[] instructionSets = new String[] {
6300                     getPrimaryInstructionSet(pkg.applicationInfo) };
6301             final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6302                     true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6303             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6304                 throw new IllegalStateException("Failed to dexopt: " + res);
6305             }
6306         }
6307     }
6308
6309     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6310         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6311             Slog.w(TAG, "Unable to update from " + oldPkg.name
6312                     + " to " + newPkg.packageName
6313                     + ": old package not in system partition");
6314             return false;
6315         } else if (mPackages.get(oldPkg.name) != null) {
6316             Slog.w(TAG, "Unable to update from " + oldPkg.name
6317                     + " to " + newPkg.packageName
6318                     + ": old package still exists");
6319             return false;
6320         }
6321         return true;
6322     }
6323
6324     private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6325         int[] users = sUserManager.getUserIds();
6326         int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6327         if (res < 0) {
6328             return res;
6329         }
6330         for (int user : users) {
6331             if (user != 0) {
6332                 res = mInstaller.createUserData(volumeUuid, packageName,
6333                         UserHandle.getUid(user, uid), user, seinfo);
6334                 if (res < 0) {
6335                     return res;
6336                 }
6337             }
6338         }
6339         return res;
6340     }
6341
6342     private int removeDataDirsLI(String volumeUuid, String packageName) {
6343         int[] users = sUserManager.getUserIds();
6344         int res = 0;
6345         for (int user : users) {
6346             int resInner = mInstaller.remove(volumeUuid, packageName, user);
6347             if (resInner < 0) {
6348                 res = resInner;
6349             }
6350         }
6351
6352         return res;
6353     }
6354
6355     private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6356         int[] users = sUserManager.getUserIds();
6357         int res = 0;
6358         for (int user : users) {
6359             int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6360             if (resInner < 0) {
6361                 res = resInner;
6362             }
6363         }
6364         return res;
6365     }
6366
6367     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6368             PackageParser.Package changingLib) {
6369         if (file.path != null) {
6370             usesLibraryFiles.add(file.path);
6371             return;
6372         }
6373         PackageParser.Package p = mPackages.get(file.apk);
6374         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6375             // If we are doing this while in the middle of updating a library apk,
6376             // then we need to make sure to use that new apk for determining the
6377             // dependencies here.  (We haven't yet finished committing the new apk
6378             // to the package manager state.)
6379             if (p == null || p.packageName.equals(changingLib.packageName)) {
6380                 p = changingLib;
6381             }
6382         }
6383         if (p != null) {
6384             usesLibraryFiles.addAll(p.getAllCodePaths());
6385         }
6386     }
6387
6388     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6389             PackageParser.Package changingLib) throws PackageManagerException {
6390         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6391             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6392             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6393             for (int i=0; i<N; i++) {
6394                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6395                 if (file == null) {
6396                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6397                             "Package " + pkg.packageName + " requires unavailable shared library "
6398                             + pkg.usesLibraries.get(i) + "; failing!");
6399                 }
6400                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6401             }
6402             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6403             for (int i=0; i<N; i++) {
6404                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6405                 if (file == null) {
6406                     Slog.w(TAG, "Package " + pkg.packageName
6407                             + " desires unavailable shared library "
6408                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6409                 } else {
6410                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6411                 }
6412             }
6413             N = usesLibraryFiles.size();
6414             if (N > 0) {
6415                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6416             } else {
6417                 pkg.usesLibraryFiles = null;
6418             }
6419         }
6420     }
6421
6422     private static boolean hasString(List<String> list, List<String> which) {
6423         if (list == null) {
6424             return false;
6425         }
6426         for (int i=list.size()-1; i>=0; i--) {
6427             for (int j=which.size()-1; j>=0; j--) {
6428                 if (which.get(j).equals(list.get(i))) {
6429                     return true;
6430                 }
6431             }
6432         }
6433         return false;
6434     }
6435
6436     private void updateAllSharedLibrariesLPw() {
6437         for (PackageParser.Package pkg : mPackages.values()) {
6438             try {
6439                 updateSharedLibrariesLPw(pkg, null);
6440             } catch (PackageManagerException e) {
6441                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6442             }
6443         }
6444     }
6445
6446     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6447             PackageParser.Package changingPkg) {
6448         ArrayList<PackageParser.Package> res = null;
6449         for (PackageParser.Package pkg : mPackages.values()) {
6450             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6451                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6452                 if (res == null) {
6453                     res = new ArrayList<PackageParser.Package>();
6454                 }
6455                 res.add(pkg);
6456                 try {
6457                     updateSharedLibrariesLPw(pkg, changingPkg);
6458                 } catch (PackageManagerException e) {
6459                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6460                 }
6461             }
6462         }
6463         return res;
6464     }
6465
6466     /**
6467      * Derive the value of the {@code cpuAbiOverride} based on the provided
6468      * value and an optional stored value from the package settings.
6469      */
6470     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6471         String cpuAbiOverride = null;
6472
6473         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6474             cpuAbiOverride = null;
6475         } else if (abiOverride != null) {
6476             cpuAbiOverride = abiOverride;
6477         } else if (settings != null) {
6478             cpuAbiOverride = settings.cpuAbiOverrideString;
6479         }
6480
6481         return cpuAbiOverride;
6482     }
6483
6484     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6485             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6486         boolean success = false;
6487         try {
6488             final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6489                     currentTime, user);
6490             success = true;
6491             return res;
6492         } finally {
6493             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6494                 removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6495             }
6496         }
6497     }
6498
6499     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6500             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6501         final File scanFile = new File(pkg.codePath);
6502         if (pkg.applicationInfo.getCodePath() == null ||
6503                 pkg.applicationInfo.getResourcePath() == null) {
6504             // Bail out. The resource and code paths haven't been set.
6505             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6506                     "Code and resource paths haven't been set correctly");
6507         }
6508
6509         if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6510             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6511         } else {
6512             // Only allow system apps to be flagged as core apps.
6513             pkg.coreApp = false;
6514         }
6515
6516         if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6517             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6518         }
6519
6520         if (mCustomResolverComponentName != null &&
6521                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6522             setUpCustomResolverActivity(pkg);
6523         }
6524
6525         if (pkg.packageName.equals("android")) {
6526             synchronized (mPackages) {
6527                 if (mAndroidApplication != null) {
6528                     Slog.w(TAG, "*************************************************");
6529                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
6530                     Slog.w(TAG, " file=" + scanFile);
6531                     Slog.w(TAG, "*************************************************");
6532                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6533                             "Core android package being redefined.  Skipping.");
6534                 }
6535
6536                 // Set up information for our fall-back user intent resolution activity.
6537                 mPlatformPackage = pkg;
6538                 pkg.mVersionCode = mSdkVersion;
6539                 mAndroidApplication = pkg.applicationInfo;
6540
6541                 if (!mResolverReplaced) {
6542                     mResolveActivity.applicationInfo = mAndroidApplication;
6543                     mResolveActivity.name = ResolverActivity.class.getName();
6544                     mResolveActivity.packageName = mAndroidApplication.packageName;
6545                     mResolveActivity.processName = "system:ui";
6546                     mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6547                     mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6548                     mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6549                     mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6550                     mResolveActivity.exported = true;
6551                     mResolveActivity.enabled = true;
6552                     mResolveInfo.activityInfo = mResolveActivity;
6553                     mResolveInfo.priority = 0;
6554                     mResolveInfo.preferredOrder = 0;
6555                     mResolveInfo.match = 0;
6556                     mResolveComponentName = new ComponentName(
6557                             mAndroidApplication.packageName, mResolveActivity.name);
6558                 }
6559             }
6560         }
6561
6562         if (DEBUG_PACKAGE_SCANNING) {
6563             if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6564                 Log.d(TAG, "Scanning package " + pkg.packageName);
6565         }
6566
6567         if (mPackages.containsKey(pkg.packageName)
6568                 || mSharedLibraries.containsKey(pkg.packageName)) {
6569             throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6570                     "Application package " + pkg.packageName
6571                     + " already installed.  Skipping duplicate.");
6572         }
6573
6574         // If we're only installing presumed-existing packages, require that the
6575         // scanned APK is both already known and at the path previously established
6576         // for it.  Previously unknown packages we pick up normally, but if we have an
6577         // a priori expectation about this package's install presence, enforce it.
6578         // With a singular exception for new system packages. When an OTA contains
6579         // a new system package, we allow the codepath to change from a system location
6580         // to the user-installed location. If we don't allow this change, any newer,
6581         // user-installed version of the application will be ignored.
6582         if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6583             if (mExpectingBetter.containsKey(pkg.packageName)) {
6584                 logCriticalInfo(Log.WARN,
6585                         "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6586             } else {
6587                 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6588                 if (known != null) {
6589                     if (DEBUG_PACKAGE_SCANNING) {
6590                         Log.d(TAG, "Examining " + pkg.codePath
6591                                 + " and requiring known paths " + known.codePathString
6592                                 + " & " + known.resourcePathString);
6593                     }
6594                     if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6595                             || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6596                         throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6597                                 "Application package " + pkg.packageName
6598                                 + " found at " + pkg.applicationInfo.getCodePath()
6599                                 + " but expected at " + known.codePathString + "; ignoring.");
6600                     }
6601                 }
6602             }
6603         }
6604
6605         // Initialize package source and resource directories
6606         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6607         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6608
6609         SharedUserSetting suid = null;
6610         PackageSetting pkgSetting = null;
6611
6612         if (!isSystemApp(pkg)) {
6613             // Only system apps can use these features.
6614             pkg.mOriginalPackages = null;
6615             pkg.mRealPackage = null;
6616             pkg.mAdoptPermissions = null;
6617         }
6618
6619         // writer
6620         synchronized (mPackages) {
6621             if (pkg.mSharedUserId != null) {
6622                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6623                 if (suid == null) {
6624                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6625                             "Creating application package " + pkg.packageName
6626                             + " for shared user failed");
6627                 }
6628                 if (DEBUG_PACKAGE_SCANNING) {
6629                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6630                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6631                                 + "): packages=" + suid.packages);
6632                 }
6633             }
6634
6635             // Check if we are renaming from an original package name.
6636             PackageSetting origPackage = null;
6637             String realName = null;
6638             if (pkg.mOriginalPackages != null) {
6639                 // This package may need to be renamed to a previously
6640                 // installed name.  Let's check on that...
6641                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6642                 if (pkg.mOriginalPackages.contains(renamed)) {
6643                     // This package had originally been installed as the
6644                     // original name, and we have already taken care of
6645                     // transitioning to the new one.  Just update the new
6646                     // one to continue using the old name.
6647                     realName = pkg.mRealPackage;
6648                     if (!pkg.packageName.equals(renamed)) {
6649                         // Callers into this function may have already taken
6650                         // care of renaming the package; only do it here if
6651                         // it is not already done.
6652                         pkg.setPackageName(renamed);
6653                     }
6654
6655                 } else {
6656                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6657                         if ((origPackage = mSettings.peekPackageLPr(
6658                                 pkg.mOriginalPackages.get(i))) != null) {
6659                             // We do have the package already installed under its
6660                             // original name...  should we use it?
6661                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6662                                 // New package is not compatible with original.
6663                                 origPackage = null;
6664                                 continue;
6665                             } else if (origPackage.sharedUser != null) {
6666                                 // Make sure uid is compatible between packages.
6667                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6668                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6669                                             + " to " + pkg.packageName + ": old uid "
6670                                             + origPackage.sharedUser.name
6671                                             + " differs from " + pkg.mSharedUserId);
6672                                     origPackage = null;
6673                                     continue;
6674                                 }
6675                             } else {
6676                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6677                                         + pkg.packageName + " to old name " + origPackage.name);
6678                             }
6679                             break;
6680                         }
6681                     }
6682                 }
6683             }
6684
6685             if (mTransferedPackages.contains(pkg.packageName)) {
6686                 Slog.w(TAG, "Package " + pkg.packageName
6687                         + " was transferred to another, but its .apk remains");
6688             }
6689
6690             // Just create the setting, don't add it yet. For already existing packages
6691             // the PkgSetting exists already and doesn't have to be created.
6692             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6693                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6694                     pkg.applicationInfo.primaryCpuAbi,
6695                     pkg.applicationInfo.secondaryCpuAbi,
6696                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6697                     user, false);
6698             if (pkgSetting == null) {
6699                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                         "Creating application package " + pkg.packageName + " failed");
6701             }
6702
6703             if (pkgSetting.origPackage != null) {
6704                 // If we are first transitioning from an original package,
6705                 // fix up the new package's name now.  We need to do this after
6706                 // looking up the package under its new name, so getPackageLP
6707                 // can take care of fiddling things correctly.
6708                 pkg.setPackageName(origPackage.name);
6709
6710                 // File a report about this.
6711                 String msg = "New package " + pkgSetting.realName
6712                         + " renamed to replace old package " + pkgSetting.name;
6713                 reportSettingsProblem(Log.WARN, msg);
6714
6715                 // Make a note of it.
6716                 mTransferedPackages.add(origPackage.name);
6717
6718                 // No longer need to retain this.
6719                 pkgSetting.origPackage = null;
6720             }
6721
6722             if (realName != null) {
6723                 // Make a note of it.
6724                 mTransferedPackages.add(pkg.packageName);
6725             }
6726
6727             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6728                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6729             }
6730
6731             if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6732                 // Check all shared libraries and map to their actual file path.
6733                 // We only do this here for apps not on a system dir, because those
6734                 // are the only ones that can fail an install due to this.  We
6735                 // will take care of the system apps by updating all of their
6736                 // library paths after the scan is done.
6737                 updateSharedLibrariesLPw(pkg, null);
6738             }
6739
6740             if (mFoundPolicyFile) {
6741                 SELinuxMMAC.assignSeinfoValue(pkg);
6742             }
6743
6744             pkg.applicationInfo.uid = pkgSetting.appId;
6745             pkg.mExtras = pkgSetting;
6746             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6747                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6748                     // We just determined the app is signed correctly, so bring
6749                     // over the latest parsed certs.
6750                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6751                 } else {
6752                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6753                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6754                                 "Package " + pkg.packageName + " upgrade keys do not match the "
6755                                 + "previously installed version");
6756                     } else {
6757                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
6758                         String msg = "System package " + pkg.packageName
6759                             + " signature changed; retaining data.";
6760                         reportSettingsProblem(Log.WARN, msg);
6761                     }
6762                 }
6763             } else {
6764                 try {
6765                     verifySignaturesLP(pkgSetting, pkg);
6766                     // We just determined the app is signed correctly, so bring
6767                     // over the latest parsed certs.
6768                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6769                 } catch (PackageManagerException e) {
6770                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6771                         throw e;
6772                     }
6773                     // The signature has changed, but this package is in the system
6774                     // image...  let's recover!
6775                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
6776                     // However...  if this package is part of a shared user, but it
6777                     // doesn't match the signature of the shared user, let's fail.
6778                     // What this means is that you can't change the signatures
6779                     // associated with an overall shared user, which doesn't seem all
6780                     // that unreasonable.
6781                     if (pkgSetting.sharedUser != null) {
6782                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6783                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6784                             throw new PackageManagerException(
6785                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6786                                             "Signature mismatch for shared user : "
6787                                             + pkgSetting.sharedUser);
6788                         }
6789                     }
6790                     // File a report about this.
6791                     String msg = "System package " + pkg.packageName
6792                         + " signature changed; retaining data.";
6793                     reportSettingsProblem(Log.WARN, msg);
6794                 }
6795             }
6796             // Verify that this new package doesn't have any content providers
6797             // that conflict with existing packages.  Only do this if the
6798             // package isn't already installed, since we don't want to break
6799             // things that are installed.
6800             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6801                 final int N = pkg.providers.size();
6802                 int i;
6803                 for (i=0; i<N; i++) {
6804                     PackageParser.Provider p = pkg.providers.get(i);
6805                     if (p.info.authority != null) {
6806                         String names[] = p.info.authority.split(";");
6807                         for (int j = 0; j < names.length; j++) {
6808                             if (mProvidersByAuthority.containsKey(names[j])) {
6809                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6810                                 final String otherPackageName =
6811                                         ((other != null && other.getComponentName() != null) ?
6812                                                 other.getComponentName().getPackageName() : "?");
6813                                 throw new PackageManagerException(
6814                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
6815                                                 "Can't install because provider name " + names[j]
6816                                                 + " (in package " + pkg.applicationInfo.packageName
6817                                                 + ") is already used by " + otherPackageName);
6818                             }
6819                         }
6820                     }
6821                 }
6822             }
6823
6824             if (pkg.mAdoptPermissions != null) {
6825                 // This package wants to adopt ownership of permissions from
6826                 // another package.
6827                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6828                     final String origName = pkg.mAdoptPermissions.get(i);
6829                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
6830                     if (orig != null) {
6831                         if (verifyPackageUpdateLPr(orig, pkg)) {
6832                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
6833                                     + pkg.packageName);
6834                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
6835                         }
6836                     }
6837                 }
6838             }
6839         }
6840
6841         final String pkgName = pkg.packageName;
6842
6843         final long scanFileTime = scanFile.lastModified();
6844         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6845         pkg.applicationInfo.processName = fixProcessName(
6846                 pkg.applicationInfo.packageName,
6847                 pkg.applicationInfo.processName,
6848                 pkg.applicationInfo.uid);
6849
6850         File dataPath;
6851         if (mPlatformPackage == pkg) {
6852             // The system package is special.
6853             dataPath = new File(Environment.getDataDirectory(), "system");
6854
6855             pkg.applicationInfo.dataDir = dataPath.getPath();
6856
6857         } else {
6858             // This is a normal package, need to make its data directory.
6859             dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6860                     UserHandle.USER_OWNER, pkg.packageName);
6861
6862             boolean uidError = false;
6863             if (dataPath.exists()) {
6864                 int currentUid = 0;
6865                 try {
6866                     StructStat stat = Os.stat(dataPath.getPath());
6867                     currentUid = stat.st_uid;
6868                 } catch (ErrnoException e) {
6869                     Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6870                 }
6871
6872                 // If we have mismatched owners for the data path, we have a problem.
6873                 if (currentUid != pkg.applicationInfo.uid) {
6874                     boolean recovered = false;
6875                     if (currentUid == 0) {
6876                         // The directory somehow became owned by root.  Wow.
6877                         // This is probably because the system was stopped while
6878                         // installd was in the middle of messing with its libs
6879                         // directory.  Ask installd to fix that.
6880                         int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6881                                 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6882                         if (ret >= 0) {
6883                             recovered = true;
6884                             String msg = "Package " + pkg.packageName
6885                                     + " unexpectedly changed to uid 0; recovered to " +
6886                                     + pkg.applicationInfo.uid;
6887                             reportSettingsProblem(Log.WARN, msg);
6888                         }
6889                     }
6890                     if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6891                             || (scanFlags&SCAN_BOOTING) != 0)) {
6892                         // If this is a system app, we can at least delete its
6893                         // current data so the application will still work.
6894                         int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6895                         if (ret >= 0) {
6896                             // TODO: Kill the processes first
6897                             // Old data gone!
6898                             String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6899                                     ? "System package " : "Third party package ";
6900                             String msg = prefix + pkg.packageName
6901                                     + " has changed from uid: "
6902                                     + currentUid + " to "
6903                                     + pkg.applicationInfo.uid + "; old data erased";
6904                             reportSettingsProblem(Log.WARN, msg);
6905                             recovered = true;
6906
6907                             // And now re-install the app.
6908                             ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6909                                     pkg.applicationInfo.seinfo);
6910                             if (ret == -1) {
6911                                 // Ack should not happen!
6912                                 msg = prefix + pkg.packageName
6913                                         + " could not have data directory re-created after delete.";
6914                                 reportSettingsProblem(Log.WARN, msg);
6915                                 throw new PackageManagerException(
6916                                         INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6917                             }
6918                         }
6919                         if (!recovered) {
6920                             mHasSystemUidErrors = true;
6921                         }
6922                     } else if (!recovered) {
6923                         // If we allow this install to proceed, we will be broken.
6924                         // Abort, abort!
6925                         throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6926                                 "scanPackageLI");
6927                     }
6928                     if (!recovered) {
6929                         pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6930                             + pkg.applicationInfo.uid + "/fs_"
6931                             + currentUid;
6932                         pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6933                         pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6934                         String msg = "Package " + pkg.packageName
6935                                 + " has mismatched uid: "
6936                                 + currentUid + " on disk, "
6937                                 + pkg.applicationInfo.uid + " in settings";
6938                         // writer
6939                         synchronized (mPackages) {
6940                             mSettings.mReadMessages.append(msg);
6941                             mSettings.mReadMessages.append('\n');
6942                             uidError = true;
6943                             if (!pkgSetting.uidError) {
6944                                 reportSettingsProblem(Log.ERROR, msg);
6945                             }
6946                         }
6947                     }
6948                 }
6949                 pkg.applicationInfo.dataDir = dataPath.getPath();
6950                 if (mShouldRestoreconData) {
6951                     Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6952                     mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6953                             pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6954                 }
6955             } else {
6956                 if (DEBUG_PACKAGE_SCANNING) {
6957                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6958                         Log.v(TAG, "Want this data dir: " + dataPath);
6959                 }
6960                 //invoke installer to do the actual installation
6961                 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6962                         pkg.applicationInfo.seinfo);
6963                 if (ret < 0) {
6964                     // Error from installer
6965                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6966                             "Unable to create data dirs [errorCode=" + ret + "]");
6967                 }
6968
6969                 if (dataPath.exists()) {
6970                     pkg.applicationInfo.dataDir = dataPath.getPath();
6971                 } else {
6972                     Slog.w(TAG, "Unable to create data directory: " + dataPath);
6973                     pkg.applicationInfo.dataDir = null;
6974                 }
6975             }
6976
6977             pkgSetting.uidError = uidError;
6978         }
6979
6980         final String path = scanFile.getPath();
6981         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6982
6983         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6984             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6985
6986             // Some system apps still use directory structure for native libraries
6987             // in which case we might end up not detecting abi solely based on apk
6988             // structure. Try to detect abi based on directory structure.
6989             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6990                     pkg.applicationInfo.primaryCpuAbi == null) {
6991                 setBundledAppAbisAndRoots(pkg, pkgSetting);
6992                 setNativeLibraryPaths(pkg);
6993             }
6994
6995         } else {
6996             if ((scanFlags & SCAN_MOVE) != 0) {
6997                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
6998                 // but we already have this packages package info in the PackageSetting. We just
6999                 // use that and derive the native library path based on the new codepath.
7000                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7001                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7002             }
7003
7004             // Set native library paths again. For moves, the path will be updated based on the
7005             // ABIs we've determined above. For non-moves, the path will be updated based on the
7006             // ABIs we determined during compilation, but the path will depend on the final
7007             // package path (after the rename away from the stage path).
7008             setNativeLibraryPaths(pkg);
7009         }
7010
7011         if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7012         final int[] userIds = sUserManager.getUserIds();
7013         synchronized (mInstallLock) {
7014             // Make sure all user data directories are ready to roll; we're okay
7015             // if they already exist
7016             if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7017                 for (int userId : userIds) {
7018                     if (userId != 0) {
7019                         mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7020                                 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7021                                 pkg.applicationInfo.seinfo);
7022                     }
7023                 }
7024             }
7025
7026             // Create a native library symlink only if we have native libraries
7027             // and if the native libraries are 32 bit libraries. We do not provide
7028             // this symlink for 64 bit libraries.
7029             if (pkg.applicationInfo.primaryCpuAbi != null &&
7030                     !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7031                 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7032                 for (int userId : userIds) {
7033                     if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7034                             nativeLibPath, userId) < 0) {
7035                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7036                                 "Failed linking native library dir (user=" + userId + ")");
7037                     }
7038                 }
7039             }
7040         }
7041
7042         // This is a special case for the "system" package, where the ABI is
7043         // dictated by the zygote configuration (and init.rc). We should keep track
7044         // of this ABI so that we can deal with "normal" applications that run under
7045         // the same UID correctly.
7046         if (mPlatformPackage == pkg) {
7047             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7048                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7049         }
7050
7051         // If there's a mismatch between the abi-override in the package setting
7052         // and the abiOverride specified for the install. Warn about this because we
7053         // would've already compiled the app without taking the package setting into
7054         // account.
7055         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7056             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7057                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7058                         " for package: " + pkg.packageName);
7059             }
7060         }
7061
7062         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7063         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7064         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7065
7066         // Copy the derived override back to the parsed package, so that we can
7067         // update the package settings accordingly.
7068         pkg.cpuAbiOverride = cpuAbiOverride;
7069
7070         if (DEBUG_ABI_SELECTION) {
7071             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7072                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7073                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7074         }
7075
7076         // Push the derived path down into PackageSettings so we know what to
7077         // clean up at uninstall time.
7078         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7079
7080         if (DEBUG_ABI_SELECTION) {
7081             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7082                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
7083                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7084         }
7085
7086         if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7087             // We don't do this here during boot because we can do it all
7088             // at once after scanning all existing packages.
7089             //
7090             // We also do this *before* we perform dexopt on this package, so that
7091             // we can avoid redundant dexopts, and also to make sure we've got the
7092             // code and package path correct.
7093             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7094                     pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7095         }
7096
7097         if ((scanFlags & SCAN_NO_DEX) == 0) {
7098             int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7099                     forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7100             if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7101                 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7102             }
7103         }
7104         if (mFactoryTest && pkg.requestedPermissions.contains(
7105                 android.Manifest.permission.FACTORY_TEST)) {
7106             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7107         }
7108
7109         ArrayList<PackageParser.Package> clientLibPkgs = null;
7110
7111         // writer
7112         synchronized (mPackages) {
7113             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7114                 // Only system apps can add new shared libraries.
7115                 if (pkg.libraryNames != null) {
7116                     for (int i=0; i<pkg.libraryNames.size(); i++) {
7117                         String name = pkg.libraryNames.get(i);
7118                         boolean allowed = false;
7119                         if (pkg.isUpdatedSystemApp()) {
7120                             // New library entries can only be added through the
7121                             // system image.  This is important to get rid of a lot
7122                             // of nasty edge cases: for example if we allowed a non-
7123                             // system update of the app to add a library, then uninstalling
7124                             // the update would make the library go away, and assumptions
7125                             // we made such as through app install filtering would now
7126                             // have allowed apps on the device which aren't compatible
7127                             // with it.  Better to just have the restriction here, be
7128                             // conservative, and create many fewer cases that can negatively
7129                             // impact the user experience.
7130                             final PackageSetting sysPs = mSettings
7131                                     .getDisabledSystemPkgLPr(pkg.packageName);
7132                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7133                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7134                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7135                                         allowed = true;
7136                                         allowed = true;
7137                                         break;
7138                                     }
7139                                 }
7140                             }
7141                         } else {
7142                             allowed = true;
7143                         }
7144                         if (allowed) {
7145                             if (!mSharedLibraries.containsKey(name)) {
7146                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7147                             } else if (!name.equals(pkg.packageName)) {
7148                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
7149                                         + name + " already exists; skipping");
7150                             }
7151                         } else {
7152                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7153                                     + name + " that is not declared on system image; skipping");
7154                         }
7155                     }
7156                     if ((scanFlags&SCAN_BOOTING) == 0) {
7157                         // If we are not booting, we need to update any applications
7158                         // that are clients of our shared library.  If we are booting,
7159                         // this will all be done once the scan is complete.
7160                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7161                     }
7162                 }
7163             }
7164         }
7165
7166         // We also need to dexopt any apps that are dependent on this library.  Note that
7167         // if these fail, we should abort the install since installing the library will
7168         // result in some apps being broken.
7169         if (clientLibPkgs != null) {
7170             if ((scanFlags & SCAN_NO_DEX) == 0) {
7171                 for (int i = 0; i < clientLibPkgs.size(); i++) {
7172                     PackageParser.Package clientPkg = clientLibPkgs.get(i);
7173                     int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7174                             null /* instruction sets */, forceDex,
7175                             (scanFlags & SCAN_DEFER_DEX) != 0, false);
7176                     if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7177                         throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7178                                 "scanPackageLI failed to dexopt clientLibPkgs");
7179                     }
7180                 }
7181             }
7182         }
7183
7184         // Request the ActivityManager to kill the process(only for existing packages)
7185         // so that we do not end up in a confused state while the user is still using the older
7186         // version of the application while the new one gets installed.
7187         if ((scanFlags & SCAN_REPLACING) != 0) {
7188             killApplication(pkg.applicationInfo.packageName,
7189                         pkg.applicationInfo.uid, "replace pkg");
7190         }
7191
7192         // Also need to kill any apps that are dependent on the library.
7193         if (clientLibPkgs != null) {
7194             for (int i=0; i<clientLibPkgs.size(); i++) {
7195                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
7196                 killApplication(clientPkg.applicationInfo.packageName,
7197                         clientPkg.applicationInfo.uid, "update lib");
7198             }
7199         }
7200
7201         // Make sure we're not adding any bogus keyset info
7202         KeySetManagerService ksms = mSettings.mKeySetManagerService;
7203         ksms.assertScannedPackageValid(pkg);
7204
7205         // writer
7206         synchronized (mPackages) {
7207             // We don't expect installation to fail beyond this point
7208
7209             // Add the new setting to mSettings
7210             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7211             // Add the new setting to mPackages
7212             mPackages.put(pkg.applicationInfo.packageName, pkg);
7213             // Make sure we don't accidentally delete its data.
7214             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7215             while (iter.hasNext()) {
7216                 PackageCleanItem item = iter.next();
7217                 if (pkgName.equals(item.packageName)) {
7218                     iter.remove();
7219                 }
7220             }
7221
7222             // Take care of first install / last update times.
7223             if (currentTime != 0) {
7224                 if (pkgSetting.firstInstallTime == 0) {
7225                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7226                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7227                     pkgSetting.lastUpdateTime = currentTime;
7228                 }
7229             } else if (pkgSetting.firstInstallTime == 0) {
7230                 // We need *something*.  Take time time stamp of the file.
7231                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7232             } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7233                 if (scanFileTime != pkgSetting.timeStamp) {
7234                     // A package on the system image has changed; consider this
7235                     // to be an update.
7236                     pkgSetting.lastUpdateTime = scanFileTime;
7237                 }
7238             }
7239
7240             // Add the package's KeySets to the global KeySetManagerService
7241             ksms.addScannedPackageLPw(pkg);
7242
7243             int N = pkg.providers.size();
7244             StringBuilder r = null;
7245             int i;
7246             for (i=0; i<N; i++) {
7247                 PackageParser.Provider p = pkg.providers.get(i);
7248                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7249                         p.info.processName, pkg.applicationInfo.uid);
7250                 mProviders.addProvider(p);
7251                 p.syncable = p.info.isSyncable;
7252                 if (p.info.authority != null) {
7253                     String names[] = p.info.authority.split(";");
7254                     p.info.authority = null;
7255                     for (int j = 0; j < names.length; j++) {
7256                         if (j == 1 && p.syncable) {
7257                             // We only want the first authority for a provider to possibly be
7258                             // syncable, so if we already added this provider using a different
7259                             // authority clear the syncable flag. We copy the provider before
7260                             // changing it because the mProviders object contains a reference
7261                             // to a provider that we don't want to change.
7262                             // Only do this for the second authority since the resulting provider
7263                             // object can be the same for all future authorities for this provider.
7264                             p = new PackageParser.Provider(p);
7265                             p.syncable = false;
7266                         }
7267                         if (!mProvidersByAuthority.containsKey(names[j])) {
7268                             mProvidersByAuthority.put(names[j], p);
7269                             if (p.info.authority == null) {
7270                                 p.info.authority = names[j];
7271                             } else {
7272                                 p.info.authority = p.info.authority + ";" + names[j];
7273                             }
7274                             if (DEBUG_PACKAGE_SCANNING) {
7275                                 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7276                                     Log.d(TAG, "Registered content provider: " + names[j]
7277                                             + ", className = " + p.info.name + ", isSyncable = "
7278                                             + p.info.isSyncable);
7279                             }
7280                         } else {
7281                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7282                             Slog.w(TAG, "Skipping provider name " + names[j] +
7283                                     " (in package " + pkg.applicationInfo.packageName +
7284                                     "): name already used by "
7285                                     + ((other != null && other.getComponentName() != null)
7286                                             ? other.getComponentName().getPackageName() : "?"));
7287                         }
7288                     }
7289                 }
7290                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7291                     if (r == null) {
7292                         r = new StringBuilder(256);
7293                     } else {
7294                         r.append(' ');
7295                     }
7296                     r.append(p.info.name);
7297                 }
7298             }
7299             if (r != null) {
7300                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7301             }
7302
7303             N = pkg.services.size();
7304             r = null;
7305             for (i=0; i<N; i++) {
7306                 PackageParser.Service s = pkg.services.get(i);
7307                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7308                         s.info.processName, pkg.applicationInfo.uid);
7309                 mServices.addService(s);
7310                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7311                     if (r == null) {
7312                         r = new StringBuilder(256);
7313                     } else {
7314                         r.append(' ');
7315                     }
7316                     r.append(s.info.name);
7317                 }
7318             }
7319             if (r != null) {
7320                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7321             }
7322
7323             N = pkg.receivers.size();
7324             r = null;
7325             for (i=0; i<N; i++) {
7326                 PackageParser.Activity a = pkg.receivers.get(i);
7327                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7328                         a.info.processName, pkg.applicationInfo.uid);
7329                 mReceivers.addActivity(a, "receiver");
7330                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7331                     if (r == null) {
7332                         r = new StringBuilder(256);
7333                     } else {
7334                         r.append(' ');
7335                     }
7336                     r.append(a.info.name);
7337                 }
7338             }
7339             if (r != null) {
7340                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7341             }
7342
7343             N = pkg.activities.size();
7344             r = null;
7345             for (i=0; i<N; i++) {
7346                 PackageParser.Activity a = pkg.activities.get(i);
7347                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7348                         a.info.processName, pkg.applicationInfo.uid);
7349                 mActivities.addActivity(a, "activity");
7350                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7351                     if (r == null) {
7352                         r = new StringBuilder(256);
7353                     } else {
7354                         r.append(' ');
7355                     }
7356                     r.append(a.info.name);
7357                 }
7358             }
7359             if (r != null) {
7360                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7361             }
7362
7363             N = pkg.permissionGroups.size();
7364             r = null;
7365             for (i=0; i<N; i++) {
7366                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7367                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7368                 if (cur == null) {
7369                     mPermissionGroups.put(pg.info.name, pg);
7370                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7371                         if (r == null) {
7372                             r = new StringBuilder(256);
7373                         } else {
7374                             r.append(' ');
7375                         }
7376                         r.append(pg.info.name);
7377                     }
7378                 } else {
7379                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7380                             + pg.info.packageName + " ignored: original from "
7381                             + cur.info.packageName);
7382                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7383                         if (r == null) {
7384                             r = new StringBuilder(256);
7385                         } else {
7386                             r.append(' ');
7387                         }
7388                         r.append("DUP:");
7389                         r.append(pg.info.name);
7390                     }
7391                 }
7392             }
7393             if (r != null) {
7394                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7395             }
7396
7397             N = pkg.permissions.size();
7398             r = null;
7399             for (i=0; i<N; i++) {
7400                 PackageParser.Permission p = pkg.permissions.get(i);
7401
7402                 // Assume by default that we did not install this permission into the system.
7403                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7404
7405                 // Now that permission groups have a special meaning, we ignore permission
7406                 // groups for legacy apps to prevent unexpected behavior. In particular,
7407                 // permissions for one app being granted to someone just becuase they happen
7408                 // to be in a group defined by another app (before this had no implications).
7409                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7410                     p.group = mPermissionGroups.get(p.info.group);
7411                     // Warn for a permission in an unknown group.
7412                     if (p.info.group != null && p.group == null) {
7413                         Slog.w(TAG, "Permission " + p.info.name + " from package "
7414                                 + p.info.packageName + " in an unknown group " + p.info.group);
7415                     }
7416                 }
7417
7418                 ArrayMap<String, BasePermission> permissionMap =
7419                         p.tree ? mSettings.mPermissionTrees
7420                                 : mSettings.mPermissions;
7421                 BasePermission bp = permissionMap.get(p.info.name);
7422
7423                 // Allow system apps to redefine non-system permissions
7424                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7425                     final boolean currentOwnerIsSystem = (bp.perm != null
7426                             && isSystemApp(bp.perm.owner));
7427                     if (isSystemApp(p.owner)) {
7428                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7429                             // It's a built-in permission and no owner, take ownership now
7430                             bp.packageSetting = pkgSetting;
7431                             bp.perm = p;
7432                             bp.uid = pkg.applicationInfo.uid;
7433                             bp.sourcePackage = p.info.packageName;
7434                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7435                         } else if (!currentOwnerIsSystem) {
7436                             String msg = "New decl " + p.owner + " of permission  "
7437                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
7438                             reportSettingsProblem(Log.WARN, msg);
7439                             bp = null;
7440                         }
7441                     }
7442                 }
7443
7444                 if (bp == null) {
7445                     bp = new BasePermission(p.info.name, p.info.packageName,
7446                             BasePermission.TYPE_NORMAL);
7447                     permissionMap.put(p.info.name, bp);
7448                 }
7449
7450                 if (bp.perm == null) {
7451                     if (bp.sourcePackage == null
7452                             || bp.sourcePackage.equals(p.info.packageName)) {
7453                         BasePermission tree = findPermissionTreeLP(p.info.name);
7454                         if (tree == null
7455                                 || tree.sourcePackage.equals(p.info.packageName)) {
7456                             bp.packageSetting = pkgSetting;
7457                             bp.perm = p;
7458                             bp.uid = pkg.applicationInfo.uid;
7459                             bp.sourcePackage = p.info.packageName;
7460                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7461                             if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7462                                 if (r == null) {
7463                                     r = new StringBuilder(256);
7464                                 } else {
7465                                     r.append(' ');
7466                                 }
7467                                 r.append(p.info.name);
7468                             }
7469                         } else {
7470                             Slog.w(TAG, "Permission " + p.info.name + " from package "
7471                                     + p.info.packageName + " ignored: base tree "
7472                                     + tree.name + " is from package "
7473                                     + tree.sourcePackage);
7474                         }
7475                     } else {
7476                         Slog.w(TAG, "Permission " + p.info.name + " from package "
7477                                 + p.info.packageName + " ignored: original from "
7478                                 + bp.sourcePackage);
7479                     }
7480                 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                     if (r == null) {
7482                         r = new StringBuilder(256);
7483                     } else {
7484                         r.append(' ');
7485                     }
7486                     r.append("DUP:");
7487                     r.append(p.info.name);
7488                 }
7489                 if (bp.perm == p) {
7490                     bp.protectionLevel = p.info.protectionLevel;
7491                 }
7492             }
7493
7494             if (r != null) {
7495                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7496             }
7497
7498             N = pkg.instrumentation.size();
7499             r = null;
7500             for (i=0; i<N; i++) {
7501                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7502                 a.info.packageName = pkg.applicationInfo.packageName;
7503                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
7504                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7505                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7506                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7507                 a.info.dataDir = pkg.applicationInfo.dataDir;
7508
7509                 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7510                 // need other information about the application, like the ABI and what not ?
7511                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7512                 mInstrumentation.put(a.getComponentName(), a);
7513                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7514                     if (r == null) {
7515                         r = new StringBuilder(256);
7516                     } else {
7517                         r.append(' ');
7518                     }
7519                     r.append(a.info.name);
7520                 }
7521             }
7522             if (r != null) {
7523                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7524             }
7525
7526             if (pkg.protectedBroadcasts != null) {
7527                 N = pkg.protectedBroadcasts.size();
7528                 for (i=0; i<N; i++) {
7529                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7530                 }
7531             }
7532
7533             pkgSetting.setTimeStamp(scanFileTime);
7534
7535             // Create idmap files for pairs of (packages, overlay packages).
7536             // Note: "android", ie framework-res.apk, is handled by native layers.
7537             if (pkg.mOverlayTarget != null) {
7538                 // This is an overlay package.
7539                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7540                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7541                         mOverlays.put(pkg.mOverlayTarget,
7542                                 new ArrayMap<String, PackageParser.Package>());
7543                     }
7544                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7545                     map.put(pkg.packageName, pkg);
7546                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7547                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7548                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7549                                 "scanPackageLI failed to createIdmap");
7550                     }
7551                 }
7552             } else if (mOverlays.containsKey(pkg.packageName) &&
7553                     !pkg.packageName.equals("android")) {
7554                 // This is a regular package, with one or more known overlay packages.
7555                 createIdmapsForPackageLI(pkg);
7556             }
7557         }
7558
7559         return pkg;
7560     }
7561
7562     /**
7563      * Derive the ABI of a non-system package located at {@code scanFile}. This information
7564      * is derived purely on the basis of the contents of {@code scanFile} and
7565      * {@code cpuAbiOverride}.
7566      *
7567      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7568      */
7569     public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7570                                  String cpuAbiOverride, boolean extractLibs)
7571             throws PackageManagerException {
7572         // TODO: We can probably be smarter about this stuff. For installed apps,
7573         // we can calculate this information at install time once and for all. For
7574         // system apps, we can probably assume that this information doesn't change
7575         // after the first boot scan. As things stand, we do lots of unnecessary work.
7576
7577         // Give ourselves some initial paths; we'll come back for another
7578         // pass once we've determined ABI below.
7579         setNativeLibraryPaths(pkg);
7580
7581         // We would never need to extract libs for forward-locked and external packages,
7582         // since the container service will do it for us. We shouldn't attempt to
7583         // extract libs from system app when it was not updated.
7584         if (pkg.isForwardLocked() || isExternal(pkg) ||
7585             (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7586             extractLibs = false;
7587         }
7588
7589         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7590         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7591
7592         NativeLibraryHelper.Handle handle = null;
7593         try {
7594             handle = NativeLibraryHelper.Handle.create(scanFile);
7595             // TODO(multiArch): This can be null for apps that didn't go through the
7596             // usual installation process. We can calculate it again, like we
7597             // do during install time.
7598             //
7599             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7600             // unnecessary.
7601             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7602
7603             // Null out the abis so that they can be recalculated.
7604             pkg.applicationInfo.primaryCpuAbi = null;
7605             pkg.applicationInfo.secondaryCpuAbi = null;
7606             if (isMultiArch(pkg.applicationInfo)) {
7607                 // Warn if we've set an abiOverride for multi-lib packages..
7608                 // By definition, we need to copy both 32 and 64 bit libraries for
7609                 // such packages.
7610                 if (pkg.cpuAbiOverride != null
7611                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7612                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7613                 }
7614
7615                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7616                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7617                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7618                     if (extractLibs) {
7619                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7620                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7621                                 useIsaSpecificSubdirs);
7622                     } else {
7623                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7624                     }
7625                 }
7626
7627                 maybeThrowExceptionForMultiArchCopy(
7628                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7629
7630                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7631                     if (extractLibs) {
7632                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7633                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7634                                 useIsaSpecificSubdirs);
7635                     } else {
7636                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7637                     }
7638                 }
7639
7640                 maybeThrowExceptionForMultiArchCopy(
7641                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7642
7643                 if (abi64 >= 0) {
7644                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7645                 }
7646
7647                 if (abi32 >= 0) {
7648                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7649                     if (abi64 >= 0) {
7650                         pkg.applicationInfo.secondaryCpuAbi = abi;
7651                     } else {
7652                         pkg.applicationInfo.primaryCpuAbi = abi;
7653                     }
7654                 }
7655             } else {
7656                 String[] abiList = (cpuAbiOverride != null) ?
7657                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7658
7659                 // Enable gross and lame hacks for apps that are built with old
7660                 // SDK tools. We must scan their APKs for renderscript bitcode and
7661                 // not launch them if it's present. Don't bother checking on devices
7662                 // that don't have 64 bit support.
7663                 boolean needsRenderScriptOverride = false;
7664                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7665                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7666                     abiList = Build.SUPPORTED_32_BIT_ABIS;
7667                     needsRenderScriptOverride = true;
7668                 }
7669
7670                 final int copyRet;
7671                 if (extractLibs) {
7672                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7673                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7674                 } else {
7675                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7676                 }
7677
7678                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7679                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7680                             "Error unpackaging native libs for app, errorCode=" + copyRet);
7681                 }
7682
7683                 if (copyRet >= 0) {
7684                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7685                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7686                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7687                 } else if (needsRenderScriptOverride) {
7688                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
7689                 }
7690             }
7691         } catch (IOException ioe) {
7692             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7693         } finally {
7694             IoUtils.closeQuietly(handle);
7695         }
7696
7697         // Now that we've calculated the ABIs and determined if it's an internal app,
7698         // we will go ahead and populate the nativeLibraryPath.
7699         setNativeLibraryPaths(pkg);
7700     }
7701
7702     /**
7703      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7704      * i.e, so that all packages can be run inside a single process if required.
7705      *
7706      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7707      * this function will either try and make the ABI for all packages in {@code packagesForUser}
7708      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7709      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7710      * updating a package that belongs to a shared user.
7711      *
7712      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7713      * adds unnecessary complexity.
7714      */
7715     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7716             PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7717         String requiredInstructionSet = null;
7718         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7719             requiredInstructionSet = VMRuntime.getInstructionSet(
7720                      scannedPackage.applicationInfo.primaryCpuAbi);
7721         }
7722
7723         PackageSetting requirer = null;
7724         for (PackageSetting ps : packagesForUser) {
7725             // If packagesForUser contains scannedPackage, we skip it. This will happen
7726             // when scannedPackage is an update of an existing package. Without this check,
7727             // we will never be able to change the ABI of any package belonging to a shared
7728             // user, even if it's compatible with other packages.
7729             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7730                 if (ps.primaryCpuAbiString == null) {
7731                     continue;
7732                 }
7733
7734                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7735                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7736                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
7737                     // this but there's not much we can do.
7738                     String errorMessage = "Instruction set mismatch, "
7739                             + ((requirer == null) ? "[caller]" : requirer)
7740                             + " requires " + requiredInstructionSet + " whereas " + ps
7741                             + " requires " + instructionSet;
7742                     Slog.w(TAG, errorMessage);
7743                 }
7744
7745                 if (requiredInstructionSet == null) {
7746                     requiredInstructionSet = instructionSet;
7747                     requirer = ps;
7748                 }
7749             }
7750         }
7751
7752         if (requiredInstructionSet != null) {
7753             String adjustedAbi;
7754             if (requirer != null) {
7755                 // requirer != null implies that either scannedPackage was null or that scannedPackage
7756                 // did not require an ABI, in which case we have to adjust scannedPackage to match
7757                 // the ABI of the set (which is the same as requirer's ABI)
7758                 adjustedAbi = requirer.primaryCpuAbiString;
7759                 if (scannedPackage != null) {
7760                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7761                 }
7762             } else {
7763                 // requirer == null implies that we're updating all ABIs in the set to
7764                 // match scannedPackage.
7765                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7766             }
7767
7768             for (PackageSetting ps : packagesForUser) {
7769                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7770                     if (ps.primaryCpuAbiString != null) {
7771                         continue;
7772                     }
7773
7774                     ps.primaryCpuAbiString = adjustedAbi;
7775                     if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7776                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7777                         Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7778
7779                         int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7780                                 null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7781                         if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7782                             ps.primaryCpuAbiString = null;
7783                             ps.pkg.applicationInfo.primaryCpuAbi = null;
7784                             return;
7785                         } else {
7786                             mInstaller.rmdex(ps.codePathString,
7787                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
7788                         }
7789                     }
7790                 }
7791             }
7792         }
7793     }
7794
7795     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7796         synchronized (mPackages) {
7797             mResolverReplaced = true;
7798             // Set up information for custom user intent resolution activity.
7799             mResolveActivity.applicationInfo = pkg.applicationInfo;
7800             mResolveActivity.name = mCustomResolverComponentName.getClassName();
7801             mResolveActivity.packageName = pkg.applicationInfo.packageName;
7802             mResolveActivity.processName = pkg.applicationInfo.packageName;
7803             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7804             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7805                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7806             mResolveActivity.theme = 0;
7807             mResolveActivity.exported = true;
7808             mResolveActivity.enabled = true;
7809             mResolveInfo.activityInfo = mResolveActivity;
7810             mResolveInfo.priority = 0;
7811             mResolveInfo.preferredOrder = 0;
7812             mResolveInfo.match = 0;
7813             mResolveComponentName = mCustomResolverComponentName;
7814             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7815                     mResolveComponentName);
7816         }
7817     }
7818
7819     private static String calculateBundledApkRoot(final String codePathString) {
7820         final File codePath = new File(codePathString);
7821         final File codeRoot;
7822         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7823             codeRoot = Environment.getRootDirectory();
7824         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7825             codeRoot = Environment.getOemDirectory();
7826         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7827             codeRoot = Environment.getVendorDirectory();
7828         } else {
7829             // Unrecognized code path; take its top real segment as the apk root:
7830             // e.g. /something/app/blah.apk => /something
7831             try {
7832                 File f = codePath.getCanonicalFile();
7833                 File parent = f.getParentFile();    // non-null because codePath is a file
7834                 File tmp;
7835                 while ((tmp = parent.getParentFile()) != null) {
7836                     f = parent;
7837                     parent = tmp;
7838                 }
7839                 codeRoot = f;
7840                 Slog.w(TAG, "Unrecognized code path "
7841                         + codePath + " - using " + codeRoot);
7842             } catch (IOException e) {
7843                 // Can't canonicalize the code path -- shenanigans?
7844                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
7845                 return Environment.getRootDirectory().getPath();
7846             }
7847         }
7848         return codeRoot.getPath();
7849     }
7850
7851     /**
7852      * Derive and set the location of native libraries for the given package,
7853      * which varies depending on where and how the package was installed.
7854      */
7855     private void setNativeLibraryPaths(PackageParser.Package pkg) {
7856         final ApplicationInfo info = pkg.applicationInfo;
7857         final String codePath = pkg.codePath;
7858         final File codeFile = new File(codePath);
7859         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7860         final boolean asecApp = info.isForwardLocked() || isExternal(info);
7861
7862         info.nativeLibraryRootDir = null;
7863         info.nativeLibraryRootRequiresIsa = false;
7864         info.nativeLibraryDir = null;
7865         info.secondaryNativeLibraryDir = null;
7866
7867         if (isApkFile(codeFile)) {
7868             // Monolithic install
7869             if (bundledApp) {
7870                 // If "/system/lib64/apkname" exists, assume that is the per-package
7871                 // native library directory to use; otherwise use "/system/lib/apkname".
7872                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7873                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7874                         getPrimaryInstructionSet(info));
7875
7876                 // This is a bundled system app so choose the path based on the ABI.
7877                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7878                 // is just the default path.
7879                 final String apkName = deriveCodePathName(codePath);
7880                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7881                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7882                         apkName).getAbsolutePath();
7883
7884                 if (info.secondaryCpuAbi != null) {
7885                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7886                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7887                             secondaryLibDir, apkName).getAbsolutePath();
7888                 }
7889             } else if (asecApp) {
7890                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7891                         .getAbsolutePath();
7892             } else {
7893                 final String apkName = deriveCodePathName(codePath);
7894                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7895                         .getAbsolutePath();
7896             }
7897
7898             info.nativeLibraryRootRequiresIsa = false;
7899             info.nativeLibraryDir = info.nativeLibraryRootDir;
7900         } else {
7901             // Cluster install
7902             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7903             info.nativeLibraryRootRequiresIsa = true;
7904
7905             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7906                     getPrimaryInstructionSet(info)).getAbsolutePath();
7907
7908             if (info.secondaryCpuAbi != null) {
7909                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7910                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7911             }
7912         }
7913     }
7914
7915     /**
7916      * Calculate the abis and roots for a bundled app. These can uniquely
7917      * be determined from the contents of the system partition, i.e whether
7918      * it contains 64 or 32 bit shared libraries etc. We do not validate any
7919      * of this information, and instead assume that the system was built
7920      * sensibly.
7921      */
7922     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7923                                            PackageSetting pkgSetting) {
7924         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7925
7926         // If "/system/lib64/apkname" exists, assume that is the per-package
7927         // native library directory to use; otherwise use "/system/lib/apkname".
7928         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7929         setBundledAppAbi(pkg, apkRoot, apkName);
7930         // pkgSetting might be null during rescan following uninstall of updates
7931         // to a bundled app, so accommodate that possibility.  The settings in
7932         // that case will be established later from the parsed package.
7933         //
7934         // If the settings aren't null, sync them up with what we've just derived.
7935         // note that apkRoot isn't stored in the package settings.
7936         if (pkgSetting != null) {
7937             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7938             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7939         }
7940     }
7941
7942     /**
7943      * Deduces the ABI of a bundled app and sets the relevant fields on the
7944      * parsed pkg object.
7945      *
7946      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7947      *        under which system libraries are installed.
7948      * @param apkName the name of the installed package.
7949      */
7950     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7951         final File codeFile = new File(pkg.codePath);
7952
7953         final boolean has64BitLibs;
7954         final boolean has32BitLibs;
7955         if (isApkFile(codeFile)) {
7956             // Monolithic install
7957             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7958             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7959         } else {
7960             // Cluster install
7961             final File rootDir = new File(codeFile, LIB_DIR_NAME);
7962             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7963                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7964                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7965                 has64BitLibs = (new File(rootDir, isa)).exists();
7966             } else {
7967                 has64BitLibs = false;
7968             }
7969             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7970                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7971                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7972                 has32BitLibs = (new File(rootDir, isa)).exists();
7973             } else {
7974                 has32BitLibs = false;
7975             }
7976         }
7977
7978         if (has64BitLibs && !has32BitLibs) {
7979             // The package has 64 bit libs, but not 32 bit libs. Its primary
7980             // ABI should be 64 bit. We can safely assume here that the bundled
7981             // native libraries correspond to the most preferred ABI in the list.
7982
7983             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7984             pkg.applicationInfo.secondaryCpuAbi = null;
7985         } else if (has32BitLibs && !has64BitLibs) {
7986             // The package has 32 bit libs but not 64 bit libs. Its primary
7987             // ABI should be 32 bit.
7988
7989             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7990             pkg.applicationInfo.secondaryCpuAbi = null;
7991         } else if (has32BitLibs && has64BitLibs) {
7992             // The application has both 64 and 32 bit bundled libraries. We check
7993             // here that the app declares multiArch support, and warn if it doesn't.
7994             //
7995             // We will be lenient here and record both ABIs. The primary will be the
7996             // ABI that's higher on the list, i.e, a device that's configured to prefer
7997             // 64 bit apps will see a 64 bit primary ABI,
7998
7999             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8000                 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8001             }
8002
8003             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8004                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8005                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8006             } else {
8007                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8008                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8009             }
8010         } else {
8011             pkg.applicationInfo.primaryCpuAbi = null;
8012             pkg.applicationInfo.secondaryCpuAbi = null;
8013         }
8014     }
8015
8016     private void killApplication(String pkgName, int appId, String reason) {
8017         // Request the ActivityManager to kill the process(only for existing packages)
8018         // so that we do not end up in a confused state while the user is still using the older
8019         // version of the application while the new one gets installed.
8020         IActivityManager am = ActivityManagerNative.getDefault();
8021         if (am != null) {
8022             try {
8023                 am.killApplicationWithAppId(pkgName, appId, reason);
8024             } catch (RemoteException e) {
8025             }
8026         }
8027     }
8028
8029     void removePackageLI(PackageSetting ps, boolean chatty) {
8030         if (DEBUG_INSTALL) {
8031             if (chatty)
8032                 Log.d(TAG, "Removing package " + ps.name);
8033         }
8034
8035         // writer
8036         synchronized (mPackages) {
8037             mPackages.remove(ps.name);
8038             final PackageParser.Package pkg = ps.pkg;
8039             if (pkg != null) {
8040                 cleanPackageDataStructuresLILPw(pkg, chatty);
8041             }
8042         }
8043     }
8044
8045     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8046         if (DEBUG_INSTALL) {
8047             if (chatty)
8048                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8049         }
8050
8051         // writer
8052         synchronized (mPackages) {
8053             mPackages.remove(pkg.applicationInfo.packageName);
8054             cleanPackageDataStructuresLILPw(pkg, chatty);
8055         }
8056     }
8057
8058     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8059         int N = pkg.providers.size();
8060         StringBuilder r = null;
8061         int i;
8062         for (i=0; i<N; i++) {
8063             PackageParser.Provider p = pkg.providers.get(i);
8064             mProviders.removeProvider(p);
8065             if (p.info.authority == null) {
8066
8067                 /* There was another ContentProvider with this authority when
8068                  * this app was installed so this authority is null,
8069                  * Ignore it as we don't have to unregister the provider.
8070                  */
8071                 continue;
8072             }
8073             String names[] = p.info.authority.split(";");
8074             for (int j = 0; j < names.length; j++) {
8075                 if (mProvidersByAuthority.get(names[j]) == p) {
8076                     mProvidersByAuthority.remove(names[j]);
8077                     if (DEBUG_REMOVE) {
8078                         if (chatty)
8079                             Log.d(TAG, "Unregistered content provider: " + names[j]
8080                                     + ", className = " + p.info.name + ", isSyncable = "
8081                                     + p.info.isSyncable);
8082                     }
8083                 }
8084             }
8085             if (DEBUG_REMOVE && chatty) {
8086                 if (r == null) {
8087                     r = new StringBuilder(256);
8088                 } else {
8089                     r.append(' ');
8090                 }
8091                 r.append(p.info.name);
8092             }
8093         }
8094         if (r != null) {
8095             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8096         }
8097
8098         N = pkg.services.size();
8099         r = null;
8100         for (i=0; i<N; i++) {
8101             PackageParser.Service s = pkg.services.get(i);
8102             mServices.removeService(s);
8103             if (chatty) {
8104                 if (r == null) {
8105                     r = new StringBuilder(256);
8106                 } else {
8107                     r.append(' ');
8108                 }
8109                 r.append(s.info.name);
8110             }
8111         }
8112         if (r != null) {
8113             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8114         }
8115
8116         N = pkg.receivers.size();
8117         r = null;
8118         for (i=0; i<N; i++) {
8119             PackageParser.Activity a = pkg.receivers.get(i);
8120             mReceivers.removeActivity(a, "receiver");
8121             if (DEBUG_REMOVE && chatty) {
8122                 if (r == null) {
8123                     r = new StringBuilder(256);
8124                 } else {
8125                     r.append(' ');
8126                 }
8127                 r.append(a.info.name);
8128             }
8129         }
8130         if (r != null) {
8131             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8132         }
8133
8134         N = pkg.activities.size();
8135         r = null;
8136         for (i=0; i<N; i++) {
8137             PackageParser.Activity a = pkg.activities.get(i);
8138             mActivities.removeActivity(a, "activity");
8139             if (DEBUG_REMOVE && chatty) {
8140                 if (r == null) {
8141                     r = new StringBuilder(256);
8142                 } else {
8143                     r.append(' ');
8144                 }
8145                 r.append(a.info.name);
8146             }
8147         }
8148         if (r != null) {
8149             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8150         }
8151
8152         N = pkg.permissions.size();
8153         r = null;
8154         for (i=0; i<N; i++) {
8155             PackageParser.Permission p = pkg.permissions.get(i);
8156             BasePermission bp = mSettings.mPermissions.get(p.info.name);
8157             if (bp == null) {
8158                 bp = mSettings.mPermissionTrees.get(p.info.name);
8159             }
8160             if (bp != null && bp.perm == p) {
8161                 bp.perm = null;
8162                 if (DEBUG_REMOVE && chatty) {
8163                     if (r == null) {
8164                         r = new StringBuilder(256);
8165                     } else {
8166                         r.append(' ');
8167                     }
8168                     r.append(p.info.name);
8169                 }
8170             }
8171             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8172                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8173                 if (appOpPerms != null) {
8174                     appOpPerms.remove(pkg.packageName);
8175                 }
8176             }
8177         }
8178         if (r != null) {
8179             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8180         }
8181
8182         N = pkg.requestedPermissions.size();
8183         r = null;
8184         for (i=0; i<N; i++) {
8185             String perm = pkg.requestedPermissions.get(i);
8186             BasePermission bp = mSettings.mPermissions.get(perm);
8187             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8188                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8189                 if (appOpPerms != null) {
8190                     appOpPerms.remove(pkg.packageName);
8191                     if (appOpPerms.isEmpty()) {
8192                         mAppOpPermissionPackages.remove(perm);
8193                     }
8194                 }
8195             }
8196         }
8197         if (r != null) {
8198             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8199         }
8200
8201         N = pkg.instrumentation.size();
8202         r = null;
8203         for (i=0; i<N; i++) {
8204             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8205             mInstrumentation.remove(a.getComponentName());
8206             if (DEBUG_REMOVE && chatty) {
8207                 if (r == null) {
8208                     r = new StringBuilder(256);
8209                 } else {
8210                     r.append(' ');
8211                 }
8212                 r.append(a.info.name);
8213             }
8214         }
8215         if (r != null) {
8216             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8217         }
8218
8219         r = null;
8220         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8221             // Only system apps can hold shared libraries.
8222             if (pkg.libraryNames != null) {
8223                 for (i=0; i<pkg.libraryNames.size(); i++) {
8224                     String name = pkg.libraryNames.get(i);
8225                     SharedLibraryEntry cur = mSharedLibraries.get(name);
8226                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8227                         mSharedLibraries.remove(name);
8228                         if (DEBUG_REMOVE && chatty) {
8229                             if (r == null) {
8230                                 r = new StringBuilder(256);
8231                             } else {
8232                                 r.append(' ');
8233                             }
8234                             r.append(name);
8235                         }
8236                     }
8237                 }
8238             }
8239         }
8240         if (r != null) {
8241             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8242         }
8243     }
8244
8245     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8246         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8247             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8248                 return true;
8249             }
8250         }
8251         return false;
8252     }
8253
8254     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8255     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8256     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8257
8258     private void updatePermissionsLPw(String changingPkg,
8259             PackageParser.Package pkgInfo, int flags) {
8260         // Make sure there are no dangling permission trees.
8261         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8262         while (it.hasNext()) {
8263             final BasePermission bp = it.next();
8264             if (bp.packageSetting == null) {
8265                 // We may not yet have parsed the package, so just see if
8266                 // we still know about its settings.
8267                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8268             }
8269             if (bp.packageSetting == null) {
8270                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8271                         + " from package " + bp.sourcePackage);
8272                 it.remove();
8273             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8274                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8275                     Slog.i(TAG, "Removing old permission tree: " + bp.name
8276                             + " from package " + bp.sourcePackage);
8277                     flags |= UPDATE_PERMISSIONS_ALL;
8278                     it.remove();
8279                 }
8280             }
8281         }
8282
8283         // Make sure all dynamic permissions have been assigned to a package,
8284         // and make sure there are no dangling permissions.
8285         it = mSettings.mPermissions.values().iterator();
8286         while (it.hasNext()) {
8287             final BasePermission bp = it.next();
8288             if (bp.type == BasePermission.TYPE_DYNAMIC) {
8289                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8290                         + bp.name + " pkg=" + bp.sourcePackage
8291                         + " info=" + bp.pendingInfo);
8292                 if (bp.packageSetting == null && bp.pendingInfo != null) {
8293                     final BasePermission tree = findPermissionTreeLP(bp.name);
8294                     if (tree != null && tree.perm != null) {
8295                         bp.packageSetting = tree.packageSetting;
8296                         bp.perm = new PackageParser.Permission(tree.perm.owner,
8297                                 new PermissionInfo(bp.pendingInfo));
8298                         bp.perm.info.packageName = tree.perm.info.packageName;
8299                         bp.perm.info.name = bp.name;
8300                         bp.uid = tree.uid;
8301                     }
8302                 }
8303             }
8304             if (bp.packageSetting == null) {
8305                 // We may not yet have parsed the package, so just see if
8306                 // we still know about its settings.
8307                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8308             }
8309             if (bp.packageSetting == null) {
8310                 Slog.w(TAG, "Removing dangling permission: " + bp.name
8311                         + " from package " + bp.sourcePackage);
8312                 it.remove();
8313             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8314                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8315                     Slog.i(TAG, "Removing old permission: " + bp.name
8316                             + " from package " + bp.sourcePackage);
8317                     flags |= UPDATE_PERMISSIONS_ALL;
8318                     it.remove();
8319                 }
8320             }
8321         }
8322
8323         // Now update the permissions for all packages, in particular
8324         // replace the granted permissions of the system packages.
8325         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8326             for (PackageParser.Package pkg : mPackages.values()) {
8327                 if (pkg != pkgInfo) {
8328                     grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8329                             changingPkg);
8330                 }
8331             }
8332         }
8333
8334         if (pkgInfo != null) {
8335             grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8336         }
8337     }
8338
8339     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8340             String packageOfInterest) {
8341         // IMPORTANT: There are two types of permissions: install and runtime.
8342         // Install time permissions are granted when the app is installed to
8343         // all device users and users added in the future. Runtime permissions
8344         // are granted at runtime explicitly to specific users. Normal and signature
8345         // protected permissions are install time permissions. Dangerous permissions
8346         // are install permissions if the app's target SDK is Lollipop MR1 or older,
8347         // otherwise they are runtime permissions. This function does not manage
8348         // runtime permissions except for the case an app targeting Lollipop MR1
8349         // being upgraded to target a newer SDK, in which case dangerous permissions
8350         // are transformed from install time to runtime ones.
8351
8352         final PackageSetting ps = (PackageSetting) pkg.mExtras;
8353         if (ps == null) {
8354             return;
8355         }
8356
8357         PermissionsState permissionsState = ps.getPermissionsState();
8358         PermissionsState origPermissions = permissionsState;
8359
8360         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8361
8362         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8363
8364         boolean changedInstallPermission = false;
8365
8366         if (replace) {
8367             ps.installPermissionsFixed = false;
8368             if (!ps.isSharedUser()) {
8369                 origPermissions = new PermissionsState(permissionsState);
8370                 permissionsState.reset();
8371             }
8372         }
8373
8374         permissionsState.setGlobalGids(mGlobalGids);
8375
8376         final int N = pkg.requestedPermissions.size();
8377         for (int i=0; i<N; i++) {
8378             final String name = pkg.requestedPermissions.get(i);
8379             final BasePermission bp = mSettings.mPermissions.get(name);
8380
8381             if (DEBUG_INSTALL) {
8382                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8383             }
8384
8385             if (bp == null || bp.packageSetting == null) {
8386                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8387                     Slog.w(TAG, "Unknown permission " + name
8388                             + " in package " + pkg.packageName);
8389                 }
8390                 continue;
8391             }
8392
8393             final String perm = bp.name;
8394             boolean allowedSig = false;
8395             int grant = GRANT_DENIED;
8396
8397             // Keep track of app op permissions.
8398             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8399                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8400                 if (pkgs == null) {
8401                     pkgs = new ArraySet<>();
8402                     mAppOpPermissionPackages.put(bp.name, pkgs);
8403                 }
8404                 pkgs.add(pkg.packageName);
8405             }
8406
8407             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8408             switch (level) {
8409                 case PermissionInfo.PROTECTION_NORMAL: {
8410                     // For all apps normal permissions are install time ones.
8411                     grant = GRANT_INSTALL;
8412                 } break;
8413
8414                 case PermissionInfo.PROTECTION_DANGEROUS: {
8415                     if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8416                         // For legacy apps dangerous permissions are install time ones.
8417                         grant = GRANT_INSTALL_LEGACY;
8418                     } else if (origPermissions.hasInstallPermission(bp.name)) {
8419                         // For legacy apps that became modern, install becomes runtime.
8420                         grant = GRANT_UPGRADE;
8421                     } else if (mPromoteSystemApps
8422                             && isSystemApp(ps)
8423                             && mExistingSystemPackages.contains(ps.name)) {
8424                         // For legacy system apps, install becomes runtime.
8425                         // We cannot check hasInstallPermission() for system apps since those
8426                         // permissions were granted implicitly and not persisted pre-M.
8427                         grant = GRANT_UPGRADE;
8428                     } else {
8429                         // For modern apps keep runtime permissions unchanged.
8430                         grant = GRANT_RUNTIME;
8431                     }
8432                 } break;
8433
8434                 case PermissionInfo.PROTECTION_SIGNATURE: {
8435                     // For all apps signature permissions are install time ones.
8436                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8437                     if (allowedSig) {
8438                         grant = GRANT_INSTALL;
8439                     }
8440                 } break;
8441             }
8442
8443             if (DEBUG_INSTALL) {
8444                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8445             }
8446
8447             if (grant != GRANT_DENIED) {
8448                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8449                     // If this is an existing, non-system package, then
8450                     // we can't add any new permissions to it.
8451                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8452                         // Except...  if this is a permission that was added
8453                         // to the platform (note: need to only do this when
8454                         // updating the platform).
8455                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8456                             grant = GRANT_DENIED;
8457                         }
8458                     }
8459                 }
8460
8461                 switch (grant) {
8462                     case GRANT_INSTALL: {
8463                         // Revoke this as runtime permission to handle the case of
8464                         // a runtime permission being downgraded to an install one.
8465                         for (int userId : UserManagerService.getInstance().getUserIds()) {
8466                             if (origPermissions.getRuntimePermissionState(
8467                                     bp.name, userId) != null) {
8468                                 // Revoke the runtime permission and clear the flags.
8469                                 origPermissions.revokeRuntimePermission(bp, userId);
8470                                 origPermissions.updatePermissionFlags(bp, userId,
8471                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
8472                                 // If we revoked a permission permission, we have to write.
8473                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8474                                         changedRuntimePermissionUserIds, userId);
8475                             }
8476                         }
8477                         // Grant an install permission.
8478                         if (permissionsState.grantInstallPermission(bp) !=
8479                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8480                             changedInstallPermission = true;
8481                         }
8482                     } break;
8483
8484                     case GRANT_INSTALL_LEGACY: {
8485                         // Grant an install permission.
8486                         if (permissionsState.grantInstallPermission(bp) !=
8487                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
8488                             changedInstallPermission = true;
8489                         }
8490                     } break;
8491
8492                     case GRANT_RUNTIME: {
8493                         // Grant previously granted runtime permissions.
8494                         for (int userId : UserManagerService.getInstance().getUserIds()) {
8495                             PermissionState permissionState = origPermissions
8496                                     .getRuntimePermissionState(bp.name, userId);
8497                             final int flags = permissionState != null
8498                                     ? permissionState.getFlags() : 0;
8499                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8500                                 if (permissionsState.grantRuntimePermission(bp, userId) ==
8501                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8502                                     // If we cannot put the permission as it was, we have to write.
8503                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8504                                             changedRuntimePermissionUserIds, userId);
8505                                 }
8506                             }
8507                             // Propagate the permission flags.
8508                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8509                         }
8510                     } break;
8511
8512                     case GRANT_UPGRADE: {
8513                         // Grant runtime permissions for a previously held install permission.
8514                         PermissionState permissionState = origPermissions
8515                                 .getInstallPermissionState(bp.name);
8516                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
8517
8518                         if (origPermissions.revokeInstallPermission(bp)
8519                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8520                             // We will be transferring the permission flags, so clear them.
8521                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8522                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
8523                             changedInstallPermission = true;
8524                         }
8525
8526                         // If the permission is not to be promoted to runtime we ignore it and
8527                         // also its other flags as they are not applicable to install permissions.
8528                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8529                             for (int userId : currentUserIds) {
8530                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
8531                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8532                                     // Transfer the permission flags.
8533                                     permissionsState.updatePermissionFlags(bp, userId,
8534                                             flags, flags);
8535                                     // If we granted the permission, we have to write.
8536                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8537                                             changedRuntimePermissionUserIds, userId);
8538                                 }
8539                             }
8540                         }
8541                     } break;
8542
8543                     default: {
8544                         if (packageOfInterest == null
8545                                 || packageOfInterest.equals(pkg.packageName)) {
8546                             Slog.w(TAG, "Not granting permission " + perm
8547                                     + " to package " + pkg.packageName
8548                                     + " because it was previously installed without");
8549                         }
8550                     } break;
8551                 }
8552             } else {
8553                 if (permissionsState.revokeInstallPermission(bp) !=
8554                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
8555                     // Also drop the permission flags.
8556                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8557                             PackageManager.MASK_PERMISSION_FLAGS, 0);
8558                     changedInstallPermission = true;
8559                     Slog.i(TAG, "Un-granting permission " + perm
8560                             + " from package " + pkg.packageName
8561                             + " (protectionLevel=" + bp.protectionLevel
8562                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8563                             + ")");
8564                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8565                     // Don't print warning for app op permissions, since it is fine for them
8566                     // not to be granted, there is a UI for the user to decide.
8567                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8568                         Slog.w(TAG, "Not granting permission " + perm
8569                                 + " to package " + pkg.packageName
8570                                 + " (protectionLevel=" + bp.protectionLevel
8571                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8572                                 + ")");
8573                     }
8574                 }
8575             }
8576         }
8577
8578         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8579                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8580             // This is the first that we have heard about this package, so the
8581             // permissions we have now selected are fixed until explicitly
8582             // changed.
8583             ps.installPermissionsFixed = true;
8584         }
8585
8586         // Persist the runtime permissions state for users with changes.
8587         for (int userId : changedRuntimePermissionUserIds) {
8588             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8589         }
8590     }
8591
8592     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8593         boolean allowed = false;
8594         final int NP = PackageParser.NEW_PERMISSIONS.length;
8595         for (int ip=0; ip<NP; ip++) {
8596             final PackageParser.NewPermissionInfo npi
8597                     = PackageParser.NEW_PERMISSIONS[ip];
8598             if (npi.name.equals(perm)
8599                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8600                 allowed = true;
8601                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8602                         + pkg.packageName);
8603                 break;
8604             }
8605         }
8606         return allowed;
8607     }
8608
8609     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8610             BasePermission bp, PermissionsState origPermissions) {
8611         boolean allowed;
8612         allowed = (compareSignatures(
8613                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8614                         == PackageManager.SIGNATURE_MATCH)
8615                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8616                         == PackageManager.SIGNATURE_MATCH);
8617         if (!allowed && (bp.protectionLevel
8618                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8619             if (isSystemApp(pkg)) {
8620                 // For updated system applications, a system permission
8621                 // is granted only if it had been defined by the original application.
8622                 if (pkg.isUpdatedSystemApp()) {
8623                     final PackageSetting sysPs = mSettings
8624                             .getDisabledSystemPkgLPr(pkg.packageName);
8625                     if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8626                         // If the original was granted this permission, we take
8627                         // that grant decision as read and propagate it to the
8628                         // update.
8629                         if (sysPs.isPrivileged()) {
8630                             allowed = true;
8631                         }
8632                     } else {
8633                         // The system apk may have been updated with an older
8634                         // version of the one on the data partition, but which
8635                         // granted a new system permission that it didn't have
8636                         // before.  In this case we do want to allow the app to
8637                         // now get the new permission if the ancestral apk is
8638                         // privileged to get it.
8639                         if (sysPs.pkg != null && sysPs.isPrivileged()) {
8640                             for (int j=0;
8641                                     j<sysPs.pkg.requestedPermissions.size(); j++) {
8642                                 if (perm.equals(
8643                                         sysPs.pkg.requestedPermissions.get(j))) {
8644                                     allowed = true;
8645                                     break;
8646                                 }
8647                             }
8648                         }
8649                     }
8650                 } else {
8651                     allowed = isPrivilegedApp(pkg);
8652                 }
8653             }
8654         }
8655         if (!allowed) {
8656             if (!allowed && (bp.protectionLevel
8657                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8658                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8659                 // If this was a previously normal/dangerous permission that got moved
8660                 // to a system permission as part of the runtime permission redesign, then
8661                 // we still want to blindly grant it to old apps.
8662                 allowed = true;
8663             }
8664             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8665                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
8666                 // If this permission is to be granted to the system installer and
8667                 // this app is an installer, then it gets the permission.
8668                 allowed = true;
8669             }
8670             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8671                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
8672                 // If this permission is to be granted to the system verifier and
8673                 // this app is a verifier, then it gets the permission.
8674                 allowed = true;
8675             }
8676             if (!allowed && (bp.protectionLevel
8677                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8678                     && isSystemApp(pkg)) {
8679                 // Any pre-installed system app is allowed to get this permission.
8680                 allowed = true;
8681             }
8682             if (!allowed && (bp.protectionLevel
8683                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8684                 // For development permissions, a development permission
8685                 // is granted only if it was already granted.
8686                 allowed = origPermissions.hasInstallPermission(perm);
8687             }
8688         }
8689         return allowed;
8690     }
8691
8692     final class ActivityIntentResolver
8693             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8694         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8695                 boolean defaultOnly, int userId) {
8696             if (!sUserManager.exists(userId)) return null;
8697             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8698             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8699         }
8700
8701         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8702                 int userId) {
8703             if (!sUserManager.exists(userId)) return null;
8704             mFlags = flags;
8705             return super.queryIntent(intent, resolvedType,
8706                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8707         }
8708
8709         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8710                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8711             if (!sUserManager.exists(userId)) return null;
8712             if (packageActivities == null) {
8713                 return null;
8714             }
8715             mFlags = flags;
8716             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8717             final int N = packageActivities.size();
8718             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8719                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8720
8721             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8722             for (int i = 0; i < N; ++i) {
8723                 intentFilters = packageActivities.get(i).intents;
8724                 if (intentFilters != null && intentFilters.size() > 0) {
8725                     PackageParser.ActivityIntentInfo[] array =
8726                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
8727                     intentFilters.toArray(array);
8728                     listCut.add(array);
8729                 }
8730             }
8731             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8732         }
8733
8734         /**
8735          * Finds a privileged activity that matches the specified activity names.
8736          */
8737         private PackageParser.Activity findMatchingActivity(
8738                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
8739             for (PackageParser.Activity sysActivity : activityList) {
8740                 if (sysActivity.info.name.equals(activityInfo.name)) {
8741                     return sysActivity;
8742                 }
8743                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
8744                     return sysActivity;
8745                 }
8746                 if (sysActivity.info.targetActivity != null) {
8747                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
8748                         return sysActivity;
8749                     }
8750                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
8751                         return sysActivity;
8752                     }
8753                 }
8754             }
8755             return null;
8756         }
8757
8758         public class IterGenerator<E> {
8759             public Iterator<E> generate(ActivityIntentInfo info) {
8760                 return null;
8761             }
8762         }
8763
8764         public class ActionIterGenerator extends IterGenerator<String> {
8765             @Override
8766             public Iterator<String> generate(ActivityIntentInfo info) {
8767                 return info.actionsIterator();
8768             }
8769         }
8770
8771         public class CategoriesIterGenerator extends IterGenerator<String> {
8772             @Override
8773             public Iterator<String> generate(ActivityIntentInfo info) {
8774                 return info.categoriesIterator();
8775             }
8776         }
8777
8778         public class SchemesIterGenerator extends IterGenerator<String> {
8779             @Override
8780             public Iterator<String> generate(ActivityIntentInfo info) {
8781                 return info.schemesIterator();
8782             }
8783         }
8784
8785         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
8786             @Override
8787             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
8788                 return info.authoritiesIterator();
8789             }
8790         }
8791
8792         /**
8793          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
8794          * MODIFIED. Do not pass in a list that should not be changed.
8795          */
8796         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
8797                 IterGenerator<T> generator, Iterator<T> searchIterator) {
8798             // loop through the set of actions; every one must be found in the intent filter
8799             while (searchIterator.hasNext()) {
8800                 // we must have at least one filter in the list to consider a match
8801                 if (intentList.size() == 0) {
8802                     break;
8803                 }
8804
8805                 final T searchAction = searchIterator.next();
8806
8807                 // loop through the set of intent filters
8808                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
8809                 while (intentIter.hasNext()) {
8810                     final ActivityIntentInfo intentInfo = intentIter.next();
8811                     boolean selectionFound = false;
8812
8813                     // loop through the intent filter's selection criteria; at least one
8814                     // of them must match the searched criteria
8815                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
8816                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
8817                         final T intentSelection = intentSelectionIter.next();
8818                         if (intentSelection != null && intentSelection.equals(searchAction)) {
8819                             selectionFound = true;
8820                             break;
8821                         }
8822                     }
8823
8824                     // the selection criteria wasn't found in this filter's set; this filter
8825                     // is not a potential match
8826                     if (!selectionFound) {
8827                         intentIter.remove();
8828                     }
8829                 }
8830             }
8831         }
8832
8833         /**
8834          * Adjusts the priority of the given intent filter according to policy.
8835          * <p>
8836          * <ul>
8837          * <li>The priority for unbundled updates to system applications is capped to the
8838          *      priority defined on the system partition</li>
8839          * </ul>
8840          */
8841         private void adjustPriority(
8842                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
8843             // nothing to do; priority is fine as-is
8844             if (intent.getPriority() <= 0) {
8845                 return;
8846             }
8847
8848             final ActivityInfo activityInfo = intent.activity.info;
8849             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
8850
8851             final boolean systemApp = applicationInfo.isSystemApp();
8852             if (!systemApp) {
8853                 // non-system applications can never define a priority >0
8854                 Slog.w(TAG, "Non-system app; cap priority to 0;"
8855                         + " package: " + applicationInfo.packageName
8856                         + " activity: " + intent.activity.className
8857                         + " origPrio: " + intent.getPriority());
8858                 intent.setPriority(0);
8859                 return;
8860             }
8861
8862             if (systemActivities == null) {
8863                 // the system package is not disabled; we're parsing the system partition
8864                 // apps on the system image get whatever priority they request
8865                 return;
8866             }
8867
8868             // system app unbundled update ... try to find the same activity
8869             final PackageParser.Activity foundActivity =
8870                     findMatchingActivity(systemActivities, activityInfo);
8871             if (foundActivity == null) {
8872                 // this is a new activity; it cannot obtain >0 priority
8873                 if (DEBUG_FILTERS) {
8874                     Slog.i(TAG, "New activity; cap priority to 0;"
8875                             + " package: " + applicationInfo.packageName
8876                             + " activity: " + intent.activity.className
8877                             + " origPrio: " + intent.getPriority());
8878                 }
8879                 intent.setPriority(0);
8880                 return;
8881             }
8882
8883             // found activity, now check for filter equivalence
8884
8885             // a shallow copy is enough; we modify the list, not its contents
8886             final List<ActivityIntentInfo> intentListCopy =
8887                     new ArrayList<>(foundActivity.intents);
8888             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
8889
8890             // find matching action subsets
8891             final Iterator<String> actionsIterator = intent.actionsIterator();
8892             if (actionsIterator != null) {
8893                 getIntentListSubset(
8894                         intentListCopy, new ActionIterGenerator(), actionsIterator);
8895                 if (intentListCopy.size() == 0) {
8896                     // no more intents to match; we're not equivalent
8897                     if (DEBUG_FILTERS) {
8898                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
8899                                 + " package: " + applicationInfo.packageName
8900                                 + " activity: " + intent.activity.className
8901                                 + " origPrio: " + intent.getPriority());
8902                     }
8903                     intent.setPriority(0);
8904                     return;
8905                 }
8906             }
8907
8908             // find matching category subsets
8909             final Iterator<String> categoriesIterator = intent.categoriesIterator();
8910             if (categoriesIterator != null) {
8911                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
8912                         categoriesIterator);
8913                 if (intentListCopy.size() == 0) {
8914                     // no more intents to match; we're not equivalent
8915                     if (DEBUG_FILTERS) {
8916                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
8917                                 + " package: " + applicationInfo.packageName
8918                                 + " activity: " + intent.activity.className
8919                                 + " origPrio: " + intent.getPriority());
8920                     }
8921                     intent.setPriority(0);
8922                     return;
8923                 }
8924             }
8925
8926             // find matching schemes subsets
8927             final Iterator<String> schemesIterator = intent.schemesIterator();
8928             if (schemesIterator != null) {
8929                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
8930                         schemesIterator);
8931                 if (intentListCopy.size() == 0) {
8932                     // no more intents to match; we're not equivalent
8933                     if (DEBUG_FILTERS) {
8934                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
8935                                 + " package: " + applicationInfo.packageName
8936                                 + " activity: " + intent.activity.className
8937                                 + " origPrio: " + intent.getPriority());
8938                     }
8939                     intent.setPriority(0);
8940                     return;
8941                 }
8942             }
8943
8944             // find matching authorities subsets
8945             final Iterator<IntentFilter.AuthorityEntry>
8946                     authoritiesIterator = intent.authoritiesIterator();
8947             if (authoritiesIterator != null) {
8948                 getIntentListSubset(intentListCopy,
8949                         new AuthoritiesIterGenerator(),
8950                         authoritiesIterator);
8951                 if (intentListCopy.size() == 0) {
8952                     // no more intents to match; we're not equivalent
8953                     if (DEBUG_FILTERS) {
8954                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
8955                                 + " package: " + applicationInfo.packageName
8956                                 + " activity: " + intent.activity.className
8957                                 + " origPrio: " + intent.getPriority());
8958                     }
8959                     intent.setPriority(0);
8960                     return;
8961                 }
8962             }
8963
8964             // we found matching filter(s); app gets the max priority of all intents
8965             int cappedPriority = 0;
8966             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
8967                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
8968             }
8969             if (intent.getPriority() > cappedPriority) {
8970                 if (DEBUG_FILTERS) {
8971                     Slog.i(TAG, "Found matching filter(s);"
8972                             + " cap priority to " + cappedPriority + ";"
8973                             + " package: " + applicationInfo.packageName
8974                             + " activity: " + intent.activity.className
8975                             + " origPrio: " + intent.getPriority());
8976                 }
8977                 intent.setPriority(cappedPriority);
8978                 return;
8979             }
8980             // all this for nothing; the requested priority was <= what was on the system
8981         }
8982
8983         public final void addActivity(PackageParser.Activity a, String type) {
8984             final boolean systemApp = a.info.applicationInfo.isSystemApp();
8985             mActivities.put(a.getComponentName(), a);
8986             if (DEBUG_SHOW_INFO)
8987                 Log.v(
8988                 TAG, "  " + type + " " +
8989                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8990             if (DEBUG_SHOW_INFO)
8991                 Log.v(TAG, "    Class=" + a.info.name);
8992             final int NI = a.intents.size();
8993             for (int j=0; j<NI; j++) {
8994                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8995                 if ("activity".equals(type)) {
8996                     final PackageSetting ps =
8997                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
8998                     final List<PackageParser.Activity> systemActivities =
8999                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
9000                     adjustPriority(systemActivities, intent);
9001                 }
9002                 if (DEBUG_SHOW_INFO) {
9003                     Log.v(TAG, "    IntentFilter:");
9004                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9005                 }
9006                 if (!intent.debugCheck()) {
9007                     Log.w(TAG, "==> For Activity " + a.info.name);
9008                 }
9009                 addFilter(intent);
9010             }
9011         }
9012
9013         public final void removeActivity(PackageParser.Activity a, String type) {
9014             mActivities.remove(a.getComponentName());
9015             if (DEBUG_SHOW_INFO) {
9016                 Log.v(TAG, "  " + type + " "
9017                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9018                                 : a.info.name) + ":");
9019                 Log.v(TAG, "    Class=" + a.info.name);
9020             }
9021             final int NI = a.intents.size();
9022             for (int j=0; j<NI; j++) {
9023                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9024                 if (DEBUG_SHOW_INFO) {
9025                     Log.v(TAG, "    IntentFilter:");
9026                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9027                 }
9028                 removeFilter(intent);
9029             }
9030         }
9031
9032         @Override
9033         protected boolean allowFilterResult(
9034                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9035             ActivityInfo filterAi = filter.activity.info;
9036             for (int i=dest.size()-1; i>=0; i--) {
9037                 ActivityInfo destAi = dest.get(i).activityInfo;
9038                 if (destAi.name == filterAi.name
9039                         && destAi.packageName == filterAi.packageName) {
9040                     return false;
9041                 }
9042             }
9043             return true;
9044         }
9045
9046         @Override
9047         protected ActivityIntentInfo[] newArray(int size) {
9048             return new ActivityIntentInfo[size];
9049         }
9050
9051         @Override
9052         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9053             if (!sUserManager.exists(userId)) return true;
9054             PackageParser.Package p = filter.activity.owner;
9055             if (p != null) {
9056                 PackageSetting ps = (PackageSetting)p.mExtras;
9057                 if (ps != null) {
9058                     // System apps are never considered stopped for purposes of
9059                     // filtering, because there may be no way for the user to
9060                     // actually re-launch them.
9061                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9062                             && ps.getStopped(userId);
9063                 }
9064             }
9065             return false;
9066         }
9067
9068         @Override
9069         protected boolean isPackageForFilter(String packageName,
9070                 PackageParser.ActivityIntentInfo info) {
9071             return packageName.equals(info.activity.owner.packageName);
9072         }
9073
9074         @Override
9075         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9076                 int match, int userId) {
9077             if (!sUserManager.exists(userId)) return null;
9078             if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
9079                 return null;
9080             }
9081             final PackageParser.Activity activity = info.activity;
9082             if (mSafeMode && (activity.info.applicationInfo.flags
9083                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
9084                 return null;
9085             }
9086             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9087             if (ps == null) {
9088                 return null;
9089             }
9090             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9091                     ps.readUserState(userId), userId);
9092             if (ai == null) {
9093                 return null;
9094             }
9095             final ResolveInfo res = new ResolveInfo();
9096             res.activityInfo = ai;
9097             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9098                 res.filter = info;
9099             }
9100             if (info != null) {
9101                 res.handleAllWebDataURI = info.handleAllWebDataURI();
9102             }
9103             res.priority = info.getPriority();
9104             res.preferredOrder = activity.owner.mPreferredOrder;
9105             //System.out.println("Result: " + res.activityInfo.className +
9106             //                   " = " + res.priority);
9107             res.match = match;
9108             res.isDefault = info.hasDefault;
9109             res.labelRes = info.labelRes;
9110             res.nonLocalizedLabel = info.nonLocalizedLabel;
9111             if (userNeedsBadging(userId)) {
9112                 res.noResourceId = true;
9113             } else {
9114                 res.icon = info.icon;
9115             }
9116             res.iconResourceId = info.icon;
9117             res.system = res.activityInfo.applicationInfo.isSystemApp();
9118             return res;
9119         }
9120
9121         @Override
9122         protected void sortResults(List<ResolveInfo> results) {
9123             Collections.sort(results, mResolvePrioritySorter);
9124         }
9125
9126         @Override
9127         protected void dumpFilter(PrintWriter out, String prefix,
9128                 PackageParser.ActivityIntentInfo filter) {
9129             out.print(prefix); out.print(
9130                     Integer.toHexString(System.identityHashCode(filter.activity)));
9131                     out.print(' ');
9132                     filter.activity.printComponentShortName(out);
9133                     out.print(" filter ");
9134                     out.println(Integer.toHexString(System.identityHashCode(filter)));
9135         }
9136
9137         @Override
9138         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9139             return filter.activity;
9140         }
9141
9142         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9143             PackageParser.Activity activity = (PackageParser.Activity)label;
9144             out.print(prefix); out.print(
9145                     Integer.toHexString(System.identityHashCode(activity)));
9146                     out.print(' ');
9147                     activity.printComponentShortName(out);
9148             if (count > 1) {
9149                 out.print(" ("); out.print(count); out.print(" filters)");
9150             }
9151             out.println();
9152         }
9153
9154         // Keys are String (activity class name), values are Activity.
9155         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9156                 = new ArrayMap<ComponentName, PackageParser.Activity>();
9157         private int mFlags;
9158     }
9159
9160     private final class ServiceIntentResolver
9161             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9162         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9163                 boolean defaultOnly, int userId) {
9164             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9165             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9166         }
9167
9168         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9169                 int userId) {
9170             if (!sUserManager.exists(userId)) return null;
9171             mFlags = flags;
9172             return super.queryIntent(intent, resolvedType,
9173                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9174         }
9175
9176         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9177                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9178             if (!sUserManager.exists(userId)) return null;
9179             if (packageServices == null) {
9180                 return null;
9181             }
9182             mFlags = flags;
9183             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9184             final int N = packageServices.size();
9185             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9186                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9187
9188             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9189             for (int i = 0; i < N; ++i) {
9190                 intentFilters = packageServices.get(i).intents;
9191                 if (intentFilters != null && intentFilters.size() > 0) {
9192                     PackageParser.ServiceIntentInfo[] array =
9193                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
9194                     intentFilters.toArray(array);
9195                     listCut.add(array);
9196                 }
9197             }
9198             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9199         }
9200
9201         public final void addService(PackageParser.Service s) {
9202             mServices.put(s.getComponentName(), s);
9203             if (DEBUG_SHOW_INFO) {
9204                 Log.v(TAG, "  "
9205                         + (s.info.nonLocalizedLabel != null
9206                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
9207                 Log.v(TAG, "    Class=" + s.info.name);
9208             }
9209             final int NI = s.intents.size();
9210             int j;
9211             for (j=0; j<NI; j++) {
9212                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9213                 if (DEBUG_SHOW_INFO) {
9214                     Log.v(TAG, "    IntentFilter:");
9215                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9216                 }
9217                 if (!intent.debugCheck()) {
9218                     Log.w(TAG, "==> For Service " + s.info.name);
9219                 }
9220                 addFilter(intent);
9221             }
9222         }
9223
9224         public final void removeService(PackageParser.Service s) {
9225             mServices.remove(s.getComponentName());
9226             if (DEBUG_SHOW_INFO) {
9227                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9228                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
9229                 Log.v(TAG, "    Class=" + s.info.name);
9230             }
9231             final int NI = s.intents.size();
9232             int j;
9233             for (j=0; j<NI; j++) {
9234                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9235                 if (DEBUG_SHOW_INFO) {
9236                     Log.v(TAG, "    IntentFilter:");
9237                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9238                 }
9239                 removeFilter(intent);
9240             }
9241         }
9242
9243         @Override
9244         protected boolean allowFilterResult(
9245                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9246             ServiceInfo filterSi = filter.service.info;
9247             for (int i=dest.size()-1; i>=0; i--) {
9248                 ServiceInfo destAi = dest.get(i).serviceInfo;
9249                 if (destAi.name == filterSi.name
9250                         && destAi.packageName == filterSi.packageName) {
9251                     return false;
9252                 }
9253             }
9254             return true;
9255         }
9256
9257         @Override
9258         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9259             return new PackageParser.ServiceIntentInfo[size];
9260         }
9261
9262         @Override
9263         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9264             if (!sUserManager.exists(userId)) return true;
9265             PackageParser.Package p = filter.service.owner;
9266             if (p != null) {
9267                 PackageSetting ps = (PackageSetting)p.mExtras;
9268                 if (ps != null) {
9269                     // System apps are never considered stopped for purposes of
9270                     // filtering, because there may be no way for the user to
9271                     // actually re-launch them.
9272                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9273                             && ps.getStopped(userId);
9274                 }
9275             }
9276             return false;
9277         }
9278
9279         @Override
9280         protected boolean isPackageForFilter(String packageName,
9281                 PackageParser.ServiceIntentInfo info) {
9282             return packageName.equals(info.service.owner.packageName);
9283         }
9284
9285         @Override
9286         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9287                 int match, int userId) {
9288             if (!sUserManager.exists(userId)) return null;
9289             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9290             if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9291                 return null;
9292             }
9293             final PackageParser.Service service = info.service;
9294             if (mSafeMode && (service.info.applicationInfo.flags
9295                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
9296                 return null;
9297             }
9298             PackageSetting ps = (PackageSetting) service.owner.mExtras;
9299             if (ps == null) {
9300                 return null;
9301             }
9302             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9303                     ps.readUserState(userId), userId);
9304             if (si == null) {
9305                 return null;
9306             }
9307             final ResolveInfo res = new ResolveInfo();
9308             res.serviceInfo = si;
9309             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9310                 res.filter = filter;
9311             }
9312             res.priority = info.getPriority();
9313             res.preferredOrder = service.owner.mPreferredOrder;
9314             res.match = match;
9315             res.isDefault = info.hasDefault;
9316             res.labelRes = info.labelRes;
9317             res.nonLocalizedLabel = info.nonLocalizedLabel;
9318             res.icon = info.icon;
9319             res.system = res.serviceInfo.applicationInfo.isSystemApp();
9320             return res;
9321         }
9322
9323         @Override
9324         protected void sortResults(List<ResolveInfo> results) {
9325             Collections.sort(results, mResolvePrioritySorter);
9326         }
9327
9328         @Override
9329         protected void dumpFilter(PrintWriter out, String prefix,
9330                 PackageParser.ServiceIntentInfo filter) {
9331             out.print(prefix); out.print(
9332                     Integer.toHexString(System.identityHashCode(filter.service)));
9333                     out.print(' ');
9334                     filter.service.printComponentShortName(out);
9335                     out.print(" filter ");
9336                     out.println(Integer.toHexString(System.identityHashCode(filter)));
9337         }
9338
9339         @Override
9340         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9341             return filter.service;
9342         }
9343
9344         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9345             PackageParser.Service service = (PackageParser.Service)label;
9346             out.print(prefix); out.print(
9347                     Integer.toHexString(System.identityHashCode(service)));
9348                     out.print(' ');
9349                     service.printComponentShortName(out);
9350             if (count > 1) {
9351                 out.print(" ("); out.print(count); out.print(" filters)");
9352             }
9353             out.println();
9354         }
9355
9356 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9357 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9358 //            final List<ResolveInfo> retList = Lists.newArrayList();
9359 //            while (i.hasNext()) {
9360 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
9361 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
9362 //                    retList.add(resolveInfo);
9363 //                }
9364 //            }
9365 //            return retList;
9366 //        }
9367
9368         // Keys are String (activity class name), values are Activity.
9369         private final ArrayMap<ComponentName, PackageParser.Service> mServices
9370                 = new ArrayMap<ComponentName, PackageParser.Service>();
9371         private int mFlags;
9372     };
9373
9374     private final class ProviderIntentResolver
9375             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9376         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9377                 boolean defaultOnly, int userId) {
9378             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9379             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9380         }
9381
9382         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9383                 int userId) {
9384             if (!sUserManager.exists(userId))
9385                 return null;
9386             mFlags = flags;
9387             return super.queryIntent(intent, resolvedType,
9388                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9389         }
9390
9391         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9392                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9393             if (!sUserManager.exists(userId))
9394                 return null;
9395             if (packageProviders == null) {
9396                 return null;
9397             }
9398             mFlags = flags;
9399             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9400             final int N = packageProviders.size();
9401             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9402                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9403
9404             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9405             for (int i = 0; i < N; ++i) {
9406                 intentFilters = packageProviders.get(i).intents;
9407                 if (intentFilters != null && intentFilters.size() > 0) {
9408                     PackageParser.ProviderIntentInfo[] array =
9409                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
9410                     intentFilters.toArray(array);
9411                     listCut.add(array);
9412                 }
9413             }
9414             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9415         }
9416
9417         public final void addProvider(PackageParser.Provider p) {
9418             if (mProviders.containsKey(p.getComponentName())) {
9419                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9420                 return;
9421             }
9422
9423             mProviders.put(p.getComponentName(), p);
9424             if (DEBUG_SHOW_INFO) {
9425                 Log.v(TAG, "  "
9426                         + (p.info.nonLocalizedLabel != null
9427                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
9428                 Log.v(TAG, "    Class=" + p.info.name);
9429             }
9430             final int NI = p.intents.size();
9431             int j;
9432             for (j = 0; j < NI; j++) {
9433                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9434                 if (DEBUG_SHOW_INFO) {
9435                     Log.v(TAG, "    IntentFilter:");
9436                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9437                 }
9438                 if (!intent.debugCheck()) {
9439                     Log.w(TAG, "==> For Provider " + p.info.name);
9440                 }
9441                 addFilter(intent);
9442             }
9443         }
9444
9445         public final void removeProvider(PackageParser.Provider p) {
9446             mProviders.remove(p.getComponentName());
9447             if (DEBUG_SHOW_INFO) {
9448                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9449                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
9450                 Log.v(TAG, "    Class=" + p.info.name);
9451             }
9452             final int NI = p.intents.size();
9453             int j;
9454             for (j = 0; j < NI; j++) {
9455                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9456                 if (DEBUG_SHOW_INFO) {
9457                     Log.v(TAG, "    IntentFilter:");
9458                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9459                 }
9460                 removeFilter(intent);
9461             }
9462         }
9463
9464         @Override
9465         protected boolean allowFilterResult(
9466                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9467             ProviderInfo filterPi = filter.provider.info;
9468             for (int i = dest.size() - 1; i >= 0; i--) {
9469                 ProviderInfo destPi = dest.get(i).providerInfo;
9470                 if (destPi.name == filterPi.name
9471                         && destPi.packageName == filterPi.packageName) {
9472                     return false;
9473                 }
9474             }
9475             return true;
9476         }
9477
9478         @Override
9479         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9480             return new PackageParser.ProviderIntentInfo[size];
9481         }
9482
9483         @Override
9484         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9485             if (!sUserManager.exists(userId))
9486                 return true;
9487             PackageParser.Package p = filter.provider.owner;
9488             if (p != null) {
9489                 PackageSetting ps = (PackageSetting) p.mExtras;
9490                 if (ps != null) {
9491                     // System apps are never considered stopped for purposes of
9492                     // filtering, because there may be no way for the user to
9493                     // actually re-launch them.
9494                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9495                             && ps.getStopped(userId);
9496                 }
9497             }
9498             return false;
9499         }
9500
9501         @Override
9502         protected boolean isPackageForFilter(String packageName,
9503                 PackageParser.ProviderIntentInfo info) {
9504             return packageName.equals(info.provider.owner.packageName);
9505         }
9506
9507         @Override
9508         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9509                 int match, int userId) {
9510             if (!sUserManager.exists(userId))
9511                 return null;
9512             final PackageParser.ProviderIntentInfo info = filter;
9513             if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9514                 return null;
9515             }
9516             final PackageParser.Provider provider = info.provider;
9517             if (mSafeMode && (provider.info.applicationInfo.flags
9518                     & ApplicationInfo.FLAG_SYSTEM) == 0) {
9519                 return null;
9520             }
9521             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9522             if (ps == null) {
9523                 return null;
9524             }
9525             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9526                     ps.readUserState(userId), userId);
9527             if (pi == null) {
9528                 return null;
9529             }
9530             final ResolveInfo res = new ResolveInfo();
9531             res.providerInfo = pi;
9532             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9533                 res.filter = filter;
9534             }
9535             res.priority = info.getPriority();
9536             res.preferredOrder = provider.owner.mPreferredOrder;
9537             res.match = match;
9538             res.isDefault = info.hasDefault;
9539             res.labelRes = info.labelRes;
9540             res.nonLocalizedLabel = info.nonLocalizedLabel;
9541             res.icon = info.icon;
9542             res.system = res.providerInfo.applicationInfo.isSystemApp();
9543             return res;
9544         }
9545
9546         @Override
9547         protected void sortResults(List<ResolveInfo> results) {
9548             Collections.sort(results, mResolvePrioritySorter);
9549         }
9550
9551         @Override
9552         protected void dumpFilter(PrintWriter out, String prefix,
9553                 PackageParser.ProviderIntentInfo filter) {
9554             out.print(prefix);
9555             out.print(
9556                     Integer.toHexString(System.identityHashCode(filter.provider)));
9557             out.print(' ');
9558             filter.provider.printComponentShortName(out);
9559             out.print(" filter ");
9560             out.println(Integer.toHexString(System.identityHashCode(filter)));
9561         }
9562
9563         @Override
9564         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9565             return filter.provider;
9566         }
9567
9568         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9569             PackageParser.Provider provider = (PackageParser.Provider)label;
9570             out.print(prefix); out.print(
9571                     Integer.toHexString(System.identityHashCode(provider)));
9572                     out.print(' ');
9573                     provider.printComponentShortName(out);
9574             if (count > 1) {
9575                 out.print(" ("); out.print(count); out.print(" filters)");
9576             }
9577             out.println();
9578         }
9579
9580         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9581                 = new ArrayMap<ComponentName, PackageParser.Provider>();
9582         private int mFlags;
9583     };
9584
9585     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9586             new Comparator<ResolveInfo>() {
9587         public int compare(ResolveInfo r1, ResolveInfo r2) {
9588             int v1 = r1.priority;
9589             int v2 = r2.priority;
9590             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9591             if (v1 != v2) {
9592                 return (v1 > v2) ? -1 : 1;
9593             }
9594             v1 = r1.preferredOrder;
9595             v2 = r2.preferredOrder;
9596             if (v1 != v2) {
9597                 return (v1 > v2) ? -1 : 1;
9598             }
9599             if (r1.isDefault != r2.isDefault) {
9600                 return r1.isDefault ? -1 : 1;
9601             }
9602             v1 = r1.match;
9603             v2 = r2.match;
9604             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9605             if (v1 != v2) {
9606                 return (v1 > v2) ? -1 : 1;
9607             }
9608             if (r1.system != r2.system) {
9609                 return r1.system ? -1 : 1;
9610             }
9611             return 0;
9612         }
9613     };
9614
9615     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9616             new Comparator<ProviderInfo>() {
9617         public int compare(ProviderInfo p1, ProviderInfo p2) {
9618             final int v1 = p1.initOrder;
9619             final int v2 = p2.initOrder;
9620             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9621         }
9622     };
9623
9624     final void sendPackageBroadcast(final String action, final String pkg,
9625             final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9626             final int[] userIds) {
9627         mHandler.post(new Runnable() {
9628             @Override
9629             public void run() {
9630                 try {
9631                     final IActivityManager am = ActivityManagerNative.getDefault();
9632                     if (am == null) return;
9633                     final int[] resolvedUserIds;
9634                     if (userIds == null) {
9635                         resolvedUserIds = am.getRunningUserIds();
9636                     } else {
9637                         resolvedUserIds = userIds;
9638                     }
9639                     for (int id : resolvedUserIds) {
9640                         final Intent intent = new Intent(action,
9641                                 pkg != null ? Uri.fromParts("package", pkg, null) : null);
9642                         if (extras != null) {
9643                             intent.putExtras(extras);
9644                         }
9645                         if (targetPkg != null) {
9646                             intent.setPackage(targetPkg);
9647                         }
9648                         // Modify the UID when posting to other users
9649                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9650                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
9651                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9652                             intent.putExtra(Intent.EXTRA_UID, uid);
9653                         }
9654                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9655                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9656                         if (DEBUG_BROADCASTS) {
9657                             RuntimeException here = new RuntimeException("here");
9658                             here.fillInStackTrace();
9659                             Slog.d(TAG, "Sending to user " + id + ": "
9660                                     + intent.toShortString(false, true, false, false)
9661                                     + " " + intent.getExtras(), here);
9662                         }
9663                         am.broadcastIntent(null, intent, null, finishedReceiver,
9664                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
9665                                 null, finishedReceiver != null, false, id);
9666                     }
9667                 } catch (RemoteException ex) {
9668                 }
9669             }
9670         });
9671     }
9672
9673     /**
9674      * Check if the external storage media is available. This is true if there
9675      * is a mounted external storage medium or if the external storage is
9676      * emulated.
9677      */
9678     private boolean isExternalMediaAvailable() {
9679         return mMediaMounted || Environment.isExternalStorageEmulated();
9680     }
9681
9682     @Override
9683     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9684         // writer
9685         synchronized (mPackages) {
9686             if (!isExternalMediaAvailable()) {
9687                 // If the external storage is no longer mounted at this point,
9688                 // the caller may not have been able to delete all of this
9689                 // packages files and can not delete any more.  Bail.
9690                 return null;
9691             }
9692             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9693             if (lastPackage != null) {
9694                 pkgs.remove(lastPackage);
9695             }
9696             if (pkgs.size() > 0) {
9697                 return pkgs.get(0);
9698             }
9699         }
9700         return null;
9701     }
9702
9703     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9704         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9705                 userId, andCode ? 1 : 0, packageName);
9706         if (mSystemReady) {
9707             msg.sendToTarget();
9708         } else {
9709             if (mPostSystemReadyMessages == null) {
9710                 mPostSystemReadyMessages = new ArrayList<>();
9711             }
9712             mPostSystemReadyMessages.add(msg);
9713         }
9714     }
9715
9716     void startCleaningPackages() {
9717         // reader
9718         synchronized (mPackages) {
9719             if (!isExternalMediaAvailable()) {
9720                 return;
9721             }
9722             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9723                 return;
9724             }
9725         }
9726         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9727         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9728         IActivityManager am = ActivityManagerNative.getDefault();
9729         if (am != null) {
9730             try {
9731                 am.startService(null, intent, null, mContext.getOpPackageName(),
9732                         UserHandle.USER_OWNER);
9733             } catch (RemoteException e) {
9734             }
9735         }
9736     }
9737
9738     @Override
9739     public void installPackage(String originPath, IPackageInstallObserver2 observer,
9740             int installFlags, String installerPackageName, VerificationParams verificationParams,
9741             String packageAbiOverride) {
9742         installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9743                 verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9744     }
9745
9746     @Override
9747     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9748             int installFlags, String installerPackageName, VerificationParams verificationParams,
9749             String packageAbiOverride, int userId) {
9750         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9751
9752         final int callingUid = Binder.getCallingUid();
9753         enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9754
9755         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9756             try {
9757                 if (observer != null) {
9758                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9759                 }
9760             } catch (RemoteException re) {
9761             }
9762             return;
9763         }
9764
9765         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9766             installFlags |= PackageManager.INSTALL_FROM_ADB;
9767
9768         } else {
9769             // Caller holds INSTALL_PACKAGES permission, so we're less strict
9770             // about installerPackageName.
9771
9772             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9773             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9774         }
9775
9776         UserHandle user;
9777         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9778             user = UserHandle.ALL;
9779         } else {
9780             user = new UserHandle(userId);
9781         }
9782
9783         // Only system components can circumvent runtime permissions when installing.
9784         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9785                 && mContext.checkCallingOrSelfPermission(Manifest.permission
9786                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9787             throw new SecurityException("You need the "
9788                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9789                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9790         }
9791
9792         verificationParams.setInstallerUid(callingUid);
9793
9794         final File originFile = new File(originPath);
9795         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9796
9797         final Message msg = mHandler.obtainMessage(INIT_COPY);
9798         msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9799                 null, verificationParams, user, packageAbiOverride, null);
9800         mHandler.sendMessage(msg);
9801     }
9802
9803     void installStage(String packageName, File stagedDir, String stagedCid,
9804             IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9805             String installerPackageName, int installerUid, UserHandle user) {
9806         final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9807                 params.referrerUri, installerUid, null);
9808         verifParams.setInstallerUid(installerUid);
9809
9810         final OriginInfo origin;
9811         if (stagedDir != null) {
9812             origin = OriginInfo.fromStagedFile(stagedDir);
9813         } else {
9814             origin = OriginInfo.fromStagedContainer(stagedCid);
9815         }
9816
9817         final Message msg = mHandler.obtainMessage(INIT_COPY);
9818         msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9819                 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9820                 params.grantedRuntimePermissions);
9821         mHandler.sendMessage(msg);
9822     }
9823
9824     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9825         Bundle extras = new Bundle(1);
9826         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9827
9828         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9829                 packageName, extras, null, null, new int[] {userId});
9830         try {
9831             IActivityManager am = ActivityManagerNative.getDefault();
9832             final boolean isSystem =
9833                     isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9834             if (isSystem && am.isUserRunning(userId, false)) {
9835                 // The just-installed/enabled app is bundled on the system, so presumed
9836                 // to be able to run automatically without needing an explicit launch.
9837                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9838                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9839                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9840                         .setPackage(packageName);
9841                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9842                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9843             }
9844         } catch (RemoteException e) {
9845             // shouldn't happen
9846             Slog.w(TAG, "Unable to bootstrap installed package", e);
9847         }
9848     }
9849
9850     @Override
9851     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9852             int userId) {
9853         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9854         PackageSetting pkgSetting;
9855         final int uid = Binder.getCallingUid();
9856         enforceCrossUserPermission(uid, userId, true, true,
9857                 "setApplicationHiddenSetting for user " + userId);
9858
9859         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9860             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9861             return false;
9862         }
9863
9864         long callingId = Binder.clearCallingIdentity();
9865         try {
9866             boolean sendAdded = false;
9867             boolean sendRemoved = false;
9868             // writer
9869             synchronized (mPackages) {
9870                 pkgSetting = mSettings.mPackages.get(packageName);
9871                 if (pkgSetting == null) {
9872                     return false;
9873                 }
9874                 if (pkgSetting.getHidden(userId) != hidden) {
9875                     pkgSetting.setHidden(hidden, userId);
9876                     mSettings.writePackageRestrictionsLPr(userId);
9877                     if (hidden) {
9878                         sendRemoved = true;
9879                     } else {
9880                         sendAdded = true;
9881                     }
9882                 }
9883             }
9884             if (sendAdded) {
9885                 sendPackageAddedForUser(packageName, pkgSetting, userId);
9886                 return true;
9887             }
9888             if (sendRemoved) {
9889                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9890                         "hiding pkg");
9891                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9892                 return true;
9893             }
9894         } finally {
9895             Binder.restoreCallingIdentity(callingId);
9896         }
9897         return false;
9898     }
9899
9900     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9901             int userId) {
9902         final PackageRemovedInfo info = new PackageRemovedInfo();
9903         info.removedPackage = packageName;
9904         info.removedUsers = new int[] {userId};
9905         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9906         info.sendBroadcast(false, false, false);
9907     }
9908
9909     /**
9910      * Returns true if application is not found or there was an error. Otherwise it returns
9911      * the hidden state of the package for the given user.
9912      */
9913     @Override
9914     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9915         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9916         enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9917                 false, "getApplicationHidden for user " + userId);
9918         PackageSetting pkgSetting;
9919         long callingId = Binder.clearCallingIdentity();
9920         try {
9921             // writer
9922             synchronized (mPackages) {
9923                 pkgSetting = mSettings.mPackages.get(packageName);
9924                 if (pkgSetting == null) {
9925                     return true;
9926                 }
9927                 return pkgSetting.getHidden(userId);
9928             }
9929         } finally {
9930             Binder.restoreCallingIdentity(callingId);
9931         }
9932     }
9933
9934     /**
9935      * @hide
9936      */
9937     @Override
9938     public int installExistingPackageAsUser(String packageName, int userId) {
9939         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9940                 null);
9941         PackageSetting pkgSetting;
9942         final int uid = Binder.getCallingUid();
9943         enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9944                 + userId);
9945         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9946             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9947         }
9948
9949         long callingId = Binder.clearCallingIdentity();
9950         try {
9951             boolean sendAdded = false;
9952
9953             // writer
9954             synchronized (mPackages) {
9955                 pkgSetting = mSettings.mPackages.get(packageName);
9956                 if (pkgSetting == null) {
9957                     return PackageManager.INSTALL_FAILED_INVALID_URI;
9958                 }
9959                 if (!pkgSetting.getInstalled(userId)) {
9960                     pkgSetting.setInstalled(true, userId);
9961                     pkgSetting.setHidden(false, userId);
9962                     mSettings.writePackageRestrictionsLPr(userId);
9963                     sendAdded = true;
9964                 }
9965             }
9966
9967             if (sendAdded) {
9968                 sendPackageAddedForUser(packageName, pkgSetting, userId);
9969             }
9970         } finally {
9971             Binder.restoreCallingIdentity(callingId);
9972         }
9973
9974         return PackageManager.INSTALL_SUCCEEDED;
9975     }
9976
9977     boolean isUserRestricted(int userId, String restrictionKey) {
9978         Bundle restrictions = sUserManager.getUserRestrictions(userId);
9979         if (restrictions.getBoolean(restrictionKey, false)) {
9980             Log.w(TAG, "User is restricted: " + restrictionKey);
9981             return true;
9982         }
9983         return false;
9984     }
9985
9986     @Override
9987     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9988         mContext.enforceCallingOrSelfPermission(
9989                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9990                 "Only package verification agents can verify applications");
9991
9992         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9993         final PackageVerificationResponse response = new PackageVerificationResponse(
9994                 verificationCode, Binder.getCallingUid());
9995         msg.arg1 = id;
9996         msg.obj = response;
9997         mHandler.sendMessage(msg);
9998     }
9999
10000     @Override
10001     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10002             long millisecondsToDelay) {
10003         mContext.enforceCallingOrSelfPermission(
10004                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10005                 "Only package verification agents can extend verification timeouts");
10006
10007         final PackageVerificationState state = mPendingVerification.get(id);
10008         final PackageVerificationResponse response = new PackageVerificationResponse(
10009                 verificationCodeAtTimeout, Binder.getCallingUid());
10010
10011         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10012             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10013         }
10014         if (millisecondsToDelay < 0) {
10015             millisecondsToDelay = 0;
10016         }
10017         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10018                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10019             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10020         }
10021
10022         if ((state != null) && !state.timeoutExtended()) {
10023             state.extendTimeout();
10024
10025             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10026             msg.arg1 = id;
10027             msg.obj = response;
10028             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10029         }
10030     }
10031
10032     private void broadcastPackageVerified(int verificationId, Uri packageUri,
10033             int verificationCode, UserHandle user) {
10034         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10035         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10036         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10037         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10038         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10039
10040         mContext.sendBroadcastAsUser(intent, user,
10041                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10042     }
10043
10044     private ComponentName matchComponentForVerifier(String packageName,
10045             List<ResolveInfo> receivers) {
10046         ActivityInfo targetReceiver = null;
10047
10048         final int NR = receivers.size();
10049         for (int i = 0; i < NR; i++) {
10050             final ResolveInfo info = receivers.get(i);
10051             if (info.activityInfo == null) {
10052                 continue;
10053             }
10054
10055             if (packageName.equals(info.activityInfo.packageName)) {
10056                 targetReceiver = info.activityInfo;
10057                 break;
10058             }
10059         }
10060
10061         if (targetReceiver == null) {
10062             return null;
10063         }
10064
10065         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10066     }
10067
10068     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10069             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10070         if (pkgInfo.verifiers.length == 0) {
10071             return null;
10072         }
10073
10074         final int N = pkgInfo.verifiers.length;
10075         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10076         for (int i = 0; i < N; i++) {
10077             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10078
10079             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10080                     receivers);
10081             if (comp == null) {
10082                 continue;
10083             }
10084
10085             final int verifierUid = getUidForVerifier(verifierInfo);
10086             if (verifierUid == -1) {
10087                 continue;
10088             }
10089
10090             if (DEBUG_VERIFY) {
10091                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10092                         + " with the correct signature");
10093             }
10094             sufficientVerifiers.add(comp);
10095             verificationState.addSufficientVerifier(verifierUid);
10096         }
10097
10098         return sufficientVerifiers;
10099     }
10100
10101     private int getUidForVerifier(VerifierInfo verifierInfo) {
10102         synchronized (mPackages) {
10103             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10104             if (pkg == null) {
10105                 return -1;
10106             } else if (pkg.mSignatures.length != 1) {
10107                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10108                         + " has more than one signature; ignoring");
10109                 return -1;
10110             }
10111
10112             /*
10113              * If the public key of the package's signature does not match
10114              * our expected public key, then this is a different package and
10115              * we should skip.
10116              */
10117
10118             final byte[] expectedPublicKey;
10119             try {
10120                 final Signature verifierSig = pkg.mSignatures[0];
10121                 final PublicKey publicKey = verifierSig.getPublicKey();
10122                 expectedPublicKey = publicKey.getEncoded();
10123             } catch (CertificateException e) {
10124                 return -1;
10125             }
10126
10127             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10128
10129             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10130                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10131                         + " does not have the expected public key; ignoring");
10132                 return -1;
10133             }
10134
10135             return pkg.applicationInfo.uid;
10136         }
10137     }
10138
10139     @Override
10140     public void finishPackageInstall(int token) {
10141         enforceSystemOrRoot("Only the system is allowed to finish installs");
10142
10143         if (DEBUG_INSTALL) {
10144             Slog.v(TAG, "BM finishing package install for " + token);
10145         }
10146
10147         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10148         mHandler.sendMessage(msg);
10149     }
10150
10151     /**
10152      * Get the verification agent timeout.
10153      *
10154      * @return verification timeout in milliseconds
10155      */
10156     private long getVerificationTimeout() {
10157         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10158                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10159                 DEFAULT_VERIFICATION_TIMEOUT);
10160     }
10161
10162     /**
10163      * Get the default verification agent response code.
10164      *
10165      * @return default verification response code
10166      */
10167     private int getDefaultVerificationResponse() {
10168         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10169                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10170                 DEFAULT_VERIFICATION_RESPONSE);
10171     }
10172
10173     /**
10174      * Check whether or not package verification has been enabled.
10175      *
10176      * @return true if verification should be performed
10177      */
10178     private boolean isVerificationEnabled(int userId, int installFlags) {
10179         if (!DEFAULT_VERIFY_ENABLE) {
10180             return false;
10181         }
10182
10183         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10184
10185         // Check if installing from ADB
10186         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10187             // Do not run verification in a test harness environment
10188             if (ActivityManager.isRunningInTestHarness()) {
10189                 return false;
10190             }
10191             if (ensureVerifyAppsEnabled) {
10192                 return true;
10193             }
10194             // Check if the developer does not want package verification for ADB installs
10195             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10196                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10197                 return false;
10198             }
10199         }
10200
10201         if (ensureVerifyAppsEnabled) {
10202             return true;
10203         }
10204
10205         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10206                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10207     }
10208
10209     @Override
10210     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10211             throws RemoteException {
10212         mContext.enforceCallingOrSelfPermission(
10213                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10214                 "Only intentfilter verification agents can verify applications");
10215
10216         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10217         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10218                 Binder.getCallingUid(), verificationCode, failedDomains);
10219         msg.arg1 = id;
10220         msg.obj = response;
10221         mHandler.sendMessage(msg);
10222     }
10223
10224     @Override
10225     public int getIntentVerificationStatus(String packageName, int userId) {
10226         synchronized (mPackages) {
10227             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10228         }
10229     }
10230
10231     @Override
10232     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10233         mContext.enforceCallingOrSelfPermission(
10234                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10235
10236         boolean result = false;
10237         synchronized (mPackages) {
10238             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10239         }
10240         if (result) {
10241             scheduleWritePackageRestrictionsLocked(userId);
10242         }
10243         return result;
10244     }
10245
10246     @Override
10247     public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10248         synchronized (mPackages) {
10249             return mSettings.getIntentFilterVerificationsLPr(packageName);
10250         }
10251     }
10252
10253     @Override
10254     public List<IntentFilter> getAllIntentFilters(String packageName) {
10255         if (TextUtils.isEmpty(packageName)) {
10256             return Collections.<IntentFilter>emptyList();
10257         }
10258         synchronized (mPackages) {
10259             PackageParser.Package pkg = mPackages.get(packageName);
10260             if (pkg == null || pkg.activities == null) {
10261                 return Collections.<IntentFilter>emptyList();
10262             }
10263             final int count = pkg.activities.size();
10264             ArrayList<IntentFilter> result = new ArrayList<>();
10265             for (int n=0; n<count; n++) {
10266                 PackageParser.Activity activity = pkg.activities.get(n);
10267                 if (activity.intents != null || activity.intents.size() > 0) {
10268                     result.addAll(activity.intents);
10269                 }
10270             }
10271             return result;
10272         }
10273     }
10274
10275     @Override
10276     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10277         mContext.enforceCallingOrSelfPermission(
10278                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10279
10280         synchronized (mPackages) {
10281             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10282             if (packageName != null) {
10283                 result |= updateIntentVerificationStatus(packageName,
10284                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10285                         userId);
10286                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10287                         packageName, userId);
10288             }
10289             return result;
10290         }
10291     }
10292
10293     @Override
10294     public String getDefaultBrowserPackageName(int userId) {
10295         synchronized (mPackages) {
10296             return mSettings.getDefaultBrowserPackageNameLPw(userId);
10297         }
10298     }
10299
10300     /**
10301      * Get the "allow unknown sources" setting.
10302      *
10303      * @return the current "allow unknown sources" setting
10304      */
10305     private int getUnknownSourcesSettings() {
10306         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10307                 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10308                 -1);
10309     }
10310
10311     @Override
10312     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10313         final int uid = Binder.getCallingUid();
10314         // writer
10315         synchronized (mPackages) {
10316             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10317             if (targetPackageSetting == null) {
10318                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10319             }
10320
10321             PackageSetting installerPackageSetting;
10322             if (installerPackageName != null) {
10323                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10324                 if (installerPackageSetting == null) {
10325                     throw new IllegalArgumentException("Unknown installer package: "
10326                             + installerPackageName);
10327                 }
10328             } else {
10329                 installerPackageSetting = null;
10330             }
10331
10332             Signature[] callerSignature;
10333             Object obj = mSettings.getUserIdLPr(uid);
10334             if (obj != null) {
10335                 if (obj instanceof SharedUserSetting) {
10336                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10337                 } else if (obj instanceof PackageSetting) {
10338                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10339                 } else {
10340                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
10341                 }
10342             } else {
10343                 throw new SecurityException("Unknown calling uid " + uid);
10344             }
10345
10346             // Verify: can't set installerPackageName to a package that is
10347             // not signed with the same cert as the caller.
10348             if (installerPackageSetting != null) {
10349                 if (compareSignatures(callerSignature,
10350                         installerPackageSetting.signatures.mSignatures)
10351                         != PackageManager.SIGNATURE_MATCH) {
10352                     throw new SecurityException(
10353                             "Caller does not have same cert as new installer package "
10354                             + installerPackageName);
10355                 }
10356             }
10357
10358             // Verify: if target already has an installer package, it must
10359             // be signed with the same cert as the caller.
10360             if (targetPackageSetting.installerPackageName != null) {
10361                 PackageSetting setting = mSettings.mPackages.get(
10362                         targetPackageSetting.installerPackageName);
10363                 // If the currently set package isn't valid, then it's always
10364                 // okay to change it.
10365                 if (setting != null) {
10366                     if (compareSignatures(callerSignature,
10367                             setting.signatures.mSignatures)
10368                             != PackageManager.SIGNATURE_MATCH) {
10369                         throw new SecurityException(
10370                                 "Caller does not have same cert as old installer package "
10371                                 + targetPackageSetting.installerPackageName);
10372                     }
10373                 }
10374             }
10375
10376             // Okay!
10377             targetPackageSetting.installerPackageName = installerPackageName;
10378             scheduleWriteSettingsLocked();
10379         }
10380     }
10381
10382     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10383         // Queue up an async operation since the package installation may take a little while.
10384         mHandler.post(new Runnable() {
10385             public void run() {
10386                 mHandler.removeCallbacks(this);
10387                  // Result object to be returned
10388                 PackageInstalledInfo res = new PackageInstalledInfo();
10389                 res.returnCode = currentStatus;
10390                 res.uid = -1;
10391                 res.pkg = null;
10392                 res.removedInfo = new PackageRemovedInfo();
10393                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10394                     args.doPreInstall(res.returnCode);
10395                     synchronized (mInstallLock) {
10396                         installPackageLI(args, res);
10397                     }
10398                     args.doPostInstall(res.returnCode, res.uid);
10399                 }
10400
10401                 // A restore should be performed at this point if (a) the install
10402                 // succeeded, (b) the operation is not an update, and (c) the new
10403                 // package has not opted out of backup participation.
10404                 final boolean update = res.removedInfo.removedPackage != null;
10405                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10406                 boolean doRestore = !update
10407                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10408
10409                 // Set up the post-install work request bookkeeping.  This will be used
10410                 // and cleaned up by the post-install event handling regardless of whether
10411                 // there's a restore pass performed.  Token values are >= 1.
10412                 int token;
10413                 if (mNextInstallToken < 0) mNextInstallToken = 1;
10414                 token = mNextInstallToken++;
10415
10416                 PostInstallData data = new PostInstallData(args, res);
10417                 mRunningInstalls.put(token, data);
10418                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10419
10420                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10421                     // Pass responsibility to the Backup Manager.  It will perform a
10422                     // restore if appropriate, then pass responsibility back to the
10423                     // Package Manager to run the post-install observer callbacks
10424                     // and broadcasts.
10425                     IBackupManager bm = IBackupManager.Stub.asInterface(
10426                             ServiceManager.getService(Context.BACKUP_SERVICE));
10427                     if (bm != null) {
10428                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10429                                 + " to BM for possible restore");
10430                         try {
10431                             if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10432                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10433                             } else {
10434                                 doRestore = false;
10435                             }
10436                         } catch (RemoteException e) {
10437                             // can't happen; the backup manager is local
10438                         } catch (Exception e) {
10439                             Slog.e(TAG, "Exception trying to enqueue restore", e);
10440                             doRestore = false;
10441                         }
10442                     } else {
10443                         Slog.e(TAG, "Backup Manager not found!");
10444                         doRestore = false;
10445                     }
10446                 }
10447
10448                 if (!doRestore) {
10449                     // No restore possible, or the Backup Manager was mysteriously not
10450                     // available -- just fire the post-install work request directly.
10451                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10452                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10453                     mHandler.sendMessage(msg);
10454                 }
10455             }
10456         });
10457     }
10458
10459     private abstract class HandlerParams {
10460         private static final int MAX_RETRIES = 4;
10461
10462         /**
10463          * Number of times startCopy() has been attempted and had a non-fatal
10464          * error.
10465          */
10466         private int mRetries = 0;
10467
10468         /** User handle for the user requesting the information or installation. */
10469         private final UserHandle mUser;
10470
10471         HandlerParams(UserHandle user) {
10472             mUser = user;
10473         }
10474
10475         UserHandle getUser() {
10476             return mUser;
10477         }
10478
10479         final boolean startCopy() {
10480             boolean res;
10481             try {
10482                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10483
10484                 if (++mRetries > MAX_RETRIES) {
10485                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10486                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
10487                     handleServiceError();
10488                     return false;
10489                 } else {
10490                     handleStartCopy();
10491                     res = true;
10492                 }
10493             } catch (RemoteException e) {
10494                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10495                 mHandler.sendEmptyMessage(MCS_RECONNECT);
10496                 res = false;
10497             }
10498             handleReturnCode();
10499             return res;
10500         }
10501
10502         final void serviceError() {
10503             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10504             handleServiceError();
10505             handleReturnCode();
10506         }
10507
10508         abstract void handleStartCopy() throws RemoteException;
10509         abstract void handleServiceError();
10510         abstract void handleReturnCode();
10511     }
10512
10513     class MeasureParams extends HandlerParams {
10514         private final PackageStats mStats;
10515         private boolean mSuccess;
10516
10517         private final IPackageStatsObserver mObserver;
10518
10519         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10520             super(new UserHandle(stats.userHandle));
10521             mObserver = observer;
10522             mStats = stats;
10523         }
10524
10525         @Override
10526         public String toString() {
10527             return "MeasureParams{"
10528                 + Integer.toHexString(System.identityHashCode(this))
10529                 + " " + mStats.packageName + "}";
10530         }
10531
10532         @Override
10533         void handleStartCopy() throws RemoteException {
10534             synchronized (mInstallLock) {
10535                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10536             }
10537
10538             if (mSuccess) {
10539                 final boolean mounted;
10540                 if (Environment.isExternalStorageEmulated()) {
10541                     mounted = true;
10542                 } else {
10543                     final String status = Environment.getExternalStorageState();
10544                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
10545                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10546                 }
10547
10548                 if (mounted) {
10549                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10550
10551                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10552                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10553
10554                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
10555                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10556
10557                     // Always subtract cache size, since it's a subdirectory
10558                     mStats.externalDataSize -= mStats.externalCacheSize;
10559
10560                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10561                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10562
10563                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
10564                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10565                 }
10566             }
10567         }
10568
10569         @Override
10570         void handleReturnCode() {
10571             if (mObserver != null) {
10572                 try {
10573                     mObserver.onGetStatsCompleted(mStats, mSuccess);
10574                 } catch (RemoteException e) {
10575                     Slog.i(TAG, "Observer no longer exists.");
10576                 }
10577             }
10578         }
10579
10580         @Override
10581         void handleServiceError() {
10582             Slog.e(TAG, "Could not measure application " + mStats.packageName
10583                             + " external storage");
10584         }
10585     }
10586
10587     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10588             throws RemoteException {
10589         long result = 0;
10590         for (File path : paths) {
10591             result += mcs.calculateDirectorySize(path.getAbsolutePath());
10592         }
10593         return result;
10594     }
10595
10596     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10597         for (File path : paths) {
10598             try {
10599                 mcs.clearDirectory(path.getAbsolutePath());
10600             } catch (RemoteException e) {
10601             }
10602         }
10603     }
10604
10605     static class OriginInfo {
10606         /**
10607          * Location where install is coming from, before it has been
10608          * copied/renamed into place. This could be a single monolithic APK
10609          * file, or a cluster directory. This location may be untrusted.
10610          */
10611         final File file;
10612         final String cid;
10613
10614         /**
10615          * Flag indicating that {@link #file} or {@link #cid} has already been
10616          * staged, meaning downstream users don't need to defensively copy the
10617          * contents.
10618          */
10619         final boolean staged;
10620
10621         /**
10622          * Flag indicating that {@link #file} or {@link #cid} is an already
10623          * installed app that is being moved.
10624          */
10625         final boolean existing;
10626
10627         final String resolvedPath;
10628         final File resolvedFile;
10629
10630         static OriginInfo fromNothing() {
10631             return new OriginInfo(null, null, false, false);
10632         }
10633
10634         static OriginInfo fromUntrustedFile(File file) {
10635             return new OriginInfo(file, null, false, false);
10636         }
10637
10638         static OriginInfo fromExistingFile(File file) {
10639             return new OriginInfo(file, null, false, true);
10640         }
10641
10642         static OriginInfo fromStagedFile(File file) {
10643             return new OriginInfo(file, null, true, false);
10644         }
10645
10646         static OriginInfo fromStagedContainer(String cid) {
10647             return new OriginInfo(null, cid, true, false);
10648         }
10649
10650         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10651             this.file = file;
10652             this.cid = cid;
10653             this.staged = staged;
10654             this.existing = existing;
10655
10656             if (cid != null) {
10657                 resolvedPath = PackageHelper.getSdDir(cid);
10658                 resolvedFile = new File(resolvedPath);
10659             } else if (file != null) {
10660                 resolvedPath = file.getAbsolutePath();
10661                 resolvedFile = file;
10662             } else {
10663                 resolvedPath = null;
10664                 resolvedFile = null;
10665             }
10666         }
10667     }
10668
10669     class MoveInfo {
10670         final int moveId;
10671         final String fromUuid;
10672         final String toUuid;
10673         final String packageName;
10674         final String dataAppName;
10675         final int appId;
10676         final String seinfo;
10677
10678         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10679                 String dataAppName, int appId, String seinfo) {
10680             this.moveId = moveId;
10681             this.fromUuid = fromUuid;
10682             this.toUuid = toUuid;
10683             this.packageName = packageName;
10684             this.dataAppName = dataAppName;
10685             this.appId = appId;
10686             this.seinfo = seinfo;
10687         }
10688     }
10689
10690     class InstallParams extends HandlerParams {
10691         final OriginInfo origin;
10692         final MoveInfo move;
10693         final IPackageInstallObserver2 observer;
10694         int installFlags;
10695         final String installerPackageName;
10696         final String volumeUuid;
10697         final VerificationParams verificationParams;
10698         private InstallArgs mArgs;
10699         private int mRet;
10700         final String packageAbiOverride;
10701         final String[] grantedRuntimePermissions;
10702
10703
10704         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10705                 int installFlags, String installerPackageName, String volumeUuid,
10706                 VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10707                 String[] grantedPermissions) {
10708             super(user);
10709             this.origin = origin;
10710             this.move = move;
10711             this.observer = observer;
10712             this.installFlags = installFlags;
10713             this.installerPackageName = installerPackageName;
10714             this.volumeUuid = volumeUuid;
10715             this.verificationParams = verificationParams;
10716             this.packageAbiOverride = packageAbiOverride;
10717             this.grantedRuntimePermissions = grantedPermissions;
10718         }
10719
10720         @Override
10721         public String toString() {
10722             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10723                     + " file=" + origin.file + " cid=" + origin.cid + "}";
10724         }
10725
10726         public ManifestDigest getManifestDigest() {
10727             if (verificationParams == null) {
10728                 return null;
10729             }
10730             return verificationParams.getManifestDigest();
10731         }
10732
10733         private int installLocationPolicy(PackageInfoLite pkgLite) {
10734             String packageName = pkgLite.packageName;
10735             int installLocation = pkgLite.installLocation;
10736             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10737             // reader
10738             synchronized (mPackages) {
10739                 PackageParser.Package pkg = mPackages.get(packageName);
10740                 if (pkg != null) {
10741                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10742                         // Check for downgrading.
10743                         if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10744                             try {
10745                                 checkDowngrade(pkg, pkgLite);
10746                             } catch (PackageManagerException e) {
10747                                 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10748                                 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10749                             }
10750                         }
10751                         // Check for updated system application.
10752                         if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10753                             if (onSd) {
10754                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
10755                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10756                             }
10757                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10758                         } else {
10759                             if (onSd) {
10760                                 // Install flag overrides everything.
10761                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10762                             }
10763                             // If current upgrade specifies particular preference
10764                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10765                                 // Application explicitly specified internal.
10766                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10767                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10768                                 // App explictly prefers external. Let policy decide
10769                             } else {
10770                                 // Prefer previous location
10771                                 if (isExternal(pkg)) {
10772                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10773                                 }
10774                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10775                             }
10776                         }
10777                     } else {
10778                         // Invalid install. Return error code
10779                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10780                     }
10781                 }
10782             }
10783             // All the special cases have been taken care of.
10784             // Return result based on recommended install location.
10785             if (onSd) {
10786                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10787             }
10788             return pkgLite.recommendedInstallLocation;
10789         }
10790
10791         /*
10792          * Invoke remote method to get package information and install
10793          * location values. Override install location based on default
10794          * policy if needed and then create install arguments based
10795          * on the install location.
10796          */
10797         public void handleStartCopy() throws RemoteException {
10798             int ret = PackageManager.INSTALL_SUCCEEDED;
10799
10800             // If we're already staged, we've firmly committed to an install location
10801             if (origin.staged) {
10802                 if (origin.file != null) {
10803                     installFlags |= PackageManager.INSTALL_INTERNAL;
10804                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10805                 } else if (origin.cid != null) {
10806                     installFlags |= PackageManager.INSTALL_EXTERNAL;
10807                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
10808                 } else {
10809                     throw new IllegalStateException("Invalid stage location");
10810                 }
10811             }
10812
10813             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10814             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10815
10816             PackageInfoLite pkgLite = null;
10817
10818             if (onInt && onSd) {
10819                 // Check if both bits are set.
10820                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10821                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10822             } else {
10823                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10824                         packageAbiOverride);
10825
10826                 /*
10827                  * If we have too little free space, try to free cache
10828                  * before giving up.
10829                  */
10830                 if (!origin.staged && pkgLite.recommendedInstallLocation
10831                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10832                     // TODO: focus freeing disk space on the target device
10833                     final StorageManager storage = StorageManager.from(mContext);
10834                     final long lowThreshold = storage.getStorageLowBytes(
10835                             Environment.getDataDirectory());
10836
10837                     final long sizeBytes = mContainerService.calculateInstalledSize(
10838                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10839
10840                     if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10841                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10842                                 installFlags, packageAbiOverride);
10843                     }
10844
10845                     /*
10846                      * The cache free must have deleted the file we
10847                      * downloaded to install.
10848                      *
10849                      * TODO: fix the "freeCache" call to not delete
10850                      *       the file we care about.
10851                      */
10852                     if (pkgLite.recommendedInstallLocation
10853                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10854                         pkgLite.recommendedInstallLocation
10855                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10856                     }
10857                 }
10858             }
10859
10860             if (ret == PackageManager.INSTALL_SUCCEEDED) {
10861                 int loc = pkgLite.recommendedInstallLocation;
10862                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10863                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10864                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10865                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10866                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10867                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10868                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10869                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10870                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10871                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10872                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10873                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10874                 } else {
10875                     // Override with defaults if needed.
10876                     loc = installLocationPolicy(pkgLite);
10877                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10878                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10879                     } else if (!onSd && !onInt) {
10880                         // Override install location with flags
10881                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10882                             // Set the flag to install on external media.
10883                             installFlags |= PackageManager.INSTALL_EXTERNAL;
10884                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
10885                         } else {
10886                             // Make sure the flag for installing on external
10887                             // media is unset
10888                             installFlags |= PackageManager.INSTALL_INTERNAL;
10889                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10890                         }
10891                     }
10892                 }
10893             }
10894
10895             final InstallArgs args = createInstallArgs(this);
10896             mArgs = args;
10897
10898             if (ret == PackageManager.INSTALL_SUCCEEDED) {
10899                  /*
10900                  * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10901                  * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10902                  */
10903                 int userIdentifier = getUser().getIdentifier();
10904                 if (userIdentifier == UserHandle.USER_ALL
10905                         && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10906                     userIdentifier = UserHandle.USER_OWNER;
10907                 }
10908
10909                 /*
10910                  * Determine if we have any installed package verifiers. If we
10911                  * do, then we'll defer to them to verify the packages.
10912                  */
10913                 final int requiredUid = mRequiredVerifierPackage == null ? -1
10914                         : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10915                 if (!origin.existing && requiredUid != -1
10916                         && isVerificationEnabled(userIdentifier, installFlags)) {
10917                     final Intent verification = new Intent(
10918                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10919                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10920                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10921                             PACKAGE_MIME_TYPE);
10922                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10923
10924                     final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10925                             PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10926                             0 /* TODO: Which userId? */);
10927
10928                     if (DEBUG_VERIFY) {
10929                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10930                                 + verification.toString() + " with " + pkgLite.verifiers.length
10931                                 + " optional verifiers");
10932                     }
10933
10934                     final int verificationId = mPendingVerificationToken++;
10935
10936                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10937
10938                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10939                             installerPackageName);
10940
10941                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10942                             installFlags);
10943
10944                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10945                             pkgLite.packageName);
10946
10947                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10948                             pkgLite.versionCode);
10949
10950                     if (verificationParams != null) {
10951                         if (verificationParams.getVerificationURI() != null) {
10952                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10953                                  verificationParams.getVerificationURI());
10954                         }
10955                         if (verificationParams.getOriginatingURI() != null) {
10956                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10957                                   verificationParams.getOriginatingURI());
10958                         }
10959                         if (verificationParams.getReferrer() != null) {
10960                             verification.putExtra(Intent.EXTRA_REFERRER,
10961                                   verificationParams.getReferrer());
10962                         }
10963                         if (verificationParams.getOriginatingUid() >= 0) {
10964                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10965                                   verificationParams.getOriginatingUid());
10966                         }
10967                         if (verificationParams.getInstallerUid() >= 0) {
10968                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10969                                   verificationParams.getInstallerUid());
10970                         }
10971                     }
10972
10973                     final PackageVerificationState verificationState = new PackageVerificationState(
10974                             requiredUid, args);
10975
10976                     mPendingVerification.append(verificationId, verificationState);
10977
10978                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10979                             receivers, verificationState);
10980
10981                     // Apps installed for "all" users use the device owner to verify the app
10982                     UserHandle verifierUser = getUser();
10983                     if (verifierUser == UserHandle.ALL) {
10984                         verifierUser = UserHandle.OWNER;
10985                     }
10986
10987                     /*
10988                      * If any sufficient verifiers were listed in the package
10989                      * manifest, attempt to ask them.
10990                      */
10991                     if (sufficientVerifiers != null) {
10992                         final int N = sufficientVerifiers.size();
10993                         if (N == 0) {
10994                             Slog.i(TAG, "Additional verifiers required, but none installed.");
10995                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10996                         } else {
10997                             for (int i = 0; i < N; i++) {
10998                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
10999
11000                                 final Intent sufficientIntent = new Intent(verification);
11001                                 sufficientIntent.setComponent(verifierComponent);
11002                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11003                             }
11004                         }
11005                     }
11006
11007                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11008                             mRequiredVerifierPackage, receivers);
11009                     if (ret == PackageManager.INSTALL_SUCCEEDED
11010                             && mRequiredVerifierPackage != null) {
11011                         /*
11012                          * Send the intent to the required verification agent,
11013                          * but only start the verification timeout after the
11014                          * target BroadcastReceivers have run.
11015                          */
11016                         verification.setComponent(requiredVerifierComponent);
11017                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11018                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11019                                 new BroadcastReceiver() {
11020                                     @Override
11021                                     public void onReceive(Context context, Intent intent) {
11022                                         final Message msg = mHandler
11023                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
11024                                         msg.arg1 = verificationId;
11025                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11026                                     }
11027                                 }, null, 0, null, null);
11028
11029                         /*
11030                          * We don't want the copy to proceed until verification
11031                          * succeeds, so null out this field.
11032                          */
11033                         mArgs = null;
11034                     }
11035                 } else {
11036                     /*
11037                      * No package verification is enabled, so immediately start
11038                      * the remote call to initiate copy using temporary file.
11039                      */
11040                     ret = args.copyApk(mContainerService, true);
11041                 }
11042             }
11043
11044             mRet = ret;
11045         }
11046
11047         @Override
11048         void handleReturnCode() {
11049             // If mArgs is null, then MCS couldn't be reached. When it
11050             // reconnects, it will try again to install. At that point, this
11051             // will succeed.
11052             if (mArgs != null) {
11053                 processPendingInstall(mArgs, mRet);
11054             }
11055         }
11056
11057         @Override
11058         void handleServiceError() {
11059             mArgs = createInstallArgs(this);
11060             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11061         }
11062
11063         public boolean isForwardLocked() {
11064             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11065         }
11066     }
11067
11068     /**
11069      * Used during creation of InstallArgs
11070      *
11071      * @param installFlags package installation flags
11072      * @return true if should be installed on external storage
11073      */
11074     private static boolean installOnExternalAsec(int installFlags) {
11075         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11076             return false;
11077         }
11078         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11079             return true;
11080         }
11081         return false;
11082     }
11083
11084     /**
11085      * Used during creation of InstallArgs
11086      *
11087      * @param installFlags package installation flags
11088      * @return true if should be installed as forward locked
11089      */
11090     private static boolean installForwardLocked(int installFlags) {
11091         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11092     }
11093
11094     private InstallArgs createInstallArgs(InstallParams params) {
11095         if (params.move != null) {
11096             return new MoveInstallArgs(params);
11097         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11098             return new AsecInstallArgs(params);
11099         } else {
11100             return new FileInstallArgs(params);
11101         }
11102     }
11103
11104     /**
11105      * Create args that describe an existing installed package. Typically used
11106      * when cleaning up old installs, or used as a move source.
11107      */
11108     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11109             String resourcePath, String[] instructionSets) {
11110         final boolean isInAsec;
11111         if (installOnExternalAsec(installFlags)) {
11112             /* Apps on SD card are always in ASEC containers. */
11113             isInAsec = true;
11114         } else if (installForwardLocked(installFlags)
11115                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11116             /*
11117              * Forward-locked apps are only in ASEC containers if they're the
11118              * new style
11119              */
11120             isInAsec = true;
11121         } else {
11122             isInAsec = false;
11123         }
11124
11125         if (isInAsec) {
11126             return new AsecInstallArgs(codePath, instructionSets,
11127                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11128         } else {
11129             return new FileInstallArgs(codePath, resourcePath, instructionSets);
11130         }
11131     }
11132
11133     static abstract class InstallArgs {
11134         /** @see InstallParams#origin */
11135         final OriginInfo origin;
11136         /** @see InstallParams#move */
11137         final MoveInfo move;
11138
11139         final IPackageInstallObserver2 observer;
11140         // Always refers to PackageManager flags only
11141         final int installFlags;
11142         final String installerPackageName;
11143         final String volumeUuid;
11144         final ManifestDigest manifestDigest;
11145         final UserHandle user;
11146         final String abiOverride;
11147         final String[] installGrantPermissions;
11148
11149         // The list of instruction sets supported by this app. This is currently
11150         // only used during the rmdex() phase to clean up resources. We can get rid of this
11151         // if we move dex files under the common app path.
11152         /* nullable */ String[] instructionSets;
11153
11154         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11155                 int installFlags, String installerPackageName, String volumeUuid,
11156                 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11157                 String abiOverride, String[] installGrantPermissions) {
11158             this.origin = origin;
11159             this.move = move;
11160             this.installFlags = installFlags;
11161             this.observer = observer;
11162             this.installerPackageName = installerPackageName;
11163             this.volumeUuid = volumeUuid;
11164             this.manifestDigest = manifestDigest;
11165             this.user = user;
11166             this.instructionSets = instructionSets;
11167             this.abiOverride = abiOverride;
11168             this.installGrantPermissions = installGrantPermissions;
11169         }
11170
11171         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11172         abstract int doPreInstall(int status);
11173
11174         /**
11175          * Rename package into final resting place. All paths on the given
11176          * scanned package should be updated to reflect the rename.
11177          */
11178         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11179         abstract int doPostInstall(int status, int uid);
11180
11181         /** @see PackageSettingBase#codePathString */
11182         abstract String getCodePath();
11183         /** @see PackageSettingBase#resourcePathString */
11184         abstract String getResourcePath();
11185
11186         // Need installer lock especially for dex file removal.
11187         abstract void cleanUpResourcesLI();
11188         abstract boolean doPostDeleteLI(boolean delete);
11189
11190         /**
11191          * Called before the source arguments are copied. This is used mostly
11192          * for MoveParams when it needs to read the source file to put it in the
11193          * destination.
11194          */
11195         int doPreCopy() {
11196             return PackageManager.INSTALL_SUCCEEDED;
11197         }
11198
11199         /**
11200          * Called after the source arguments are copied. This is used mostly for
11201          * MoveParams when it needs to read the source file to put it in the
11202          * destination.
11203          */
11204         int doPostCopy(int uid) {
11205             return PackageManager.INSTALL_SUCCEEDED;
11206         }
11207
11208         protected boolean isFwdLocked() {
11209             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11210         }
11211
11212         protected boolean isExternalAsec() {
11213             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11214         }
11215
11216         UserHandle getUser() {
11217             return user;
11218         }
11219     }
11220
11221     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11222         if (!allCodePaths.isEmpty()) {
11223             if (instructionSets == null) {
11224                 throw new IllegalStateException("instructionSet == null");
11225             }
11226             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11227             for (String codePath : allCodePaths) {
11228                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11229                     int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11230                     if (retCode < 0) {
11231                         Slog.w(TAG, "Couldn't remove dex file for package: "
11232                                 + " at location " + codePath + ", retcode=" + retCode);
11233                         // we don't consider this to be a failure of the core package deletion
11234                     }
11235                 }
11236             }
11237         }
11238     }
11239
11240     /**
11241      * Logic to handle installation of non-ASEC applications, including copying
11242      * and renaming logic.
11243      */
11244     class FileInstallArgs extends InstallArgs {
11245         private File codeFile;
11246         private File resourceFile;
11247
11248         // Example topology:
11249         // /data/app/com.example/base.apk
11250         // /data/app/com.example/split_foo.apk
11251         // /data/app/com.example/lib/arm/libfoo.so
11252         // /data/app/com.example/lib/arm64/libfoo.so
11253         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11254
11255         /** New install */
11256         FileInstallArgs(InstallParams params) {
11257             super(params.origin, params.move, params.observer, params.installFlags,
11258                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11259                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11260                     params.grantedRuntimePermissions);
11261             if (isFwdLocked()) {
11262                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
11263             }
11264         }
11265
11266         /** Existing install */
11267         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11268             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11269                     null, null);
11270             this.codeFile = (codePath != null) ? new File(codePath) : null;
11271             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11272         }
11273
11274         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11275             if (origin.staged) {
11276                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11277                 codeFile = origin.file;
11278                 resourceFile = origin.file;
11279                 return PackageManager.INSTALL_SUCCEEDED;
11280             }
11281
11282             try {
11283                 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11284                 codeFile = tempDir;
11285                 resourceFile = tempDir;
11286             } catch (IOException e) {
11287                 Slog.w(TAG, "Failed to create copy file: " + e);
11288                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11289             }
11290
11291             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11292                 @Override
11293                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11294                     if (!FileUtils.isValidExtFilename(name)) {
11295                         throw new IllegalArgumentException("Invalid filename: " + name);
11296                     }
11297                     try {
11298                         final File file = new File(codeFile, name);
11299                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11300                                 O_RDWR | O_CREAT, 0644);
11301                         Os.chmod(file.getAbsolutePath(), 0644);
11302                         return new ParcelFileDescriptor(fd);
11303                     } catch (ErrnoException e) {
11304                         throw new RemoteException("Failed to open: " + e.getMessage());
11305                     }
11306                 }
11307             };
11308
11309             int ret = PackageManager.INSTALL_SUCCEEDED;
11310             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11311             if (ret != PackageManager.INSTALL_SUCCEEDED) {
11312                 Slog.e(TAG, "Failed to copy package");
11313                 return ret;
11314             }
11315
11316             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11317             NativeLibraryHelper.Handle handle = null;
11318             try {
11319                 handle = NativeLibraryHelper.Handle.create(codeFile);
11320                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11321                         abiOverride);
11322             } catch (IOException e) {
11323                 Slog.e(TAG, "Copying native libraries failed", e);
11324                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11325             } finally {
11326                 IoUtils.closeQuietly(handle);
11327             }
11328
11329             return ret;
11330         }
11331
11332         int doPreInstall(int status) {
11333             if (status != PackageManager.INSTALL_SUCCEEDED) {
11334                 cleanUp();
11335             }
11336             return status;
11337         }
11338
11339         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11340             if (status != PackageManager.INSTALL_SUCCEEDED) {
11341                 cleanUp();
11342                 return false;
11343             }
11344
11345             final File targetDir = codeFile.getParentFile();
11346             final File beforeCodeFile = codeFile;
11347             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11348
11349             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11350             try {
11351                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11352             } catch (ErrnoException e) {
11353                 Slog.w(TAG, "Failed to rename", e);
11354                 return false;
11355             }
11356
11357             if (!SELinux.restoreconRecursive(afterCodeFile)) {
11358                 Slog.w(TAG, "Failed to restorecon");
11359                 return false;
11360             }
11361
11362             // Reflect the rename internally
11363             codeFile = afterCodeFile;
11364             resourceFile = afterCodeFile;
11365
11366             // Reflect the rename in scanned details
11367             pkg.codePath = afterCodeFile.getAbsolutePath();
11368             pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11369                     pkg.baseCodePath);
11370             pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11371                     pkg.splitCodePaths);
11372
11373             // Reflect the rename in app info
11374             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11375             pkg.applicationInfo.setCodePath(pkg.codePath);
11376             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11377             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11378             pkg.applicationInfo.setResourcePath(pkg.codePath);
11379             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11380             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11381
11382             return true;
11383         }
11384
11385         int doPostInstall(int status, int uid) {
11386             if (status != PackageManager.INSTALL_SUCCEEDED) {
11387                 cleanUp();
11388             }
11389             return status;
11390         }
11391
11392         @Override
11393         String getCodePath() {
11394             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11395         }
11396
11397         @Override
11398         String getResourcePath() {
11399             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11400         }
11401
11402         private boolean cleanUp() {
11403             if (codeFile == null || !codeFile.exists()) {
11404                 return false;
11405             }
11406
11407             if (codeFile.isDirectory()) {
11408                 mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11409             } else {
11410                 codeFile.delete();
11411             }
11412
11413             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11414                 resourceFile.delete();
11415             }
11416
11417             return true;
11418         }
11419
11420         void cleanUpResourcesLI() {
11421             // Try enumerating all code paths before deleting
11422             List<String> allCodePaths = Collections.EMPTY_LIST;
11423             if (codeFile != null && codeFile.exists()) {
11424                 try {
11425                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11426                     allCodePaths = pkg.getAllCodePaths();
11427                 } catch (PackageParserException e) {
11428                     // Ignored; we tried our best
11429                 }
11430             }
11431
11432             cleanUp();
11433             removeDexFiles(allCodePaths, instructionSets);
11434         }
11435
11436         boolean doPostDeleteLI(boolean delete) {
11437             // XXX err, shouldn't we respect the delete flag?
11438             cleanUpResourcesLI();
11439             return true;
11440         }
11441     }
11442
11443     private boolean isAsecExternal(String cid) {
11444         final String asecPath = PackageHelper.getSdFilesystem(cid);
11445         return !asecPath.startsWith(mAsecInternalPath);
11446     }
11447
11448     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11449             PackageManagerException {
11450         if (copyRet < 0) {
11451             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11452                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11453                 throw new PackageManagerException(copyRet, message);
11454             }
11455         }
11456     }
11457
11458     /**
11459      * Extract the MountService "container ID" from the full code path of an
11460      * .apk.
11461      */
11462     static String cidFromCodePath(String fullCodePath) {
11463         int eidx = fullCodePath.lastIndexOf("/");
11464         String subStr1 = fullCodePath.substring(0, eidx);
11465         int sidx = subStr1.lastIndexOf("/");
11466         return subStr1.substring(sidx+1, eidx);
11467     }
11468
11469     /**
11470      * Logic to handle installation of ASEC applications, including copying and
11471      * renaming logic.
11472      */
11473     class AsecInstallArgs extends InstallArgs {
11474         static final String RES_FILE_NAME = "pkg.apk";
11475         static final String PUBLIC_RES_FILE_NAME = "res.zip";
11476
11477         String cid;
11478         String packagePath;
11479         String resourcePath;
11480
11481         /** New install */
11482         AsecInstallArgs(InstallParams params) {
11483             super(params.origin, params.move, params.observer, params.installFlags,
11484                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11485                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11486                     params.grantedRuntimePermissions);
11487         }
11488
11489         /** Existing install */
11490         AsecInstallArgs(String fullCodePath, String[] instructionSets,
11491                         boolean isExternal, boolean isForwardLocked) {
11492             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11493                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11494                     instructionSets, null, null);
11495             // Hackily pretend we're still looking at a full code path
11496             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11497                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11498             }
11499
11500             // Extract cid from fullCodePath
11501             int eidx = fullCodePath.lastIndexOf("/");
11502             String subStr1 = fullCodePath.substring(0, eidx);
11503             int sidx = subStr1.lastIndexOf("/");
11504             cid = subStr1.substring(sidx+1, eidx);
11505             setMountPath(subStr1);
11506         }
11507
11508         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11509             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11510                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11511                     instructionSets, null, null);
11512             this.cid = cid;
11513             setMountPath(PackageHelper.getSdDir(cid));
11514         }
11515
11516         void createCopyFile() {
11517             cid = mInstallerService.allocateExternalStageCidLegacy();
11518         }
11519
11520         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11521             if (origin.staged) {
11522                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11523                 cid = origin.cid;
11524                 setMountPath(PackageHelper.getSdDir(cid));
11525                 return PackageManager.INSTALL_SUCCEEDED;
11526             }
11527
11528             if (temp) {
11529                 createCopyFile();
11530             } else {
11531                 /*
11532                  * Pre-emptively destroy the container since it's destroyed if
11533                  * copying fails due to it existing anyway.
11534                  */
11535                 PackageHelper.destroySdDir(cid);
11536             }
11537
11538             final String newMountPath = imcs.copyPackageToContainer(
11539                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11540                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11541
11542             if (newMountPath != null) {
11543                 setMountPath(newMountPath);
11544                 return PackageManager.INSTALL_SUCCEEDED;
11545             } else {
11546                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11547             }
11548         }
11549
11550         @Override
11551         String getCodePath() {
11552             return packagePath;
11553         }
11554
11555         @Override
11556         String getResourcePath() {
11557             return resourcePath;
11558         }
11559
11560         int doPreInstall(int status) {
11561             if (status != PackageManager.INSTALL_SUCCEEDED) {
11562                 // Destroy container
11563                 PackageHelper.destroySdDir(cid);
11564             } else {
11565                 boolean mounted = PackageHelper.isContainerMounted(cid);
11566                 if (!mounted) {
11567                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11568                             Process.SYSTEM_UID);
11569                     if (newMountPath != null) {
11570                         setMountPath(newMountPath);
11571                     } else {
11572                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11573                     }
11574                 }
11575             }
11576             return status;
11577         }
11578
11579         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11580             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11581             String newMountPath = null;
11582             if (PackageHelper.isContainerMounted(cid)) {
11583                 // Unmount the container
11584                 if (!PackageHelper.unMountSdDir(cid)) {
11585                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11586                     return false;
11587                 }
11588             }
11589             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11590                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11591                         " which might be stale. Will try to clean up.");
11592                 // Clean up the stale container and proceed to recreate.
11593                 if (!PackageHelper.destroySdDir(newCacheId)) {
11594                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11595                     return false;
11596                 }
11597                 // Successfully cleaned up stale container. Try to rename again.
11598                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11599                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11600                             + " inspite of cleaning it up.");
11601                     return false;
11602                 }
11603             }
11604             if (!PackageHelper.isContainerMounted(newCacheId)) {
11605                 Slog.w(TAG, "Mounting container " + newCacheId);
11606                 newMountPath = PackageHelper.mountSdDir(newCacheId,
11607                         getEncryptKey(), Process.SYSTEM_UID);
11608             } else {
11609                 newMountPath = PackageHelper.getSdDir(newCacheId);
11610             }
11611             if (newMountPath == null) {
11612                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11613                 return false;
11614             }
11615             Log.i(TAG, "Succesfully renamed " + cid +
11616                     " to " + newCacheId +
11617                     " at new path: " + newMountPath);
11618             cid = newCacheId;
11619
11620             final File beforeCodeFile = new File(packagePath);
11621             setMountPath(newMountPath);
11622             final File afterCodeFile = new File(packagePath);
11623
11624             // Reflect the rename in scanned details
11625             pkg.codePath = afterCodeFile.getAbsolutePath();
11626             pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11627                     pkg.baseCodePath);
11628             pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11629                     pkg.splitCodePaths);
11630
11631             // Reflect the rename in app info
11632             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11633             pkg.applicationInfo.setCodePath(pkg.codePath);
11634             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11635             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11636             pkg.applicationInfo.setResourcePath(pkg.codePath);
11637             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11638             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11639
11640             return true;
11641         }
11642
11643         private void setMountPath(String mountPath) {
11644             final File mountFile = new File(mountPath);
11645
11646             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11647             if (monolithicFile.exists()) {
11648                 packagePath = monolithicFile.getAbsolutePath();
11649                 if (isFwdLocked()) {
11650                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11651                 } else {
11652                     resourcePath = packagePath;
11653                 }
11654             } else {
11655                 packagePath = mountFile.getAbsolutePath();
11656                 resourcePath = packagePath;
11657             }
11658         }
11659
11660         int doPostInstall(int status, int uid) {
11661             if (status != PackageManager.INSTALL_SUCCEEDED) {
11662                 cleanUp();
11663             } else {
11664                 final int groupOwner;
11665                 final String protectedFile;
11666                 if (isFwdLocked()) {
11667                     groupOwner = UserHandle.getSharedAppGid(uid);
11668                     protectedFile = RES_FILE_NAME;
11669                 } else {
11670                     groupOwner = -1;
11671                     protectedFile = null;
11672                 }
11673
11674                 if (uid < Process.FIRST_APPLICATION_UID
11675                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11676                     Slog.e(TAG, "Failed to finalize " + cid);
11677                     PackageHelper.destroySdDir(cid);
11678                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11679                 }
11680
11681                 boolean mounted = PackageHelper.isContainerMounted(cid);
11682                 if (!mounted) {
11683                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11684                 }
11685             }
11686             return status;
11687         }
11688
11689         private void cleanUp() {
11690             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11691
11692             // Destroy secure container
11693             PackageHelper.destroySdDir(cid);
11694         }
11695
11696         private List<String> getAllCodePaths() {
11697             final File codeFile = new File(getCodePath());
11698             if (codeFile != null && codeFile.exists()) {
11699                 try {
11700                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11701                     return pkg.getAllCodePaths();
11702                 } catch (PackageParserException e) {
11703                     // Ignored; we tried our best
11704                 }
11705             }
11706             return Collections.EMPTY_LIST;
11707         }
11708
11709         void cleanUpResourcesLI() {
11710             // Enumerate all code paths before deleting
11711             cleanUpResourcesLI(getAllCodePaths());
11712         }
11713
11714         private void cleanUpResourcesLI(List<String> allCodePaths) {
11715             cleanUp();
11716             removeDexFiles(allCodePaths, instructionSets);
11717         }
11718
11719         String getPackageName() {
11720             return getAsecPackageName(cid);
11721         }
11722
11723         boolean doPostDeleteLI(boolean delete) {
11724             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11725             final List<String> allCodePaths = getAllCodePaths();
11726             boolean mounted = PackageHelper.isContainerMounted(cid);
11727             if (mounted) {
11728                 // Unmount first
11729                 if (PackageHelper.unMountSdDir(cid)) {
11730                     mounted = false;
11731                 }
11732             }
11733             if (!mounted && delete) {
11734                 cleanUpResourcesLI(allCodePaths);
11735             }
11736             return !mounted;
11737         }
11738
11739         @Override
11740         int doPreCopy() {
11741             if (isFwdLocked()) {
11742                 if (!PackageHelper.fixSdPermissions(cid,
11743                         getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11744                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11745                 }
11746             }
11747
11748             return PackageManager.INSTALL_SUCCEEDED;
11749         }
11750
11751         @Override
11752         int doPostCopy(int uid) {
11753             if (isFwdLocked()) {
11754                 if (uid < Process.FIRST_APPLICATION_UID
11755                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11756                                 RES_FILE_NAME)) {
11757                     Slog.e(TAG, "Failed to finalize " + cid);
11758                     PackageHelper.destroySdDir(cid);
11759                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11760                 }
11761             }
11762
11763             return PackageManager.INSTALL_SUCCEEDED;
11764         }
11765     }
11766
11767     /**
11768      * Logic to handle movement of existing installed applications.
11769      */
11770     class MoveInstallArgs extends InstallArgs {
11771         private File codeFile;
11772         private File resourceFile;
11773
11774         /** New install */
11775         MoveInstallArgs(InstallParams params) {
11776             super(params.origin, params.move, params.observer, params.installFlags,
11777                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11778                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11779                     params.grantedRuntimePermissions);
11780         }
11781
11782         int copyApk(IMediaContainerService imcs, boolean temp) {
11783             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11784                     + move.fromUuid + " to " + move.toUuid);
11785             synchronized (mInstaller) {
11786                 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11787                         move.dataAppName, move.appId, move.seinfo) != 0) {
11788                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11789                 }
11790             }
11791
11792             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11793             resourceFile = codeFile;
11794             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11795
11796             return PackageManager.INSTALL_SUCCEEDED;
11797         }
11798
11799         int doPreInstall(int status) {
11800             if (status != PackageManager.INSTALL_SUCCEEDED) {
11801                 cleanUp(move.toUuid);
11802             }
11803             return status;
11804         }
11805
11806         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11807             if (status != PackageManager.INSTALL_SUCCEEDED) {
11808                 cleanUp(move.toUuid);
11809                 return false;
11810             }
11811
11812             // Reflect the move in app info
11813             pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11814             pkg.applicationInfo.setCodePath(pkg.codePath);
11815             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11816             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11817             pkg.applicationInfo.setResourcePath(pkg.codePath);
11818             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11819             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11820
11821             return true;
11822         }
11823
11824         int doPostInstall(int status, int uid) {
11825             if (status == PackageManager.INSTALL_SUCCEEDED) {
11826                 cleanUp(move.fromUuid);
11827             } else {
11828                 cleanUp(move.toUuid);
11829             }
11830             return status;
11831         }
11832
11833         @Override
11834         String getCodePath() {
11835             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11836         }
11837
11838         @Override
11839         String getResourcePath() {
11840             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11841         }
11842
11843         private boolean cleanUp(String volumeUuid) {
11844             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11845                     move.dataAppName);
11846             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11847             synchronized (mInstallLock) {
11848                 // Clean up both app data and code
11849                 removeDataDirsLI(volumeUuid, move.packageName);
11850                 if (codeFile.isDirectory()) {
11851                     mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11852                 } else {
11853                     codeFile.delete();
11854                 }
11855             }
11856             return true;
11857         }
11858
11859         void cleanUpResourcesLI() {
11860             throw new UnsupportedOperationException();
11861         }
11862
11863         boolean doPostDeleteLI(boolean delete) {
11864             throw new UnsupportedOperationException();
11865         }
11866     }
11867
11868     static String getAsecPackageName(String packageCid) {
11869         int idx = packageCid.lastIndexOf("-");
11870         if (idx == -1) {
11871             return packageCid;
11872         }
11873         return packageCid.substring(0, idx);
11874     }
11875
11876     // Utility method used to create code paths based on package name and available index.
11877     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11878         String idxStr = "";
11879         int idx = 1;
11880         // Fall back to default value of idx=1 if prefix is not
11881         // part of oldCodePath
11882         if (oldCodePath != null) {
11883             String subStr = oldCodePath;
11884             // Drop the suffix right away
11885             if (suffix != null && subStr.endsWith(suffix)) {
11886                 subStr = subStr.substring(0, subStr.length() - suffix.length());
11887             }
11888             // If oldCodePath already contains prefix find out the
11889             // ending index to either increment or decrement.
11890             int sidx = subStr.lastIndexOf(prefix);
11891             if (sidx != -1) {
11892                 subStr = subStr.substring(sidx + prefix.length());
11893                 if (subStr != null) {
11894                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11895                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11896                     }
11897                     try {
11898                         idx = Integer.parseInt(subStr);
11899                         if (idx <= 1) {
11900                             idx++;
11901                         } else {
11902                             idx--;
11903                         }
11904                     } catch(NumberFormatException e) {
11905                     }
11906                 }
11907             }
11908         }
11909         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11910         return prefix + idxStr;
11911     }
11912
11913     private File getNextCodePath(File targetDir, String packageName) {
11914         int suffix = 1;
11915         File result;
11916         do {
11917             result = new File(targetDir, packageName + "-" + suffix);
11918             suffix++;
11919         } while (result.exists());
11920         return result;
11921     }
11922
11923     // Utility method that returns the relative package path with respect
11924     // to the installation directory. Like say for /data/data/com.test-1.apk
11925     // string com.test-1 is returned.
11926     static String deriveCodePathName(String codePath) {
11927         if (codePath == null) {
11928             return null;
11929         }
11930         final File codeFile = new File(codePath);
11931         final String name = codeFile.getName();
11932         if (codeFile.isDirectory()) {
11933             return name;
11934         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11935             final int lastDot = name.lastIndexOf('.');
11936             return name.substring(0, lastDot);
11937         } else {
11938             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11939             return null;
11940         }
11941     }
11942
11943     class PackageInstalledInfo {
11944         String name;
11945         int uid;
11946         // The set of users that originally had this package installed.
11947         int[] origUsers;
11948         // The set of users that now have this package installed.
11949         int[] newUsers;
11950         PackageParser.Package pkg;
11951         int returnCode;
11952         String returnMsg;
11953         PackageRemovedInfo removedInfo;
11954
11955         public void setError(int code, String msg) {
11956             returnCode = code;
11957             returnMsg = msg;
11958             Slog.w(TAG, msg);
11959         }
11960
11961         public void setError(String msg, PackageParserException e) {
11962             returnCode = e.error;
11963             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11964             Slog.w(TAG, msg, e);
11965         }
11966
11967         public void setError(String msg, PackageManagerException e) {
11968             returnCode = e.error;
11969             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11970             Slog.w(TAG, msg, e);
11971         }
11972
11973         // In some error cases we want to convey more info back to the observer
11974         String origPackage;
11975         String origPermission;
11976     }
11977
11978     /*
11979      * Install a non-existing package.
11980      */
11981     private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11982             UserHandle user, String installerPackageName, String volumeUuid,
11983             PackageInstalledInfo res) {
11984         // Remember this for later, in case we need to rollback this install
11985         String pkgName = pkg.packageName;
11986
11987         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11988         final boolean dataDirExists = Environment
11989                 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11990         synchronized(mPackages) {
11991             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11992                 // A package with the same name is already installed, though
11993                 // it has been renamed to an older name.  The package we
11994                 // are trying to install should be installed as an update to
11995                 // the existing one, but that has not been requested, so bail.
11996                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11997                         + " without first uninstalling package running as "
11998                         + mSettings.mRenamedPackages.get(pkgName));
11999                 return;
12000             }
12001             if (mPackages.containsKey(pkgName)) {
12002                 // Don't allow installation over an existing package with the same name.
12003                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12004                         + " without first uninstalling.");
12005                 return;
12006             }
12007         }
12008
12009         try {
12010             PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
12011                     System.currentTimeMillis(), user);
12012
12013             updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12014             // delete the partially installed application. the data directory will have to be
12015             // restored if it was already existing
12016             if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12017                 // remove package from internal structures.  Note that we want deletePackageX to
12018                 // delete the package data and cache directories that it created in
12019                 // scanPackageLocked, unless those directories existed before we even tried to
12020                 // install.
12021                 deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12022                         dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12023                                 res.removedInfo, true);
12024             }
12025
12026         } catch (PackageManagerException e) {
12027             res.setError("Package couldn't be installed in " + pkg.codePath, e);
12028         }
12029     }
12030
12031     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12032         // Can't rotate keys during boot or if sharedUser.
12033         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12034                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12035             return false;
12036         }
12037         // app is using upgradeKeySets; make sure all are valid
12038         KeySetManagerService ksms = mSettings.mKeySetManagerService;
12039         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12040         for (int i = 0; i < upgradeKeySets.length; i++) {
12041             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12042                 Slog.wtf(TAG, "Package "
12043                          + (oldPs.name != null ? oldPs.name : "<null>")
12044                          + " contains upgrade-key-set reference to unknown key-set: "
12045                          + upgradeKeySets[i]
12046                          + " reverting to signatures check.");
12047                 return false;
12048             }
12049         }
12050         return true;
12051     }
12052
12053     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12054         // Upgrade keysets are being used.  Determine if new package has a superset of the
12055         // required keys.
12056         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12057         KeySetManagerService ksms = mSettings.mKeySetManagerService;
12058         for (int i = 0; i < upgradeKeySets.length; i++) {
12059             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12060             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12061                 return true;
12062             }
12063         }
12064         return false;
12065     }
12066
12067     private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12068             UserHandle user, String installerPackageName, String volumeUuid,
12069             PackageInstalledInfo res) {
12070         final PackageParser.Package oldPackage;
12071         final String pkgName = pkg.packageName;
12072         final int[] allUsers;
12073         final boolean[] perUserInstalled;
12074
12075         // First find the old package info and check signatures
12076         synchronized(mPackages) {
12077             oldPackage = mPackages.get(pkgName);
12078             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12079             final PackageSetting ps = mSettings.mPackages.get(pkgName);
12080             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12081                 if(!checkUpgradeKeySetLP(ps, pkg)) {
12082                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12083                             "New package not signed by keys specified by upgrade-keysets: "
12084                             + pkgName);
12085                     return;
12086                 }
12087             } else {
12088                 // default to original signature matching
12089                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12090                     != PackageManager.SIGNATURE_MATCH) {
12091                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12092                             "New package has a different signature: " + pkgName);
12093                     return;
12094                 }
12095             }
12096
12097             // In case of rollback, remember per-user/profile install state
12098             allUsers = sUserManager.getUserIds();
12099             perUserInstalled = new boolean[allUsers.length];
12100             for (int i = 0; i < allUsers.length; i++) {
12101                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12102             }
12103         }
12104
12105         boolean sysPkg = (isSystemApp(oldPackage));
12106         if (sysPkg) {
12107             replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12108                     user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12109         } else {
12110             replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12111                     user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12112         }
12113     }
12114
12115     private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12116             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12117             int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12118             String volumeUuid, PackageInstalledInfo res) {
12119         String pkgName = deletedPackage.packageName;
12120         boolean deletedPkg = true;
12121         boolean updatedSettings = false;
12122
12123         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12124                 + deletedPackage);
12125         long origUpdateTime;
12126         if (pkg.mExtras != null) {
12127             origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12128         } else {
12129             origUpdateTime = 0;
12130         }
12131
12132         // First delete the existing package while retaining the data directory
12133         if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12134                 res.removedInfo, true)) {
12135             // If the existing package wasn't successfully deleted
12136             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12137             deletedPkg = false;
12138         } else {
12139             // Successfully deleted the old package; proceed with replace.
12140
12141             // If deleted package lived in a container, give users a chance to
12142             // relinquish resources before killing.
12143             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12144                 if (DEBUG_INSTALL) {
12145                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12146                 }
12147                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12148                 final ArrayList<String> pkgList = new ArrayList<String>(1);
12149                 pkgList.add(deletedPackage.applicationInfo.packageName);
12150                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12151             }
12152
12153             deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12154             try {
12155                 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
12156                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12157                 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12158                         perUserInstalled, res, user);
12159                 updatedSettings = true;
12160             } catch (PackageManagerException e) {
12161                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
12162             }
12163         }
12164
12165         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12166             // remove package from internal structures.  Note that we want deletePackageX to
12167             // delete the package data and cache directories that it created in
12168             // scanPackageLocked, unless those directories existed before we even tried to
12169             // install.
12170             if(updatedSettings) {
12171                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12172                 deletePackageLI(
12173                         pkgName, null, true, allUsers, perUserInstalled,
12174                         PackageManager.DELETE_KEEP_DATA,
12175                                 res.removedInfo, true);
12176             }
12177             // Since we failed to install the new package we need to restore the old
12178             // package that we deleted.
12179             if (deletedPkg) {
12180                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12181                 File restoreFile = new File(deletedPackage.codePath);
12182                 // Parse old package
12183                 boolean oldExternal = isExternal(deletedPackage);
12184                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12185                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12186                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12187                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12188                 try {
12189                     scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12190                 } catch (PackageManagerException e) {
12191                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12192                             + e.getMessage());
12193                     return;
12194                 }
12195                 // Restore of old package succeeded. Update permissions.
12196                 // writer
12197                 synchronized (mPackages) {
12198                     updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12199                             UPDATE_PERMISSIONS_ALL);
12200                     // can downgrade to reader
12201                     mSettings.writeLPr();
12202                 }
12203                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12204             }
12205         }
12206     }
12207
12208     private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12209             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12210             int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12211             String volumeUuid, PackageInstalledInfo res) {
12212         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12213                 + ", old=" + deletedPackage);
12214         boolean disabledSystem = false;
12215         boolean updatedSettings = false;
12216         parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12217         if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12218                 != 0) {
12219             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12220         }
12221         String packageName = deletedPackage.packageName;
12222         if (packageName == null) {
12223             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12224                     "Attempt to delete null packageName.");
12225             return;
12226         }
12227         PackageParser.Package oldPkg;
12228         PackageSetting oldPkgSetting;
12229         // reader
12230         synchronized (mPackages) {
12231             oldPkg = mPackages.get(packageName);
12232             oldPkgSetting = mSettings.mPackages.get(packageName);
12233             if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12234                     (oldPkgSetting == null)) {
12235                 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12236                         "Couldn't find package:" + packageName + " information");
12237                 return;
12238             }
12239         }
12240
12241         killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12242
12243         res.removedInfo.uid = oldPkg.applicationInfo.uid;
12244         res.removedInfo.removedPackage = packageName;
12245         // Remove existing system package
12246         removePackageLI(oldPkgSetting, true);
12247         // writer
12248         synchronized (mPackages) {
12249             disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12250             if (!disabledSystem && deletedPackage != null) {
12251                 // We didn't need to disable the .apk as a current system package,
12252                 // which means we are replacing another update that is already
12253                 // installed.  We need to make sure to delete the older one's .apk.
12254                 res.removedInfo.args = createInstallArgsForExisting(0,
12255                         deletedPackage.applicationInfo.getCodePath(),
12256                         deletedPackage.applicationInfo.getResourcePath(),
12257                         getAppDexInstructionSets(deletedPackage.applicationInfo));
12258             } else {
12259                 res.removedInfo.args = null;
12260             }
12261         }
12262
12263         // Successfully disabled the old package. Now proceed with re-installation
12264         deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12265
12266         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12267         pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12268
12269         PackageParser.Package newPackage = null;
12270         try {
12271             newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12272             if (newPackage.mExtras != null) {
12273                 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12274                 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12275                 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12276
12277                 // is the update attempting to change shared user? that isn't going to work...
12278                 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12279                     res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12280                             "Forbidding shared user change from " + oldPkgSetting.sharedUser
12281                             + " to " + newPkgSetting.sharedUser);
12282                     updatedSettings = true;
12283                 }
12284             }
12285
12286             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12287                 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12288                         perUserInstalled, res, user);
12289                 updatedSettings = true;
12290             }
12291
12292         } catch (PackageManagerException e) {
12293             res.setError("Package couldn't be installed in " + pkg.codePath, e);
12294         }
12295
12296         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12297             // Re installation failed. Restore old information
12298             // Remove new pkg information
12299             if (newPackage != null) {
12300                 removeInstalledPackageLI(newPackage, true);
12301             }
12302             // Add back the old system package
12303             try {
12304                 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12305             } catch (PackageManagerException e) {
12306                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12307             }
12308             // Restore the old system information in Settings
12309             synchronized (mPackages) {
12310                 if (disabledSystem) {
12311                     mSettings.enableSystemPackageLPw(packageName);
12312                 }
12313                 if (updatedSettings) {
12314                     mSettings.setInstallerPackageName(packageName,
12315                             oldPkgSetting.installerPackageName);
12316                 }
12317                 mSettings.writeLPr();
12318             }
12319         }
12320     }
12321
12322     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12323             String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12324             UserHandle user) {
12325         String pkgName = newPackage.packageName;
12326         synchronized (mPackages) {
12327             //write settings. the installStatus will be incomplete at this stage.
12328             //note that the new package setting would have already been
12329             //added to mPackages. It hasn't been persisted yet.
12330             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12331             mSettings.writeLPr();
12332         }
12333
12334         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12335
12336         synchronized (mPackages) {
12337             updatePermissionsLPw(newPackage.packageName, newPackage,
12338                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12339                             ? UPDATE_PERMISSIONS_ALL : 0));
12340             // For system-bundled packages, we assume that installing an upgraded version
12341             // of the package implies that the user actually wants to run that new code,
12342             // so we enable the package.
12343             PackageSetting ps = mSettings.mPackages.get(pkgName);
12344             if (ps != null) {
12345                 if (isSystemApp(newPackage)) {
12346                     // NB: implicit assumption that system package upgrades apply to all users
12347                     if (DEBUG_INSTALL) {
12348                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12349                     }
12350                     if (res.origUsers != null) {
12351                         for (int userHandle : res.origUsers) {
12352                             ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12353                                     userHandle, installerPackageName);
12354                         }
12355                     }
12356                     // Also convey the prior install/uninstall state
12357                     if (allUsers != null && perUserInstalled != null) {
12358                         for (int i = 0; i < allUsers.length; i++) {
12359                             if (DEBUG_INSTALL) {
12360                                 Slog.d(TAG, "    user " + allUsers[i]
12361                                         + " => " + perUserInstalled[i]);
12362                             }
12363                             ps.setInstalled(perUserInstalled[i], allUsers[i]);
12364                         }
12365                         // these install state changes will be persisted in the
12366                         // upcoming call to mSettings.writeLPr().
12367                     }
12368                 }
12369                 // It's implied that when a user requests installation, they want the app to be
12370                 // installed and enabled.
12371                 int userId = user.getIdentifier();
12372                 if (userId != UserHandle.USER_ALL) {
12373                     ps.setInstalled(true, userId);
12374                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12375                 }
12376             }
12377             res.name = pkgName;
12378             res.uid = newPackage.applicationInfo.uid;
12379             res.pkg = newPackage;
12380             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12381             mSettings.setInstallerPackageName(pkgName, installerPackageName);
12382             res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12383             //to update install status
12384             mSettings.writeLPr();
12385         }
12386     }
12387
12388     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12389         final int installFlags = args.installFlags;
12390         final String installerPackageName = args.installerPackageName;
12391         final String volumeUuid = args.volumeUuid;
12392         final File tmpPackageFile = new File(args.getCodePath());
12393         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12394         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12395                 || (args.volumeUuid != null));
12396         boolean replace = false;
12397         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12398         if (args.move != null) {
12399             // moving a complete application; perfom an initial scan on the new install location
12400             scanFlags |= SCAN_INITIAL;
12401         }
12402         // Result object to be returned
12403         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12404
12405         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12406         // Retrieve PackageSettings and parse package
12407         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12408                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12409                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12410         PackageParser pp = new PackageParser();
12411         pp.setSeparateProcesses(mSeparateProcesses);
12412         pp.setDisplayMetrics(mMetrics);
12413
12414         final PackageParser.Package pkg;
12415         try {
12416             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12417         } catch (PackageParserException e) {
12418             res.setError("Failed parse during installPackageLI", e);
12419             return;
12420         }
12421
12422         // Mark that we have an install time CPU ABI override.
12423         pkg.cpuAbiOverride = args.abiOverride;
12424
12425         String pkgName = res.name = pkg.packageName;
12426         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12427             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12428                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12429                 return;
12430             }
12431         }
12432
12433         try {
12434             pp.collectCertificates(pkg, parseFlags);
12435             pp.collectManifestDigest(pkg);
12436         } catch (PackageParserException e) {
12437             res.setError("Failed collect during installPackageLI", e);
12438             return;
12439         }
12440
12441         /* If the installer passed in a manifest digest, compare it now. */
12442         if (args.manifestDigest != null) {
12443             if (DEBUG_INSTALL) {
12444                 final String parsedManifest = pkg.manifestDigest == null ? "null"
12445                         : pkg.manifestDigest.toString();
12446                 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12447                         + parsedManifest);
12448             }
12449
12450             if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12451                 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12452                 return;
12453             }
12454         } else if (DEBUG_INSTALL) {
12455             final String parsedManifest = pkg.manifestDigest == null
12456                     ? "null" : pkg.manifestDigest.toString();
12457             Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12458         }
12459
12460         // Get rid of all references to package scan path via parser.
12461         pp = null;
12462         String oldCodePath = null;
12463         boolean systemApp = false;
12464         synchronized (mPackages) {
12465             // Check if installing already existing package
12466             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12467                 String oldName = mSettings.mRenamedPackages.get(pkgName);
12468                 if (pkg.mOriginalPackages != null
12469                         && pkg.mOriginalPackages.contains(oldName)
12470                         && mPackages.containsKey(oldName)) {
12471                     // This package is derived from an original package,
12472                     // and this device has been updating from that original
12473                     // name.  We must continue using the original name, so
12474                     // rename the new package here.
12475                     pkg.setPackageName(oldName);
12476                     pkgName = pkg.packageName;
12477                     replace = true;
12478                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12479                             + oldName + " pkgName=" + pkgName);
12480                 } else if (mPackages.containsKey(pkgName)) {
12481                     // This package, under its official name, already exists
12482                     // on the device; we should replace it.
12483                     replace = true;
12484                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12485                 }
12486
12487                 // Prevent apps opting out from runtime permissions
12488                 if (replace) {
12489                     PackageParser.Package oldPackage = mPackages.get(pkgName);
12490                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12491                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12492                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12493                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12494                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12495                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12496                                         + " doesn't support runtime permissions but the old"
12497                                         + " target SDK " + oldTargetSdk + " does.");
12498                         return;
12499                     }
12500                 }
12501             }
12502
12503             PackageSetting ps = mSettings.mPackages.get(pkgName);
12504             if (ps != null) {
12505                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12506
12507                 // Quick sanity check that we're signed correctly if updating;
12508                 // we'll check this again later when scanning, but we want to
12509                 // bail early here before tripping over redefined permissions.
12510                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12511                     if (!checkUpgradeKeySetLP(ps, pkg)) {
12512                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12513                                 + pkg.packageName + " upgrade keys do not match the "
12514                                 + "previously installed version");
12515                         return;
12516                     }
12517                 } else {
12518                     try {
12519                         verifySignaturesLP(ps, pkg);
12520                     } catch (PackageManagerException e) {
12521                         res.setError(e.error, e.getMessage());
12522                         return;
12523                     }
12524                 }
12525
12526                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12527                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12528                     systemApp = (ps.pkg.applicationInfo.flags &
12529                             ApplicationInfo.FLAG_SYSTEM) != 0;
12530                 }
12531                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12532             }
12533
12534             // Check whether the newly-scanned package wants to define an already-defined perm
12535             int N = pkg.permissions.size();
12536             for (int i = N-1; i >= 0; i--) {
12537                 PackageParser.Permission perm = pkg.permissions.get(i);
12538                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12539                 if (bp != null) {
12540                     // If the defining package is signed with our cert, it's okay.  This
12541                     // also includes the "updating the same package" case, of course.
12542                     // "updating same package" could also involve key-rotation.
12543                     final boolean sigsOk;
12544                     if (bp.sourcePackage.equals(pkg.packageName)
12545                             && (bp.packageSetting instanceof PackageSetting)
12546                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12547                                     scanFlags))) {
12548                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12549                     } else {
12550                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12551                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12552                     }
12553                     if (!sigsOk) {
12554                         // If the owning package is the system itself, we log but allow
12555                         // install to proceed; we fail the install on all other permission
12556                         // redefinitions.
12557                         if (!bp.sourcePackage.equals("android")) {
12558                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12559                                     + pkg.packageName + " attempting to redeclare permission "
12560                                     + perm.info.name + " already owned by " + bp.sourcePackage);
12561                             res.origPermission = perm.info.name;
12562                             res.origPackage = bp.sourcePackage;
12563                             return;
12564                         } else {
12565                             Slog.w(TAG, "Package " + pkg.packageName
12566                                     + " attempting to redeclare system permission "
12567                                     + perm.info.name + "; ignoring new declaration");
12568                             pkg.permissions.remove(i);
12569                         }
12570                     }
12571                 }
12572             }
12573
12574         }
12575
12576         if (systemApp && onExternal) {
12577             // Disable updates to system apps on sdcard
12578             res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12579                     "Cannot install updates to system apps on sdcard");
12580             return;
12581         }
12582
12583         if (args.move != null) {
12584             // We did an in-place move, so dex is ready to roll
12585             scanFlags |= SCAN_NO_DEX;
12586             scanFlags |= SCAN_MOVE;
12587
12588             synchronized (mPackages) {
12589                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
12590                 if (ps == null) {
12591                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12592                             "Missing settings for moved package " + pkgName);
12593                 }
12594
12595                 // We moved the entire application as-is, so bring over the
12596                 // previously derived ABI information.
12597                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12598                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12599             }
12600
12601         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12602             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12603             scanFlags |= SCAN_NO_DEX;
12604
12605             try {
12606                 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12607                         true /* extract libs */);
12608             } catch (PackageManagerException pme) {
12609                 Slog.e(TAG, "Error deriving application ABI", pme);
12610                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12611                 return;
12612             }
12613
12614             // Run dexopt before old package gets removed, to minimize time when app is unavailable
12615             int result = mPackageDexOptimizer
12616                     .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12617                             false /* defer */, false /* inclDependencies */);
12618             if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12619                 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12620                 return;
12621             }
12622         }
12623
12624         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12625             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12626             return;
12627         }
12628
12629         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12630
12631         if (replace) {
12632             replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12633                     installerPackageName, volumeUuid, res);
12634         } else {
12635             installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12636                     args.user, installerPackageName, volumeUuid, res);
12637         }
12638         synchronized (mPackages) {
12639             final PackageSetting ps = mSettings.mPackages.get(pkgName);
12640             if (ps != null) {
12641                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12642             }
12643         }
12644     }
12645
12646     private void startIntentFilterVerifications(int userId, boolean replacing,
12647             PackageParser.Package pkg) {
12648         if (mIntentFilterVerifierComponent == null) {
12649             Slog.w(TAG, "No IntentFilter verification will not be done as "
12650                     + "there is no IntentFilterVerifier available!");
12651             return;
12652         }
12653
12654         final int verifierUid = getPackageUid(
12655                 mIntentFilterVerifierComponent.getPackageName(),
12656                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12657
12658         mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12659         final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12660         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12661         mHandler.sendMessage(msg);
12662     }
12663
12664     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12665             PackageParser.Package pkg) {
12666         int size = pkg.activities.size();
12667         if (size == 0) {
12668             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12669                     "No activity, so no need to verify any IntentFilter!");
12670             return;
12671         }
12672
12673         final boolean hasDomainURLs = hasDomainURLs(pkg);
12674         if (!hasDomainURLs) {
12675             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12676                     "No domain URLs, so no need to verify any IntentFilter!");
12677             return;
12678         }
12679
12680         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12681                 + " if any IntentFilter from the " + size
12682                 + " Activities needs verification ...");
12683
12684         int count = 0;
12685         final String packageName = pkg.packageName;
12686
12687         synchronized (mPackages) {
12688             // If this is a new install and we see that we've already run verification for this
12689             // package, we have nothing to do: it means the state was restored from backup.
12690             if (!replacing) {
12691                 IntentFilterVerificationInfo ivi =
12692                         mSettings.getIntentFilterVerificationLPr(packageName);
12693                 if (ivi != null) {
12694                     if (DEBUG_DOMAIN_VERIFICATION) {
12695                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
12696                                 + ivi.getStatusString());
12697                     }
12698                     return;
12699                 }
12700             }
12701
12702             // If any filters need to be verified, then all need to be.
12703             boolean needToVerify = false;
12704             for (PackageParser.Activity a : pkg.activities) {
12705                 for (ActivityIntentInfo filter : a.intents) {
12706                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12707                         if (DEBUG_DOMAIN_VERIFICATION) {
12708                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12709                         }
12710                         needToVerify = true;
12711                         break;
12712                     }
12713                 }
12714             }
12715
12716             if (needToVerify) {
12717                 final int verificationId = mIntentFilterVerificationToken++;
12718                 for (PackageParser.Activity a : pkg.activities) {
12719                     for (ActivityIntentInfo filter : a.intents) {
12720                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12721                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12722                                     "Verification needed for IntentFilter:" + filter.toString());
12723                             mIntentFilterVerifier.addOneIntentFilterVerification(
12724                                     verifierUid, userId, verificationId, filter, packageName);
12725                             count++;
12726                         }
12727                     }
12728                 }
12729             }
12730         }
12731
12732         if (count > 0) {
12733             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12734                     + " IntentFilter verification" + (count > 1 ? "s" : "")
12735                     +  " for userId:" + userId);
12736             mIntentFilterVerifier.startVerifications(userId);
12737         } else {
12738             if (DEBUG_DOMAIN_VERIFICATION) {
12739                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12740             }
12741         }
12742     }
12743
12744     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12745         final ComponentName cn  = filter.activity.getComponentName();
12746         final String packageName = cn.getPackageName();
12747
12748         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12749                 packageName);
12750         if (ivi == null) {
12751             return true;
12752         }
12753         int status = ivi.getStatus();
12754         switch (status) {
12755             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12756             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12757                 return true;
12758
12759             default:
12760                 // Nothing to do
12761                 return false;
12762         }
12763     }
12764
12765     private static boolean isMultiArch(PackageSetting ps) {
12766         return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12767     }
12768
12769     private static boolean isMultiArch(ApplicationInfo info) {
12770         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12771     }
12772
12773     private static boolean isExternal(PackageParser.Package pkg) {
12774         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12775     }
12776
12777     private static boolean isExternal(PackageSetting ps) {
12778         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12779     }
12780
12781     private static boolean isExternal(ApplicationInfo info) {
12782         return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12783     }
12784
12785     private static boolean isSystemApp(PackageParser.Package pkg) {
12786         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12787     }
12788
12789     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12790         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12791     }
12792
12793     private static boolean hasDomainURLs(PackageParser.Package pkg) {
12794         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12795     }
12796
12797     private static boolean isSystemApp(PackageSetting ps) {
12798         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12799     }
12800
12801     private static boolean isUpdatedSystemApp(PackageSetting ps) {
12802         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12803     }
12804
12805     private int packageFlagsToInstallFlags(PackageSetting ps) {
12806         int installFlags = 0;
12807         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12808             // This existing package was an external ASEC install when we have
12809             // the external flag without a UUID
12810             installFlags |= PackageManager.INSTALL_EXTERNAL;
12811         }
12812         if (ps.isForwardLocked()) {
12813             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12814         }
12815         return installFlags;
12816     }
12817
12818     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12819         if (isExternal(pkg)) {
12820             if (TextUtils.isEmpty(pkg.volumeUuid)) {
12821                 return mSettings.getExternalVersion();
12822             } else {
12823                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
12824             }
12825         } else {
12826             return mSettings.getInternalVersion();
12827         }
12828     }
12829
12830     private void deleteTempPackageFiles() {
12831         final FilenameFilter filter = new FilenameFilter() {
12832             public boolean accept(File dir, String name) {
12833                 return name.startsWith("vmdl") && name.endsWith(".tmp");
12834             }
12835         };
12836         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12837             file.delete();
12838         }
12839     }
12840
12841     @Override
12842     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12843             int flags) {
12844         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12845                 flags);
12846     }
12847
12848     @Override
12849     public void deletePackage(final String packageName,
12850             final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12851         mContext.enforceCallingOrSelfPermission(
12852                 android.Manifest.permission.DELETE_PACKAGES, null);
12853         Preconditions.checkNotNull(packageName);
12854         Preconditions.checkNotNull(observer);
12855         final int uid = Binder.getCallingUid();
12856         if (UserHandle.getUserId(uid) != userId) {
12857             mContext.enforceCallingPermission(
12858                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12859                     "deletePackage for user " + userId);
12860         }
12861         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12862             try {
12863                 observer.onPackageDeleted(packageName,
12864                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12865             } catch (RemoteException re) {
12866             }
12867             return;
12868         }
12869
12870         boolean uninstallBlocked = false;
12871         if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12872             int[] users = sUserManager.getUserIds();
12873             for (int i = 0; i < users.length; ++i) {
12874                 if (getBlockUninstallForUser(packageName, users[i])) {
12875                     uninstallBlocked = true;
12876                     break;
12877                 }
12878             }
12879         } else {
12880             uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12881         }
12882         if (uninstallBlocked) {
12883             try {
12884                 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12885                         null);
12886             } catch (RemoteException re) {
12887             }
12888             return;
12889         }
12890
12891         if (DEBUG_REMOVE) {
12892             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12893         }
12894         // Queue up an async operation since the package deletion may take a little while.
12895         mHandler.post(new Runnable() {
12896             public void run() {
12897                 mHandler.removeCallbacks(this);
12898                 final int returnCode = deletePackageX(packageName, userId, flags);
12899                 if (observer != null) {
12900                     try {
12901                         observer.onPackageDeleted(packageName, returnCode, null);
12902                     } catch (RemoteException e) {
12903                         Log.i(TAG, "Observer no longer exists.");
12904                     } //end catch
12905                 } //end if
12906             } //end run
12907         });
12908     }
12909
12910     private boolean isPackageDeviceAdmin(String packageName, int userId) {
12911         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12912                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12913         try {
12914             if (dpm != null) {
12915                 if (dpm.isDeviceOwner(packageName)) {
12916                     return true;
12917                 }
12918                 int[] users;
12919                 if (userId == UserHandle.USER_ALL) {
12920                     users = sUserManager.getUserIds();
12921                 } else {
12922                     users = new int[]{userId};
12923                 }
12924                 for (int i = 0; i < users.length; ++i) {
12925                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12926                         return true;
12927                     }
12928                 }
12929             }
12930         } catch (RemoteException e) {
12931         }
12932         return false;
12933     }
12934
12935     /**
12936      *  This method is an internal method that could be get invoked either
12937      *  to delete an installed package or to clean up a failed installation.
12938      *  After deleting an installed package, a broadcast is sent to notify any
12939      *  listeners that the package has been installed. For cleaning up a failed
12940      *  installation, the broadcast is not necessary since the package's
12941      *  installation wouldn't have sent the initial broadcast either
12942      *  The key steps in deleting a package are
12943      *  deleting the package information in internal structures like mPackages,
12944      *  deleting the packages base directories through installd
12945      *  updating mSettings to reflect current status
12946      *  persisting settings for later use
12947      *  sending a broadcast if necessary
12948      */
12949     private int deletePackageX(String packageName, int userId, int flags) {
12950         final PackageRemovedInfo info = new PackageRemovedInfo();
12951         final boolean res;
12952
12953         final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12954                 ? UserHandle.ALL : new UserHandle(userId);
12955
12956         if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12957             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12958             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12959         }
12960
12961         boolean removedForAllUsers = false;
12962         boolean systemUpdate = false;
12963
12964         // for the uninstall-updates case and restricted profiles, remember the per-
12965         // userhandle installed state
12966         int[] allUsers;
12967         boolean[] perUserInstalled;
12968         synchronized (mPackages) {
12969             PackageSetting ps = mSettings.mPackages.get(packageName);
12970             allUsers = sUserManager.getUserIds();
12971             perUserInstalled = new boolean[allUsers.length];
12972             for (int i = 0; i < allUsers.length; i++) {
12973                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12974             }
12975         }
12976
12977         synchronized (mInstallLock) {
12978             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12979             res = deletePackageLI(packageName, removeForUser,
12980                     true, allUsers, perUserInstalled,
12981                     flags | REMOVE_CHATTY, info, true);
12982             systemUpdate = info.isRemovedPackageSystemUpdate;
12983             if (res && !systemUpdate && mPackages.get(packageName) == null) {
12984                 removedForAllUsers = true;
12985             }
12986             if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12987                     + " removedForAllUsers=" + removedForAllUsers);
12988         }
12989
12990         if (res) {
12991             info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12992
12993             // If the removed package was a system update, the old system package
12994             // was re-enabled; we need to broadcast this information
12995             if (systemUpdate) {
12996                 Bundle extras = new Bundle(1);
12997                 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12998                         ? info.removedAppId : info.uid);
12999                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
13000
13001                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13002                         extras, null, null, null);
13003                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13004                         extras, null, null, null);
13005                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13006                         null, packageName, null, null);
13007             }
13008         }
13009         // Force a gc here.
13010         Runtime.getRuntime().gc();
13011         // Delete the resources here after sending the broadcast to let
13012         // other processes clean up before deleting resources.
13013         if (info.args != null) {
13014             synchronized (mInstallLock) {
13015                 info.args.doPostDeleteLI(true);
13016             }
13017         }
13018
13019         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13020     }
13021
13022     class PackageRemovedInfo {
13023         String removedPackage;
13024         int uid = -1;
13025         int removedAppId = -1;
13026         int[] removedUsers = null;
13027         boolean isRemovedPackageSystemUpdate = false;
13028         // Clean up resources deleted packages.
13029         InstallArgs args = null;
13030
13031         void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13032             Bundle extras = new Bundle(1);
13033             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13034             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13035             if (replacing) {
13036                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
13037             }
13038             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13039             if (removedPackage != null) {
13040                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13041                         extras, null, null, removedUsers);
13042                 if (fullRemove && !replacing) {
13043                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13044                             extras, null, null, removedUsers);
13045                 }
13046             }
13047             if (removedAppId >= 0) {
13048                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13049                         removedUsers);
13050             }
13051         }
13052     }
13053
13054     /*
13055      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13056      * flag is not set, the data directory is removed as well.
13057      * make sure this flag is set for partially installed apps. If not its meaningless to
13058      * delete a partially installed application.
13059      */
13060     private void removePackageDataLI(PackageSetting ps,
13061             int[] allUserHandles, boolean[] perUserInstalled,
13062             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13063         String packageName = ps.name;
13064         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13065         removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13066         // Retrieve object to delete permissions for shared user later on
13067         final PackageSetting deletedPs;
13068         // reader
13069         synchronized (mPackages) {
13070             deletedPs = mSettings.mPackages.get(packageName);
13071             if (outInfo != null) {
13072                 outInfo.removedPackage = packageName;
13073                 outInfo.removedUsers = deletedPs != null
13074                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13075                         : null;
13076             }
13077         }
13078         if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13079             removeDataDirsLI(ps.volumeUuid, packageName);
13080             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13081         }
13082         // writer
13083         synchronized (mPackages) {
13084             if (deletedPs != null) {
13085                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13086                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13087                     clearDefaultBrowserIfNeeded(packageName);
13088                     if (outInfo != null) {
13089                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13090                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13091                     }
13092                     updatePermissionsLPw(deletedPs.name, null, 0);
13093                     if (deletedPs.sharedUser != null) {
13094                         // Remove permissions associated with package. Since runtime
13095                         // permissions are per user we have to kill the removed package
13096                         // or packages running under the shared user of the removed
13097                         // package if revoking the permissions requested only by the removed
13098                         // package is successful and this causes a change in gids.
13099                         for (int userId : UserManagerService.getInstance().getUserIds()) {
13100                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13101                                     userId);
13102                             if (userIdToKill == UserHandle.USER_ALL
13103                                     || userIdToKill >= UserHandle.USER_OWNER) {
13104                                 // If gids changed for this user, kill all affected packages.
13105                                 mHandler.post(new Runnable() {
13106                                     @Override
13107                                     public void run() {
13108                                         // This has to happen with no lock held.
13109                                         killApplication(deletedPs.name, deletedPs.appId,
13110                                                 KILL_APP_REASON_GIDS_CHANGED);
13111                                     }
13112                                 });
13113                                 break;
13114                             }
13115                         }
13116                     }
13117                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13118                 }
13119                 // make sure to preserve per-user disabled state if this removal was just
13120                 // a downgrade of a system app to the factory package
13121                 if (allUserHandles != null && perUserInstalled != null) {
13122                     if (DEBUG_REMOVE) {
13123                         Slog.d(TAG, "Propagating install state across downgrade");
13124                     }
13125                     for (int i = 0; i < allUserHandles.length; i++) {
13126                         if (DEBUG_REMOVE) {
13127                             Slog.d(TAG, "    user " + allUserHandles[i]
13128                                     + " => " + perUserInstalled[i]);
13129                         }
13130                         ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13131                     }
13132                 }
13133             }
13134             // can downgrade to reader
13135             if (writeSettings) {
13136                 // Save settings now
13137                 mSettings.writeLPr();
13138             }
13139         }
13140         if (outInfo != null) {
13141             // A user ID was deleted here. Go through all users and remove it
13142             // from KeyStore.
13143             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13144         }
13145     }
13146
13147     static boolean locationIsPrivileged(File path) {
13148         try {
13149             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13150                     .getCanonicalPath();
13151             return path.getCanonicalPath().startsWith(privilegedAppDir);
13152         } catch (IOException e) {
13153             Slog.e(TAG, "Unable to access code path " + path);
13154         }
13155         return false;
13156     }
13157
13158     /*
13159      * Tries to delete system package.
13160      */
13161     private boolean deleteSystemPackageLI(PackageSetting newPs,
13162             int[] allUserHandles, boolean[] perUserInstalled,
13163             int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13164         final boolean applyUserRestrictions
13165                 = (allUserHandles != null) && (perUserInstalled != null);
13166         PackageSetting disabledPs = null;
13167         // Confirm if the system package has been updated
13168         // An updated system app can be deleted. This will also have to restore
13169         // the system pkg from system partition
13170         // reader
13171         synchronized (mPackages) {
13172             disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13173         }
13174         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13175                 + " disabledPs=" + disabledPs);
13176         if (disabledPs == null) {
13177             Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13178             return false;
13179         } else if (DEBUG_REMOVE) {
13180             Slog.d(TAG, "Deleting system pkg from data partition");
13181         }
13182         if (DEBUG_REMOVE) {
13183             if (applyUserRestrictions) {
13184                 Slog.d(TAG, "Remembering install states:");
13185                 for (int i = 0; i < allUserHandles.length; i++) {
13186                     Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13187                 }
13188             }
13189         }
13190         // Delete the updated package
13191         outInfo.isRemovedPackageSystemUpdate = true;
13192         if (disabledPs.versionCode < newPs.versionCode) {
13193             // Delete data for downgrades
13194             flags &= ~PackageManager.DELETE_KEEP_DATA;
13195         } else {
13196             // Preserve data by setting flag
13197             flags |= PackageManager.DELETE_KEEP_DATA;
13198         }
13199         boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13200                 allUserHandles, perUserInstalled, outInfo, writeSettings);
13201         if (!ret) {
13202             return false;
13203         }
13204         // writer
13205         synchronized (mPackages) {
13206             // Reinstate the old system package
13207             mSettings.enableSystemPackageLPw(newPs.name);
13208             // Remove any native libraries from the upgraded package.
13209             NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13210         }
13211         // Install the system package
13212         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13213         int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13214         if (locationIsPrivileged(disabledPs.codePath)) {
13215             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13216         }
13217
13218         final PackageParser.Package newPkg;
13219         try {
13220             newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13221         } catch (PackageManagerException e) {
13222             Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13223             return false;
13224         }
13225
13226         // writer
13227         synchronized (mPackages) {
13228             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13229
13230             // Propagate the permissions state as we do not want to drop on the floor
13231             // runtime permissions. The update permissions method below will take
13232             // care of removing obsolete permissions and grant install permissions.
13233             ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13234             updatePermissionsLPw(newPkg.packageName, newPkg,
13235                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13236
13237             if (applyUserRestrictions) {
13238                 if (DEBUG_REMOVE) {
13239                     Slog.d(TAG, "Propagating install state across reinstall");
13240                 }
13241                 for (int i = 0; i < allUserHandles.length; i++) {
13242                     if (DEBUG_REMOVE) {
13243                         Slog.d(TAG, "    user " + allUserHandles[i]
13244                                 + " => " + perUserInstalled[i]);
13245                     }
13246                     ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13247
13248                     mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13249                 }
13250                 // Regardless of writeSettings we need to ensure that this restriction
13251                 // state propagation is persisted
13252                 mSettings.writeAllUsersPackageRestrictionsLPr();
13253             }
13254             // can downgrade to reader here
13255             if (writeSettings) {
13256                 mSettings.writeLPr();
13257             }
13258         }
13259         return true;
13260     }
13261
13262     private boolean deleteInstalledPackageLI(PackageSetting ps,
13263             boolean deleteCodeAndResources, int flags,
13264             int[] allUserHandles, boolean[] perUserInstalled,
13265             PackageRemovedInfo outInfo, boolean writeSettings) {
13266         if (outInfo != null) {
13267             outInfo.uid = ps.appId;
13268         }
13269
13270         // Delete package data from internal structures and also remove data if flag is set
13271         removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13272
13273         // Delete application code and resources
13274         if (deleteCodeAndResources && (outInfo != null)) {
13275             outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13276                     ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13277             if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13278         }
13279         return true;
13280     }
13281
13282     @Override
13283     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13284             int userId) {
13285         mContext.enforceCallingOrSelfPermission(
13286                 android.Manifest.permission.DELETE_PACKAGES, null);
13287         synchronized (mPackages) {
13288             PackageSetting ps = mSettings.mPackages.get(packageName);
13289             if (ps == null) {
13290                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13291                 return false;
13292             }
13293             if (!ps.getInstalled(userId)) {
13294                 // Can't block uninstall for an app that is not installed or enabled.
13295                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13296                 return false;
13297             }
13298             ps.setBlockUninstall(blockUninstall, userId);
13299             mSettings.writePackageRestrictionsLPr(userId);
13300         }
13301         return true;
13302     }
13303
13304     @Override
13305     public boolean getBlockUninstallForUser(String packageName, int userId) {
13306         synchronized (mPackages) {
13307             PackageSetting ps = mSettings.mPackages.get(packageName);
13308             if (ps == null) {
13309                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13310                 return false;
13311             }
13312             return ps.getBlockUninstall(userId);
13313         }
13314     }
13315
13316     /*
13317      * This method handles package deletion in general
13318      */
13319     private boolean deletePackageLI(String packageName, UserHandle user,
13320             boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13321             int flags, PackageRemovedInfo outInfo,
13322             boolean writeSettings) {
13323         if (packageName == null) {
13324             Slog.w(TAG, "Attempt to delete null packageName.");
13325             return false;
13326         }
13327         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13328         PackageSetting ps;
13329         boolean dataOnly = false;
13330         int removeUser = -1;
13331         int appId = -1;
13332         synchronized (mPackages) {
13333             ps = mSettings.mPackages.get(packageName);
13334             if (ps == null) {
13335                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13336                 return false;
13337             }
13338             if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13339                     && user.getIdentifier() != UserHandle.USER_ALL) {
13340                 // The caller is asking that the package only be deleted for a single
13341                 // user.  To do this, we just mark its uninstalled state and delete
13342                 // its data.  If this is a system app, we only allow this to happen if
13343                 // they have set the special DELETE_SYSTEM_APP which requests different
13344                 // semantics than normal for uninstalling system apps.
13345                 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13346                 final int userId = user.getIdentifier();
13347                 ps.setUserState(userId,
13348                         COMPONENT_ENABLED_STATE_DEFAULT,
13349                         false, //installed
13350                         true,  //stopped
13351                         true,  //notLaunched
13352                         false, //hidden
13353                         null, null, null,
13354                         false, // blockUninstall
13355                         ps.readUserState(userId).domainVerificationStatus, 0);
13356                 if (!isSystemApp(ps)) {
13357                     if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13358                         // Other user still have this package installed, so all
13359                         // we need to do is clear this user's data and save that
13360                         // it is uninstalled.
13361                         if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13362                         removeUser = user.getIdentifier();
13363                         appId = ps.appId;
13364                         scheduleWritePackageRestrictionsLocked(removeUser);
13365                     } else {
13366                         // We need to set it back to 'installed' so the uninstall
13367                         // broadcasts will be sent correctly.
13368                         if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13369                         ps.setInstalled(true, user.getIdentifier());
13370                     }
13371                 } else {
13372                     // This is a system app, so we assume that the
13373                     // other users still have this package installed, so all
13374                     // we need to do is clear this user's data and save that
13375                     // it is uninstalled.
13376                     if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13377                     removeUser = user.getIdentifier();
13378                     appId = ps.appId;
13379                     scheduleWritePackageRestrictionsLocked(removeUser);
13380                 }
13381             }
13382         }
13383
13384         if (removeUser >= 0) {
13385             // From above, we determined that we are deleting this only
13386             // for a single user.  Continue the work here.
13387             if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13388             if (outInfo != null) {
13389                 outInfo.removedPackage = packageName;
13390                 outInfo.removedAppId = appId;
13391                 outInfo.removedUsers = new int[] {removeUser};
13392             }
13393             mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13394             removeKeystoreDataIfNeeded(removeUser, appId);
13395             schedulePackageCleaning(packageName, removeUser, false);
13396             synchronized (mPackages) {
13397                 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13398                     scheduleWritePackageRestrictionsLocked(removeUser);
13399                 }
13400                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13401             }
13402             return true;
13403         }
13404
13405         if (dataOnly) {
13406             // Delete application data first
13407             if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13408             removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13409             return true;
13410         }
13411
13412         boolean ret = false;
13413         if (isSystemApp(ps)) {
13414             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13415             // When an updated system application is deleted we delete the existing resources as well and
13416             // fall back to existing code in system partition
13417             ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13418                     flags, outInfo, writeSettings);
13419         } else {
13420             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13421             // Kill application pre-emptively especially for apps on sd.
13422             killApplication(packageName, ps.appId, "uninstall pkg");
13423             ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13424                     allUserHandles, perUserInstalled,
13425                     outInfo, writeSettings);
13426         }
13427
13428         return ret;
13429     }
13430
13431     private final class ClearStorageConnection implements ServiceConnection {
13432         IMediaContainerService mContainerService;
13433
13434         @Override
13435         public void onServiceConnected(ComponentName name, IBinder service) {
13436             synchronized (this) {
13437                 mContainerService = IMediaContainerService.Stub.asInterface(service);
13438                 notifyAll();
13439             }
13440         }
13441
13442         @Override
13443         public void onServiceDisconnected(ComponentName name) {
13444         }
13445     }
13446
13447     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13448         final boolean mounted;
13449         if (Environment.isExternalStorageEmulated()) {
13450             mounted = true;
13451         } else {
13452             final String status = Environment.getExternalStorageState();
13453
13454             mounted = status.equals(Environment.MEDIA_MOUNTED)
13455                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13456         }
13457
13458         if (!mounted) {
13459             return;
13460         }
13461
13462         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13463         int[] users;
13464         if (userId == UserHandle.USER_ALL) {
13465             users = sUserManager.getUserIds();
13466         } else {
13467             users = new int[] { userId };
13468         }
13469         final ClearStorageConnection conn = new ClearStorageConnection();
13470         if (mContext.bindServiceAsUser(
13471                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13472             try {
13473                 for (int curUser : users) {
13474                     long timeout = SystemClock.uptimeMillis() + 5000;
13475                     synchronized (conn) {
13476                         long now = SystemClock.uptimeMillis();
13477                         while (conn.mContainerService == null && now < timeout) {
13478                             try {
13479                                 conn.wait(timeout - now);
13480                             } catch (InterruptedException e) {
13481                             }
13482                         }
13483                     }
13484                     if (conn.mContainerService == null) {
13485                         return;
13486                     }
13487
13488                     final UserEnvironment userEnv = new UserEnvironment(curUser);
13489                     clearDirectory(conn.mContainerService,
13490                             userEnv.buildExternalStorageAppCacheDirs(packageName));
13491                     if (allData) {
13492                         clearDirectory(conn.mContainerService,
13493                                 userEnv.buildExternalStorageAppDataDirs(packageName));
13494                         clearDirectory(conn.mContainerService,
13495                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
13496                     }
13497                 }
13498             } finally {
13499                 mContext.unbindService(conn);
13500             }
13501         }
13502     }
13503
13504     @Override
13505     public void clearApplicationUserData(final String packageName,
13506             final IPackageDataObserver observer, final int userId) {
13507         mContext.enforceCallingOrSelfPermission(
13508                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13509         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13510         // Queue up an async operation since the package deletion may take a little while.
13511         mHandler.post(new Runnable() {
13512             public void run() {
13513                 mHandler.removeCallbacks(this);
13514                 final boolean succeeded;
13515                 synchronized (mInstallLock) {
13516                     succeeded = clearApplicationUserDataLI(packageName, userId);
13517                 }
13518                 clearExternalStorageDataSync(packageName, userId, true);
13519                 if (succeeded) {
13520                     // invoke DeviceStorageMonitor's update method to clear any notifications
13521                     DeviceStorageMonitorInternal
13522                             dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13523                     if (dsm != null) {
13524                         dsm.checkMemory();
13525                     }
13526                 }
13527                 if(observer != null) {
13528                     try {
13529                         observer.onRemoveCompleted(packageName, succeeded);
13530                     } catch (RemoteException e) {
13531                         Log.i(TAG, "Observer no longer exists.");
13532                     }
13533                 } //end if observer
13534             } //end run
13535         });
13536     }
13537
13538     private boolean clearApplicationUserDataLI(String packageName, int userId) {
13539         if (packageName == null) {
13540             Slog.w(TAG, "Attempt to delete null packageName.");
13541             return false;
13542         }
13543
13544         // Try finding details about the requested package
13545         PackageParser.Package pkg;
13546         synchronized (mPackages) {
13547             pkg = mPackages.get(packageName);
13548             if (pkg == null) {
13549                 final PackageSetting ps = mSettings.mPackages.get(packageName);
13550                 if (ps != null) {
13551                     pkg = ps.pkg;
13552                 }
13553             }
13554
13555             if (pkg == null) {
13556                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13557                 return false;
13558             }
13559
13560             PackageSetting ps = (PackageSetting) pkg.mExtras;
13561             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13562         }
13563
13564         // Always delete data directories for package, even if we found no other
13565         // record of app. This helps users recover from UID mismatches without
13566         // resorting to a full data wipe.
13567         int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13568         if (retCode < 0) {
13569             Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13570             return false;
13571         }
13572
13573         final int appId = pkg.applicationInfo.uid;
13574         removeKeystoreDataIfNeeded(userId, appId);
13575
13576         // Create a native library symlink only if we have native libraries
13577         // and if the native libraries are 32 bit libraries. We do not provide
13578         // this symlink for 64 bit libraries.
13579         if (pkg.applicationInfo.primaryCpuAbi != null &&
13580                 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13581             final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13582             if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13583                     nativeLibPath, userId) < 0) {
13584                 Slog.w(TAG, "Failed linking native library dir");
13585                 return false;
13586             }
13587         }
13588
13589         return true;
13590     }
13591
13592     /**
13593      * Reverts user permission state changes (permissions and flags) in
13594      * all packages for a given user.
13595      *
13596      * @param userId The device user for which to do a reset.
13597      */
13598     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13599         final int packageCount = mPackages.size();
13600         for (int i = 0; i < packageCount; i++) {
13601             PackageParser.Package pkg = mPackages.valueAt(i);
13602             PackageSetting ps = (PackageSetting) pkg.mExtras;
13603             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13604         }
13605     }
13606
13607     /**
13608      * Reverts user permission state changes (permissions and flags).
13609      *
13610      * @param ps The package for which to reset.
13611      * @param userId The device user for which to do a reset.
13612      */
13613     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13614             final PackageSetting ps, final int userId) {
13615         if (ps.pkg == null) {
13616             return;
13617         }
13618
13619         final int userSettableFlags = FLAG_PERMISSION_USER_SET
13620                 | FLAG_PERMISSION_USER_FIXED
13621                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13622
13623         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13624                 | FLAG_PERMISSION_POLICY_FIXED;
13625
13626         boolean writeInstallPermissions = false;
13627         boolean writeRuntimePermissions = false;
13628
13629         final int permissionCount = ps.pkg.requestedPermissions.size();
13630         for (int i = 0; i < permissionCount; i++) {
13631             String permission = ps.pkg.requestedPermissions.get(i);
13632
13633             BasePermission bp = mSettings.mPermissions.get(permission);
13634             if (bp == null) {
13635                 continue;
13636             }
13637
13638             // If shared user we just reset the state to which only this app contributed.
13639             if (ps.sharedUser != null) {
13640                 boolean used = false;
13641                 final int packageCount = ps.sharedUser.packages.size();
13642                 for (int j = 0; j < packageCount; j++) {
13643                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13644                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13645                             && pkg.pkg.requestedPermissions.contains(permission)) {
13646                         used = true;
13647                         break;
13648                     }
13649                 }
13650                 if (used) {
13651                     continue;
13652                 }
13653             }
13654
13655             PermissionsState permissionsState = ps.getPermissionsState();
13656
13657             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13658
13659             // Always clear the user settable flags.
13660             final boolean hasInstallState = permissionsState.getInstallPermissionState(
13661                     bp.name) != null;
13662             if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13663                 if (hasInstallState) {
13664                     writeInstallPermissions = true;
13665                 } else {
13666                     writeRuntimePermissions = true;
13667                 }
13668             }
13669
13670             // Below is only runtime permission handling.
13671             if (!bp.isRuntime()) {
13672                 continue;
13673             }
13674
13675             // Never clobber system or policy.
13676             if ((oldFlags & policyOrSystemFlags) != 0) {
13677                 continue;
13678             }
13679
13680             // If this permission was granted by default, make sure it is.
13681             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13682                 if (permissionsState.grantRuntimePermission(bp, userId)
13683                         != PERMISSION_OPERATION_FAILURE) {
13684                     writeRuntimePermissions = true;
13685                 }
13686             } else {
13687                 // Otherwise, reset the permission.
13688                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13689                 switch (revokeResult) {
13690                     case PERMISSION_OPERATION_SUCCESS: {
13691                         writeRuntimePermissions = true;
13692                     } break;
13693
13694                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13695                         writeRuntimePermissions = true;
13696                         final int appId = ps.appId;
13697                         mHandler.post(new Runnable() {
13698                             @Override
13699                             public void run() {
13700                                 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13701                             }
13702                         });
13703                     } break;
13704                 }
13705             }
13706         }
13707
13708         // Synchronously write as we are taking permissions away.
13709         if (writeRuntimePermissions) {
13710             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13711         }
13712
13713         // Synchronously write as we are taking permissions away.
13714         if (writeInstallPermissions) {
13715             mSettings.writeLPr();
13716         }
13717     }
13718
13719     /**
13720      * Remove entries from the keystore daemon. Will only remove it if the
13721      * {@code appId} is valid.
13722      */
13723     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13724         if (appId < 0) {
13725             return;
13726         }
13727
13728         final KeyStore keyStore = KeyStore.getInstance();
13729         if (keyStore != null) {
13730             if (userId == UserHandle.USER_ALL) {
13731                 for (final int individual : sUserManager.getUserIds()) {
13732                     keyStore.clearUid(UserHandle.getUid(individual, appId));
13733                 }
13734             } else {
13735                 keyStore.clearUid(UserHandle.getUid(userId, appId));
13736             }
13737         } else {
13738             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13739         }
13740     }
13741
13742     @Override
13743     public void deleteApplicationCacheFiles(final String packageName,
13744             final IPackageDataObserver observer) {
13745         mContext.enforceCallingOrSelfPermission(
13746                 android.Manifest.permission.DELETE_CACHE_FILES, null);
13747         // Queue up an async operation since the package deletion may take a little while.
13748         final int userId = UserHandle.getCallingUserId();
13749         mHandler.post(new Runnable() {
13750             public void run() {
13751                 mHandler.removeCallbacks(this);
13752                 final boolean succeded;
13753                 synchronized (mInstallLock) {
13754                     succeded = deleteApplicationCacheFilesLI(packageName, userId);
13755                 }
13756                 clearExternalStorageDataSync(packageName, userId, false);
13757                 if (observer != null) {
13758                     try {
13759                         observer.onRemoveCompleted(packageName, succeded);
13760                     } catch (RemoteException e) {
13761                         Log.i(TAG, "Observer no longer exists.");
13762                     }
13763                 } //end if observer
13764             } //end run
13765         });
13766     }
13767
13768     private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13769         if (packageName == null) {
13770             Slog.w(TAG, "Attempt to delete null packageName.");
13771             return false;
13772         }
13773         PackageParser.Package p;
13774         synchronized (mPackages) {
13775             p = mPackages.get(packageName);
13776         }
13777         if (p == null) {
13778             Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13779             return false;
13780         }
13781         final ApplicationInfo applicationInfo = p.applicationInfo;
13782         if (applicationInfo == null) {
13783             Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13784             return false;
13785         }
13786         int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13787         if (retCode < 0) {
13788             Slog.w(TAG, "Couldn't remove cache files for package: "
13789                        + packageName + " u" + userId);
13790             return false;
13791         }
13792         return true;
13793     }
13794
13795     @Override
13796     public void getPackageSizeInfo(final String packageName, int userHandle,
13797             final IPackageStatsObserver observer) {
13798         mContext.enforceCallingOrSelfPermission(
13799                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
13800         if (packageName == null) {
13801             throw new IllegalArgumentException("Attempt to get size of null packageName");
13802         }
13803
13804         PackageStats stats = new PackageStats(packageName, userHandle);
13805
13806         /*
13807          * Queue up an async operation since the package measurement may take a
13808          * little while.
13809          */
13810         Message msg = mHandler.obtainMessage(INIT_COPY);
13811         msg.obj = new MeasureParams(stats, observer);
13812         mHandler.sendMessage(msg);
13813     }
13814
13815     private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13816             PackageStats pStats) {
13817         if (packageName == null) {
13818             Slog.w(TAG, "Attempt to get size of null packageName.");
13819             return false;
13820         }
13821         PackageParser.Package p;
13822         boolean dataOnly = false;
13823         String libDirRoot = null;
13824         String asecPath = null;
13825         PackageSetting ps = null;
13826         synchronized (mPackages) {
13827             p = mPackages.get(packageName);
13828             ps = mSettings.mPackages.get(packageName);
13829             if(p == null) {
13830                 dataOnly = true;
13831                 if((ps == null) || (ps.pkg == null)) {
13832                     Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13833                     return false;
13834                 }
13835                 p = ps.pkg;
13836             }
13837             if (ps != null) {
13838                 libDirRoot = ps.legacyNativeLibraryPathString;
13839             }
13840             if (p != null && (isExternal(p) || p.isForwardLocked())) {
13841                 final long token = Binder.clearCallingIdentity();
13842                 try {
13843                     String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13844                     if (secureContainerId != null) {
13845                         asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13846                     }
13847                 } finally {
13848                     Binder.restoreCallingIdentity(token);
13849                 }
13850             }
13851         }
13852         String publicSrcDir = null;
13853         if(!dataOnly) {
13854             final ApplicationInfo applicationInfo = p.applicationInfo;
13855             if (applicationInfo == null) {
13856                 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13857                 return false;
13858             }
13859             if (p.isForwardLocked()) {
13860                 publicSrcDir = applicationInfo.getBaseResourcePath();
13861             }
13862         }
13863         // TODO: extend to measure size of split APKs
13864         // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13865         // not just the first level.
13866         // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13867         // just the primary.
13868         String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13869         int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13870                 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13871         if (res < 0) {
13872             return false;
13873         }
13874
13875         // Fix-up for forward-locked applications in ASEC containers.
13876         if (!isExternal(p)) {
13877             pStats.codeSize += pStats.externalCodeSize;
13878             pStats.externalCodeSize = 0L;
13879         }
13880
13881         return true;
13882     }
13883
13884
13885     @Override
13886     public void addPackageToPreferred(String packageName) {
13887         Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13888     }
13889
13890     @Override
13891     public void removePackageFromPreferred(String packageName) {
13892         Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13893     }
13894
13895     @Override
13896     public List<PackageInfo> getPreferredPackages(int flags) {
13897         return new ArrayList<PackageInfo>();
13898     }
13899
13900     private int getUidTargetSdkVersionLockedLPr(int uid) {
13901         Object obj = mSettings.getUserIdLPr(uid);
13902         if (obj instanceof SharedUserSetting) {
13903             final SharedUserSetting sus = (SharedUserSetting) obj;
13904             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13905             final Iterator<PackageSetting> it = sus.packages.iterator();
13906             while (it.hasNext()) {
13907                 final PackageSetting ps = it.next();
13908                 if (ps.pkg != null) {
13909                     int v = ps.pkg.applicationInfo.targetSdkVersion;
13910                     if (v < vers) vers = v;
13911                 }
13912             }
13913             return vers;
13914         } else if (obj instanceof PackageSetting) {
13915             final PackageSetting ps = (PackageSetting) obj;
13916             if (ps.pkg != null) {
13917                 return ps.pkg.applicationInfo.targetSdkVersion;
13918             }
13919         }
13920         return Build.VERSION_CODES.CUR_DEVELOPMENT;
13921     }
13922
13923     @Override
13924     public void addPreferredActivity(IntentFilter filter, int match,
13925             ComponentName[] set, ComponentName activity, int userId) {
13926         addPreferredActivityInternal(filter, match, set, activity, true, userId,
13927                 "Adding preferred");
13928     }
13929
13930     private void addPreferredActivityInternal(IntentFilter filter, int match,
13931             ComponentName[] set, ComponentName activity, boolean always, int userId,
13932             String opname) {
13933         // writer
13934         int callingUid = Binder.getCallingUid();
13935         enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13936         if (filter.countActions() == 0) {
13937             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13938             return;
13939         }
13940         synchronized (mPackages) {
13941             if (mContext.checkCallingOrSelfPermission(
13942                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13943                     != PackageManager.PERMISSION_GRANTED) {
13944                 if (getUidTargetSdkVersionLockedLPr(callingUid)
13945                         < Build.VERSION_CODES.FROYO) {
13946                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13947                             + callingUid);
13948                     return;
13949                 }
13950                 mContext.enforceCallingOrSelfPermission(
13951                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13952             }
13953
13954             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13955             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13956                     + userId + ":");
13957             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13958             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13959             scheduleWritePackageRestrictionsLocked(userId);
13960         }
13961     }
13962
13963     @Override
13964     public void replacePreferredActivity(IntentFilter filter, int match,
13965             ComponentName[] set, ComponentName activity, int userId) {
13966         if (filter.countActions() != 1) {
13967             throw new IllegalArgumentException(
13968                     "replacePreferredActivity expects filter to have only 1 action.");
13969         }
13970         if (filter.countDataAuthorities() != 0
13971                 || filter.countDataPaths() != 0
13972                 || filter.countDataSchemes() > 1
13973                 || filter.countDataTypes() != 0) {
13974             throw new IllegalArgumentException(
13975                     "replacePreferredActivity expects filter to have no data authorities, " +
13976                     "paths, or types; and at most one scheme.");
13977         }
13978
13979         final int callingUid = Binder.getCallingUid();
13980         enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13981         synchronized (mPackages) {
13982             if (mContext.checkCallingOrSelfPermission(
13983                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13984                     != PackageManager.PERMISSION_GRANTED) {
13985                 if (getUidTargetSdkVersionLockedLPr(callingUid)
13986                         < Build.VERSION_CODES.FROYO) {
13987                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13988                             + Binder.getCallingUid());
13989                     return;
13990                 }
13991                 mContext.enforceCallingOrSelfPermission(
13992                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13993             }
13994
13995             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13996             if (pir != null) {
13997                 // Get all of the existing entries that exactly match this filter.
13998                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13999                 if (existing != null && existing.size() == 1) {
14000                     PreferredActivity cur = existing.get(0);
14001                     if (DEBUG_PREFERRED) {
14002                         Slog.i(TAG, "Checking replace of preferred:");
14003                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14004                         if (!cur.mPref.mAlways) {
14005                             Slog.i(TAG, "  -- CUR; not mAlways!");
14006                         } else {
14007                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14008                             Slog.i(TAG, "  -- CUR: mSet="
14009                                     + Arrays.toString(cur.mPref.mSetComponents));
14010                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14011                             Slog.i(TAG, "  -- NEW: mMatch="
14012                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
14013                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14014                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14015                         }
14016                     }
14017                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14018                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14019                             && cur.mPref.sameSet(set)) {
14020                         // Setting the preferred activity to what it happens to be already
14021                         if (DEBUG_PREFERRED) {
14022                             Slog.i(TAG, "Replacing with same preferred activity "
14023                                     + cur.mPref.mShortComponent + " for user "
14024                                     + userId + ":");
14025                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14026                         }
14027                         return;
14028                     }
14029                 }
14030
14031                 if (existing != null) {
14032                     if (DEBUG_PREFERRED) {
14033                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
14034                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14035                     }
14036                     for (int i = 0; i < existing.size(); i++) {
14037                         PreferredActivity pa = existing.get(i);
14038                         if (DEBUG_PREFERRED) {
14039                             Slog.i(TAG, "Removing existing preferred activity "
14040                                     + pa.mPref.mComponent + ":");
14041                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14042                         }
14043                         pir.removeFilter(pa);
14044                     }
14045                 }
14046             }
14047             addPreferredActivityInternal(filter, match, set, activity, true, userId,
14048                     "Replacing preferred");
14049         }
14050     }
14051
14052     @Override
14053     public void clearPackagePreferredActivities(String packageName) {
14054         final int uid = Binder.getCallingUid();
14055         // writer
14056         synchronized (mPackages) {
14057             PackageParser.Package pkg = mPackages.get(packageName);
14058             if (pkg == null || pkg.applicationInfo.uid != uid) {
14059                 if (mContext.checkCallingOrSelfPermission(
14060                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14061                         != PackageManager.PERMISSION_GRANTED) {
14062                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14063                             < Build.VERSION_CODES.FROYO) {
14064                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14065                                 + Binder.getCallingUid());
14066                         return;
14067                     }
14068                     mContext.enforceCallingOrSelfPermission(
14069                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14070                 }
14071             }
14072
14073             int user = UserHandle.getCallingUserId();
14074             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14075                 scheduleWritePackageRestrictionsLocked(user);
14076             }
14077         }
14078     }
14079
14080     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14081     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14082         ArrayList<PreferredActivity> removed = null;
14083         boolean changed = false;
14084         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14085             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14086             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14087             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14088                 continue;
14089             }
14090             Iterator<PreferredActivity> it = pir.filterIterator();
14091             while (it.hasNext()) {
14092                 PreferredActivity pa = it.next();
14093                 // Mark entry for removal only if it matches the package name
14094                 // and the entry is of type "always".
14095                 if (packageName == null ||
14096                         (pa.mPref.mComponent.getPackageName().equals(packageName)
14097                                 && pa.mPref.mAlways)) {
14098                     if (removed == null) {
14099                         removed = new ArrayList<PreferredActivity>();
14100                     }
14101                     removed.add(pa);
14102                 }
14103             }
14104             if (removed != null) {
14105                 for (int j=0; j<removed.size(); j++) {
14106                     PreferredActivity pa = removed.get(j);
14107                     pir.removeFilter(pa);
14108                 }
14109                 changed = true;
14110             }
14111         }
14112         return changed;
14113     }
14114
14115     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14116     private void clearIntentFilterVerificationsLPw(int userId) {
14117         final int packageCount = mPackages.size();
14118         for (int i = 0; i < packageCount; i++) {
14119             PackageParser.Package pkg = mPackages.valueAt(i);
14120             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14121         }
14122     }
14123
14124     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14125     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14126         if (userId == UserHandle.USER_ALL) {
14127             if (mSettings.removeIntentFilterVerificationLPw(packageName,
14128                     sUserManager.getUserIds())) {
14129                 for (int oneUserId : sUserManager.getUserIds()) {
14130                     scheduleWritePackageRestrictionsLocked(oneUserId);
14131                 }
14132             }
14133         } else {
14134             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14135                 scheduleWritePackageRestrictionsLocked(userId);
14136             }
14137         }
14138     }
14139
14140     void clearDefaultBrowserIfNeeded(String packageName) {
14141         for (int oneUserId : sUserManager.getUserIds()) {
14142             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14143             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14144             if (packageName.equals(defaultBrowserPackageName)) {
14145                 setDefaultBrowserPackageName(null, oneUserId);
14146             }
14147         }
14148     }
14149
14150     @Override
14151     public void resetApplicationPreferences(int userId) {
14152         mContext.enforceCallingOrSelfPermission(
14153                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14154         // writer
14155         synchronized (mPackages) {
14156             final long identity = Binder.clearCallingIdentity();
14157             try {
14158                 clearPackagePreferredActivitiesLPw(null, userId);
14159                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
14160                 // TODO: We have to reset the default SMS and Phone. This requires
14161                 // significant refactoring to keep all default apps in the package
14162                 // manager (cleaner but more work) or have the services provide
14163                 // callbacks to the package manager to request a default app reset.
14164                 applyFactoryDefaultBrowserLPw(userId);
14165                 clearIntentFilterVerificationsLPw(userId);
14166                 primeDomainVerificationsLPw(userId);
14167                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14168                 scheduleWritePackageRestrictionsLocked(userId);
14169             } finally {
14170                 Binder.restoreCallingIdentity(identity);
14171             }
14172         }
14173     }
14174
14175     @Override
14176     public int getPreferredActivities(List<IntentFilter> outFilters,
14177             List<ComponentName> outActivities, String packageName) {
14178
14179         int num = 0;
14180         final int userId = UserHandle.getCallingUserId();
14181         // reader
14182         synchronized (mPackages) {
14183             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14184             if (pir != null) {
14185                 final Iterator<PreferredActivity> it = pir.filterIterator();
14186                 while (it.hasNext()) {
14187                     final PreferredActivity pa = it.next();
14188                     if (packageName == null
14189                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
14190                                     && pa.mPref.mAlways)) {
14191                         if (outFilters != null) {
14192                             outFilters.add(new IntentFilter(pa));
14193                         }
14194                         if (outActivities != null) {
14195                             outActivities.add(pa.mPref.mComponent);
14196                         }
14197                     }
14198                 }
14199             }
14200         }
14201
14202         return num;
14203     }
14204
14205     @Override
14206     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14207             int userId) {
14208         int callingUid = Binder.getCallingUid();
14209         if (callingUid != Process.SYSTEM_UID) {
14210             throw new SecurityException(
14211                     "addPersistentPreferredActivity can only be run by the system");
14212         }
14213         if (filter.countActions() == 0) {
14214             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14215             return;
14216         }
14217         synchronized (mPackages) {
14218             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14219                     " :");
14220             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14221             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14222                     new PersistentPreferredActivity(filter, activity));
14223             scheduleWritePackageRestrictionsLocked(userId);
14224         }
14225     }
14226
14227     @Override
14228     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14229         int callingUid = Binder.getCallingUid();
14230         if (callingUid != Process.SYSTEM_UID) {
14231             throw new SecurityException(
14232                     "clearPackagePersistentPreferredActivities can only be run by the system");
14233         }
14234         ArrayList<PersistentPreferredActivity> removed = null;
14235         boolean changed = false;
14236         synchronized (mPackages) {
14237             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14238                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14239                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14240                         .valueAt(i);
14241                 if (userId != thisUserId) {
14242                     continue;
14243                 }
14244                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14245                 while (it.hasNext()) {
14246                     PersistentPreferredActivity ppa = it.next();
14247                     // Mark entry for removal only if it matches the package name.
14248                     if (ppa.mComponent.getPackageName().equals(packageName)) {
14249                         if (removed == null) {
14250                             removed = new ArrayList<PersistentPreferredActivity>();
14251                         }
14252                         removed.add(ppa);
14253                     }
14254                 }
14255                 if (removed != null) {
14256                     for (int j=0; j<removed.size(); j++) {
14257                         PersistentPreferredActivity ppa = removed.get(j);
14258                         ppir.removeFilter(ppa);
14259                     }
14260                     changed = true;
14261                 }
14262             }
14263
14264             if (changed) {
14265                 scheduleWritePackageRestrictionsLocked(userId);
14266             }
14267         }
14268     }
14269
14270     /**
14271      * Common machinery for picking apart a restored XML blob and passing
14272      * it to a caller-supplied functor to be applied to the running system.
14273      */
14274     private void restoreFromXml(XmlPullParser parser, int userId,
14275             String expectedStartTag, BlobXmlRestorer functor)
14276             throws IOException, XmlPullParserException {
14277         int type;
14278         while ((type = parser.next()) != XmlPullParser.START_TAG
14279                 && type != XmlPullParser.END_DOCUMENT) {
14280         }
14281         if (type != XmlPullParser.START_TAG) {
14282             // oops didn't find a start tag?!
14283             if (DEBUG_BACKUP) {
14284                 Slog.e(TAG, "Didn't find start tag during restore");
14285             }
14286             return;
14287         }
14288
14289         // this is supposed to be TAG_PREFERRED_BACKUP
14290         if (!expectedStartTag.equals(parser.getName())) {
14291             if (DEBUG_BACKUP) {
14292                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
14293             }
14294             return;
14295         }
14296
14297         // skip interfering stuff, then we're aligned with the backing implementation
14298         while ((type = parser.next()) == XmlPullParser.TEXT) { }
14299         functor.apply(parser, userId);
14300     }
14301
14302     private interface BlobXmlRestorer {
14303         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14304     }
14305
14306     /**
14307      * Non-Binder method, support for the backup/restore mechanism: write the
14308      * full set of preferred activities in its canonical XML format.  Returns the
14309      * XML output as a byte array, or null if there is none.
14310      */
14311     @Override
14312     public byte[] getPreferredActivityBackup(int userId) {
14313         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14314             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14315         }
14316
14317         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14318         try {
14319             final XmlSerializer serializer = new FastXmlSerializer();
14320             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14321             serializer.startDocument(null, true);
14322             serializer.startTag(null, TAG_PREFERRED_BACKUP);
14323
14324             synchronized (mPackages) {
14325                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14326             }
14327
14328             serializer.endTag(null, TAG_PREFERRED_BACKUP);
14329             serializer.endDocument();
14330             serializer.flush();
14331         } catch (Exception e) {
14332             if (DEBUG_BACKUP) {
14333                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
14334             }
14335             return null;
14336         }
14337
14338         return dataStream.toByteArray();
14339     }
14340
14341     @Override
14342     public void restorePreferredActivities(byte[] backup, int userId) {
14343         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14344             throw new SecurityException("Only the system may call restorePreferredActivities()");
14345         }
14346
14347         try {
14348             final XmlPullParser parser = Xml.newPullParser();
14349             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14350             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14351                     new BlobXmlRestorer() {
14352                         @Override
14353                         public void apply(XmlPullParser parser, int userId)
14354                                 throws XmlPullParserException, IOException {
14355                             synchronized (mPackages) {
14356                                 mSettings.readPreferredActivitiesLPw(parser, userId);
14357                             }
14358                         }
14359                     } );
14360         } catch (Exception e) {
14361             if (DEBUG_BACKUP) {
14362                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14363             }
14364         }
14365     }
14366
14367     /**
14368      * Non-Binder method, support for the backup/restore mechanism: write the
14369      * default browser (etc) settings in its canonical XML format.  Returns the default
14370      * browser XML representation as a byte array, or null if there is none.
14371      */
14372     @Override
14373     public byte[] getDefaultAppsBackup(int userId) {
14374         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14375             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14376         }
14377
14378         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14379         try {
14380             final XmlSerializer serializer = new FastXmlSerializer();
14381             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14382             serializer.startDocument(null, true);
14383             serializer.startTag(null, TAG_DEFAULT_APPS);
14384
14385             synchronized (mPackages) {
14386                 mSettings.writeDefaultAppsLPr(serializer, userId);
14387             }
14388
14389             serializer.endTag(null, TAG_DEFAULT_APPS);
14390             serializer.endDocument();
14391             serializer.flush();
14392         } catch (Exception e) {
14393             if (DEBUG_BACKUP) {
14394                 Slog.e(TAG, "Unable to write default apps for backup", e);
14395             }
14396             return null;
14397         }
14398
14399         return dataStream.toByteArray();
14400     }
14401
14402     @Override
14403     public void restoreDefaultApps(byte[] backup, int userId) {
14404         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14405             throw new SecurityException("Only the system may call restoreDefaultApps()");
14406         }
14407
14408         try {
14409             final XmlPullParser parser = Xml.newPullParser();
14410             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14411             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14412                     new BlobXmlRestorer() {
14413                         @Override
14414                         public void apply(XmlPullParser parser, int userId)
14415                                 throws XmlPullParserException, IOException {
14416                             synchronized (mPackages) {
14417                                 mSettings.readDefaultAppsLPw(parser, userId);
14418                             }
14419                         }
14420                     } );
14421         } catch (Exception e) {
14422             if (DEBUG_BACKUP) {
14423                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14424             }
14425         }
14426     }
14427
14428     @Override
14429     public byte[] getIntentFilterVerificationBackup(int userId) {
14430         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14431             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14432         }
14433
14434         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14435         try {
14436             final XmlSerializer serializer = new FastXmlSerializer();
14437             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14438             serializer.startDocument(null, true);
14439             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14440
14441             synchronized (mPackages) {
14442                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14443             }
14444
14445             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14446             serializer.endDocument();
14447             serializer.flush();
14448         } catch (Exception e) {
14449             if (DEBUG_BACKUP) {
14450                 Slog.e(TAG, "Unable to write default apps for backup", e);
14451             }
14452             return null;
14453         }
14454
14455         return dataStream.toByteArray();
14456     }
14457
14458     @Override
14459     public void restoreIntentFilterVerification(byte[] backup, int userId) {
14460         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14461             throw new SecurityException("Only the system may call restorePreferredActivities()");
14462         }
14463
14464         try {
14465             final XmlPullParser parser = Xml.newPullParser();
14466             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14467             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14468                     new BlobXmlRestorer() {
14469                         @Override
14470                         public void apply(XmlPullParser parser, int userId)
14471                                 throws XmlPullParserException, IOException {
14472                             synchronized (mPackages) {
14473                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
14474                                 mSettings.writeLPr();
14475                             }
14476                         }
14477                     } );
14478         } catch (Exception e) {
14479             if (DEBUG_BACKUP) {
14480                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14481             }
14482         }
14483     }
14484
14485     @Override
14486     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14487             int sourceUserId, int targetUserId, int flags) {
14488         mContext.enforceCallingOrSelfPermission(
14489                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14490         int callingUid = Binder.getCallingUid();
14491         enforceOwnerRights(ownerPackage, callingUid);
14492         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14493         if (intentFilter.countActions() == 0) {
14494             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14495             return;
14496         }
14497         synchronized (mPackages) {
14498             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14499                     ownerPackage, targetUserId, flags);
14500             CrossProfileIntentResolver resolver =
14501                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14502             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14503             // We have all those whose filter is equal. Now checking if the rest is equal as well.
14504             if (existing != null) {
14505                 int size = existing.size();
14506                 for (int i = 0; i < size; i++) {
14507                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14508                         return;
14509                     }
14510                 }
14511             }
14512             resolver.addFilter(newFilter);
14513             scheduleWritePackageRestrictionsLocked(sourceUserId);
14514         }
14515     }
14516
14517     @Override
14518     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14519         mContext.enforceCallingOrSelfPermission(
14520                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14521         int callingUid = Binder.getCallingUid();
14522         enforceOwnerRights(ownerPackage, callingUid);
14523         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14524         synchronized (mPackages) {
14525             CrossProfileIntentResolver resolver =
14526                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14527             ArraySet<CrossProfileIntentFilter> set =
14528                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14529             for (CrossProfileIntentFilter filter : set) {
14530                 if (filter.getOwnerPackage().equals(ownerPackage)) {
14531                     resolver.removeFilter(filter);
14532                 }
14533             }
14534             scheduleWritePackageRestrictionsLocked(sourceUserId);
14535         }
14536     }
14537
14538     // Enforcing that callingUid is owning pkg on userId
14539     private void enforceOwnerRights(String pkg, int callingUid) {
14540         // The system owns everything.
14541         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14542             return;
14543         }
14544         int callingUserId = UserHandle.getUserId(callingUid);
14545         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14546         if (pi == null) {
14547             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14548                     + callingUserId);
14549         }
14550         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14551             throw new SecurityException("Calling uid " + callingUid
14552                     + " does not own package " + pkg);
14553         }
14554     }
14555
14556     @Override
14557     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14558         Intent intent = new Intent(Intent.ACTION_MAIN);
14559         intent.addCategory(Intent.CATEGORY_HOME);
14560
14561         final int callingUserId = UserHandle.getCallingUserId();
14562         List<ResolveInfo> list = queryIntentActivities(intent, null,
14563                 PackageManager.GET_META_DATA, callingUserId);
14564         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14565                 true, false, false, callingUserId);
14566
14567         allHomeCandidates.clear();
14568         if (list != null) {
14569             for (ResolveInfo ri : list) {
14570                 allHomeCandidates.add(ri);
14571             }
14572         }
14573         return (preferred == null || preferred.activityInfo == null)
14574                 ? null
14575                 : new ComponentName(preferred.activityInfo.packageName,
14576                         preferred.activityInfo.name);
14577     }
14578
14579     @Override
14580     public void setApplicationEnabledSetting(String appPackageName,
14581             int newState, int flags, int userId, String callingPackage) {
14582         if (!sUserManager.exists(userId)) return;
14583         if (callingPackage == null) {
14584             callingPackage = Integer.toString(Binder.getCallingUid());
14585         }
14586         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14587     }
14588
14589     @Override
14590     public void setComponentEnabledSetting(ComponentName componentName,
14591             int newState, int flags, int userId) {
14592         if (!sUserManager.exists(userId)) return;
14593         setEnabledSetting(componentName.getPackageName(),
14594                 componentName.getClassName(), newState, flags, userId, null);
14595     }
14596
14597     private void setEnabledSetting(final String packageName, String className, int newState,
14598             final int flags, int userId, String callingPackage) {
14599         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14600               || newState == COMPONENT_ENABLED_STATE_ENABLED
14601               || newState == COMPONENT_ENABLED_STATE_DISABLED
14602               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14603               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14604             throw new IllegalArgumentException("Invalid new component state: "
14605                     + newState);
14606         }
14607         PackageSetting pkgSetting;
14608         final int uid = Binder.getCallingUid();
14609         final int permission = mContext.checkCallingOrSelfPermission(
14610                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14611         enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14612         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14613         boolean sendNow = false;
14614         boolean isApp = (className == null);
14615         String componentName = isApp ? packageName : className;
14616         int packageUid = -1;
14617         ArrayList<String> components;
14618
14619         // writer
14620         synchronized (mPackages) {
14621             pkgSetting = mSettings.mPackages.get(packageName);
14622             if (pkgSetting == null) {
14623                 if (className == null) {
14624                     throw new IllegalArgumentException(
14625                             "Unknown package: " + packageName);
14626                 }
14627                 throw new IllegalArgumentException(
14628                         "Unknown component: " + packageName
14629                         + "/" + className);
14630             }
14631             // Allow root and verify that userId is not being specified by a different user
14632             if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14633                 throw new SecurityException(
14634                         "Permission Denial: attempt to change component state from pid="
14635                         + Binder.getCallingPid()
14636                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14637             }
14638             if (className == null) {
14639                 // We're dealing with an application/package level state change
14640                 if (pkgSetting.getEnabled(userId) == newState) {
14641                     // Nothing to do
14642                     return;
14643                 }
14644                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14645                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14646                     // Don't care about who enables an app.
14647                     callingPackage = null;
14648                 }
14649                 pkgSetting.setEnabled(newState, userId, callingPackage);
14650                 // pkgSetting.pkg.mSetEnabled = newState;
14651             } else {
14652                 // We're dealing with a component level state change
14653                 // First, verify that this is a valid class name.
14654                 PackageParser.Package pkg = pkgSetting.pkg;
14655                 if (pkg == null || !pkg.hasComponentClassName(className)) {
14656                     if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14657                         throw new IllegalArgumentException("Component class " + className
14658                                 + " does not exist in " + packageName);
14659                     } else {
14660                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14661                                 + className + " does not exist in " + packageName);
14662                     }
14663                 }
14664                 switch (newState) {
14665                 case COMPONENT_ENABLED_STATE_ENABLED:
14666                     if (!pkgSetting.enableComponentLPw(className, userId)) {
14667                         return;
14668                     }
14669                     break;
14670                 case COMPONENT_ENABLED_STATE_DISABLED:
14671                     if (!pkgSetting.disableComponentLPw(className, userId)) {
14672                         return;
14673                     }
14674                     break;
14675                 case COMPONENT_ENABLED_STATE_DEFAULT:
14676                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
14677                         return;
14678                     }
14679                     break;
14680                 default:
14681                     Slog.e(TAG, "Invalid new component state: " + newState);
14682                     return;
14683                 }
14684             }
14685             scheduleWritePackageRestrictionsLocked(userId);
14686             components = mPendingBroadcasts.get(userId, packageName);
14687             final boolean newPackage = components == null;
14688             if (newPackage) {
14689                 components = new ArrayList<String>();
14690             }
14691             if (!components.contains(componentName)) {
14692                 components.add(componentName);
14693             }
14694             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14695                 sendNow = true;
14696                 // Purge entry from pending broadcast list if another one exists already
14697                 // since we are sending one right away.
14698                 mPendingBroadcasts.remove(userId, packageName);
14699             } else {
14700                 if (newPackage) {
14701                     mPendingBroadcasts.put(userId, packageName, components);
14702                 }
14703                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14704                     // Schedule a message
14705                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14706                 }
14707             }
14708         }
14709
14710         long callingId = Binder.clearCallingIdentity();
14711         try {
14712             if (sendNow) {
14713                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14714                 sendPackageChangedBroadcast(packageName,
14715                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14716             }
14717         } finally {
14718             Binder.restoreCallingIdentity(callingId);
14719         }
14720     }
14721
14722     private void sendPackageChangedBroadcast(String packageName,
14723             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14724         if (DEBUG_INSTALL)
14725             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14726                     + componentNames);
14727         Bundle extras = new Bundle(4);
14728         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14729         String nameList[] = new String[componentNames.size()];
14730         componentNames.toArray(nameList);
14731         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14732         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14733         extras.putInt(Intent.EXTRA_UID, packageUid);
14734         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14735                 new int[] {UserHandle.getUserId(packageUid)});
14736     }
14737
14738     @Override
14739     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14740         if (!sUserManager.exists(userId)) return;
14741         final int uid = Binder.getCallingUid();
14742         final int permission = mContext.checkCallingOrSelfPermission(
14743                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14744         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14745         enforceCrossUserPermission(uid, userId, true, true, "stop package");
14746         // writer
14747         synchronized (mPackages) {
14748             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14749                     allowedByPermission, uid, userId)) {
14750                 scheduleWritePackageRestrictionsLocked(userId);
14751             }
14752         }
14753     }
14754
14755     @Override
14756     public String getInstallerPackageName(String packageName) {
14757         // reader
14758         synchronized (mPackages) {
14759             return mSettings.getInstallerPackageNameLPr(packageName);
14760         }
14761     }
14762
14763     @Override
14764     public int getApplicationEnabledSetting(String packageName, int userId) {
14765         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14766         int uid = Binder.getCallingUid();
14767         enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14768         // reader
14769         synchronized (mPackages) {
14770             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14771         }
14772     }
14773
14774     @Override
14775     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14776         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14777         int uid = Binder.getCallingUid();
14778         enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14779         // reader
14780         synchronized (mPackages) {
14781             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14782         }
14783     }
14784
14785     @Override
14786     public void enterSafeMode() {
14787         enforceSystemOrRoot("Only the system can request entering safe mode");
14788
14789         if (!mSystemReady) {
14790             mSafeMode = true;
14791         }
14792     }
14793
14794     @Override
14795     public void systemReady() {
14796         mSystemReady = true;
14797
14798         // Read the compatibilty setting when the system is ready.
14799         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14800                 mContext.getContentResolver(),
14801                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14802         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14803         if (DEBUG_SETTINGS) {
14804             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14805         }
14806
14807         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14808
14809         synchronized (mPackages) {
14810             // Verify that all of the preferred activity components actually
14811             // exist.  It is possible for applications to be updated and at
14812             // that point remove a previously declared activity component that
14813             // had been set as a preferred activity.  We try to clean this up
14814             // the next time we encounter that preferred activity, but it is
14815             // possible for the user flow to never be able to return to that
14816             // situation so here we do a sanity check to make sure we haven't
14817             // left any junk around.
14818             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14819             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14820                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14821                 removed.clear();
14822                 for (PreferredActivity pa : pir.filterSet()) {
14823                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14824                         removed.add(pa);
14825                     }
14826                 }
14827                 if (removed.size() > 0) {
14828                     for (int r=0; r<removed.size(); r++) {
14829                         PreferredActivity pa = removed.get(r);
14830                         Slog.w(TAG, "Removing dangling preferred activity: "
14831                                 + pa.mPref.mComponent);
14832                         pir.removeFilter(pa);
14833                     }
14834                     mSettings.writePackageRestrictionsLPr(
14835                             mSettings.mPreferredActivities.keyAt(i));
14836                 }
14837             }
14838
14839             for (int userId : UserManagerService.getInstance().getUserIds()) {
14840                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14841                     grantPermissionsUserIds = ArrayUtils.appendInt(
14842                             grantPermissionsUserIds, userId);
14843                 }
14844             }
14845         }
14846         sUserManager.systemReady();
14847
14848         // If we upgraded grant all default permissions before kicking off.
14849         for (int userId : grantPermissionsUserIds) {
14850             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14851         }
14852
14853         // Kick off any messages waiting for system ready
14854         if (mPostSystemReadyMessages != null) {
14855             for (Message msg : mPostSystemReadyMessages) {
14856                 msg.sendToTarget();
14857             }
14858             mPostSystemReadyMessages = null;
14859         }
14860
14861         // Watch for external volumes that come and go over time
14862         final StorageManager storage = mContext.getSystemService(StorageManager.class);
14863         storage.registerListener(mStorageListener);
14864
14865         mInstallerService.systemReady();
14866         mPackageDexOptimizer.systemReady();
14867
14868         MountServiceInternal mountServiceInternal = LocalServices.getService(
14869                 MountServiceInternal.class);
14870         mountServiceInternal.addExternalStoragePolicy(
14871                 new MountServiceInternal.ExternalStorageMountPolicy() {
14872             @Override
14873             public int getMountMode(int uid, String packageName) {
14874                 if (Process.isIsolated(uid)) {
14875                     return Zygote.MOUNT_EXTERNAL_NONE;
14876                 }
14877                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14878                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
14879                 }
14880                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14881                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
14882                 }
14883                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14884                     return Zygote.MOUNT_EXTERNAL_READ;
14885                 }
14886                 return Zygote.MOUNT_EXTERNAL_WRITE;
14887             }
14888
14889             @Override
14890             public boolean hasExternalStorage(int uid, String packageName) {
14891                 return true;
14892             }
14893         });
14894     }
14895
14896     @Override
14897     public boolean isSafeMode() {
14898         return mSafeMode;
14899     }
14900
14901     @Override
14902     public boolean hasSystemUidErrors() {
14903         return mHasSystemUidErrors;
14904     }
14905
14906     static String arrayToString(int[] array) {
14907         StringBuffer buf = new StringBuffer(128);
14908         buf.append('[');
14909         if (array != null) {
14910             for (int i=0; i<array.length; i++) {
14911                 if (i > 0) buf.append(", ");
14912                 buf.append(array[i]);
14913             }
14914         }
14915         buf.append(']');
14916         return buf.toString();
14917     }
14918
14919     static class DumpState {
14920         public static final int DUMP_LIBS = 1 << 0;
14921         public static final int DUMP_FEATURES = 1 << 1;
14922         public static final int DUMP_RESOLVERS = 1 << 2;
14923         public static final int DUMP_PERMISSIONS = 1 << 3;
14924         public static final int DUMP_PACKAGES = 1 << 4;
14925         public static final int DUMP_SHARED_USERS = 1 << 5;
14926         public static final int DUMP_MESSAGES = 1 << 6;
14927         public static final int DUMP_PROVIDERS = 1 << 7;
14928         public static final int DUMP_VERIFIERS = 1 << 8;
14929         public static final int DUMP_PREFERRED = 1 << 9;
14930         public static final int DUMP_PREFERRED_XML = 1 << 10;
14931         public static final int DUMP_KEYSETS = 1 << 11;
14932         public static final int DUMP_VERSION = 1 << 12;
14933         public static final int DUMP_INSTALLS = 1 << 13;
14934         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14935         public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14936
14937         public static final int OPTION_SHOW_FILTERS = 1 << 0;
14938
14939         private int mTypes;
14940
14941         private int mOptions;
14942
14943         private boolean mTitlePrinted;
14944
14945         private SharedUserSetting mSharedUser;
14946
14947         public boolean isDumping(int type) {
14948             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14949                 return true;
14950             }
14951
14952             return (mTypes & type) != 0;
14953         }
14954
14955         public void setDump(int type) {
14956             mTypes |= type;
14957         }
14958
14959         public boolean isOptionEnabled(int option) {
14960             return (mOptions & option) != 0;
14961         }
14962
14963         public void setOptionEnabled(int option) {
14964             mOptions |= option;
14965         }
14966
14967         public boolean onTitlePrinted() {
14968             final boolean printed = mTitlePrinted;
14969             mTitlePrinted = true;
14970             return printed;
14971         }
14972
14973         public boolean getTitlePrinted() {
14974             return mTitlePrinted;
14975         }
14976
14977         public void setTitlePrinted(boolean enabled) {
14978             mTitlePrinted = enabled;
14979         }
14980
14981         public SharedUserSetting getSharedUser() {
14982             return mSharedUser;
14983         }
14984
14985         public void setSharedUser(SharedUserSetting user) {
14986             mSharedUser = user;
14987         }
14988     }
14989
14990     @Override
14991     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14992         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14993                 != PackageManager.PERMISSION_GRANTED) {
14994             pw.println("Permission Denial: can't dump ActivityManager from from pid="
14995                     + Binder.getCallingPid()
14996                     + ", uid=" + Binder.getCallingUid()
14997                     + " without permission "
14998                     + android.Manifest.permission.DUMP);
14999             return;
15000         }
15001
15002         DumpState dumpState = new DumpState();
15003         boolean fullPreferred = false;
15004         boolean checkin = false;
15005
15006         String packageName = null;
15007         ArraySet<String> permissionNames = null;
15008
15009         int opti = 0;
15010         while (opti < args.length) {
15011             String opt = args[opti];
15012             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15013                 break;
15014             }
15015             opti++;
15016
15017             if ("-a".equals(opt)) {
15018                 // Right now we only know how to print all.
15019             } else if ("-h".equals(opt)) {
15020                 pw.println("Package manager dump options:");
15021                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15022                 pw.println("    --checkin: dump for a checkin");
15023                 pw.println("    -f: print details of intent filters");
15024                 pw.println("    -h: print this help");
15025                 pw.println("  cmd may be one of:");
15026                 pw.println("    l[ibraries]: list known shared libraries");
15027                 pw.println("    f[ibraries]: list device features");
15028                 pw.println("    k[eysets]: print known keysets");
15029                 pw.println("    r[esolvers]: dump intent resolvers");
15030                 pw.println("    perm[issions]: dump permissions");
15031                 pw.println("    permission [name ...]: dump declaration and use of given permission");
15032                 pw.println("    pref[erred]: print preferred package settings");
15033                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15034                 pw.println("    prov[iders]: dump content providers");
15035                 pw.println("    p[ackages]: dump installed packages");
15036                 pw.println("    s[hared-users]: dump shared user IDs");
15037                 pw.println("    m[essages]: print collected runtime messages");
15038                 pw.println("    v[erifiers]: print package verifier info");
15039                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15040                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15041                 pw.println("    version: print database version info");
15042                 pw.println("    write: write current settings now");
15043                 pw.println("    installs: details about install sessions");
15044                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15045                 pw.println("    <package.name>: info about given package");
15046                 return;
15047             } else if ("--checkin".equals(opt)) {
15048                 checkin = true;
15049             } else if ("-f".equals(opt)) {
15050                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15051             } else {
15052                 pw.println("Unknown argument: " + opt + "; use -h for help");
15053             }
15054         }
15055
15056         // Is the caller requesting to dump a particular piece of data?
15057         if (opti < args.length) {
15058             String cmd = args[opti];
15059             opti++;
15060             // Is this a package name?
15061             if ("android".equals(cmd) || cmd.contains(".")) {
15062                 packageName = cmd;
15063                 // When dumping a single package, we always dump all of its
15064                 // filter information since the amount of data will be reasonable.
15065                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15066             } else if ("check-permission".equals(cmd)) {
15067                 if (opti >= args.length) {
15068                     pw.println("Error: check-permission missing permission argument");
15069                     return;
15070                 }
15071                 String perm = args[opti];
15072                 opti++;
15073                 if (opti >= args.length) {
15074                     pw.println("Error: check-permission missing package argument");
15075                     return;
15076                 }
15077                 String pkg = args[opti];
15078                 opti++;
15079                 int user = UserHandle.getUserId(Binder.getCallingUid());
15080                 if (opti < args.length) {
15081                     try {
15082                         user = Integer.parseInt(args[opti]);
15083                     } catch (NumberFormatException e) {
15084                         pw.println("Error: check-permission user argument is not a number: "
15085                                 + args[opti]);
15086                         return;
15087                     }
15088                 }
15089                 pw.println(checkPermission(perm, pkg, user));
15090                 return;
15091             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15092                 dumpState.setDump(DumpState.DUMP_LIBS);
15093             } else if ("f".equals(cmd) || "features".equals(cmd)) {
15094                 dumpState.setDump(DumpState.DUMP_FEATURES);
15095             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15096                 dumpState.setDump(DumpState.DUMP_RESOLVERS);
15097             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15098                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15099             } else if ("permission".equals(cmd)) {
15100                 if (opti >= args.length) {
15101                     pw.println("Error: permission requires permission name");
15102                     return;
15103                 }
15104                 permissionNames = new ArraySet<>();
15105                 while (opti < args.length) {
15106                     permissionNames.add(args[opti]);
15107                     opti++;
15108                 }
15109                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
15110                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15111             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15112                 dumpState.setDump(DumpState.DUMP_PREFERRED);
15113             } else if ("preferred-xml".equals(cmd)) {
15114                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15115                 if (opti < args.length && "--full".equals(args[opti])) {
15116                     fullPreferred = true;
15117                     opti++;
15118                 }
15119             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15120                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15121             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15122                 dumpState.setDump(DumpState.DUMP_PACKAGES);
15123             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15124                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15125             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15126                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
15127             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15128                 dumpState.setDump(DumpState.DUMP_MESSAGES);
15129             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15130                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
15131             } else if ("i".equals(cmd) || "ifv".equals(cmd)
15132                     || "intent-filter-verifiers".equals(cmd)) {
15133                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15134             } else if ("version".equals(cmd)) {
15135                 dumpState.setDump(DumpState.DUMP_VERSION);
15136             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15137                 dumpState.setDump(DumpState.DUMP_KEYSETS);
15138             } else if ("installs".equals(cmd)) {
15139                 dumpState.setDump(DumpState.DUMP_INSTALLS);
15140             } else if ("write".equals(cmd)) {
15141                 synchronized (mPackages) {
15142                     mSettings.writeLPr();
15143                     pw.println("Settings written.");
15144                     return;
15145                 }
15146             }
15147         }
15148
15149         if (checkin) {
15150             pw.println("vers,1");
15151         }
15152
15153         // reader
15154         synchronized (mPackages) {
15155             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15156                 if (!checkin) {
15157                     if (dumpState.onTitlePrinted())
15158                         pw.println();
15159                     pw.println("Database versions:");
15160                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15161                 }
15162             }
15163
15164             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15165                 if (!checkin) {
15166                     if (dumpState.onTitlePrinted())
15167                         pw.println();
15168                     pw.println("Verifiers:");
15169                     pw.print("  Required: ");
15170                     pw.print(mRequiredVerifierPackage);
15171                     pw.print(" (uid=");
15172                     pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15173                     pw.println(")");
15174                 } else if (mRequiredVerifierPackage != null) {
15175                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15176                     pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15177                 }
15178             }
15179
15180             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15181                     packageName == null) {
15182                 if (mIntentFilterVerifierComponent != null) {
15183                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15184                     if (!checkin) {
15185                         if (dumpState.onTitlePrinted())
15186                             pw.println();
15187                         pw.println("Intent Filter Verifier:");
15188                         pw.print("  Using: ");
15189                         pw.print(verifierPackageName);
15190                         pw.print(" (uid=");
15191                         pw.print(getPackageUid(verifierPackageName, 0));
15192                         pw.println(")");
15193                     } else if (verifierPackageName != null) {
15194                         pw.print("ifv,"); pw.print(verifierPackageName);
15195                         pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15196                     }
15197                 } else {
15198                     pw.println();
15199                     pw.println("No Intent Filter Verifier available!");
15200                 }
15201             }
15202
15203             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15204                 boolean printedHeader = false;
15205                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
15206                 while (it.hasNext()) {
15207                     String name = it.next();
15208                     SharedLibraryEntry ent = mSharedLibraries.get(name);
15209                     if (!checkin) {
15210                         if (!printedHeader) {
15211                             if (dumpState.onTitlePrinted())
15212                                 pw.println();
15213                             pw.println("Libraries:");
15214                             printedHeader = true;
15215                         }
15216                         pw.print("  ");
15217                     } else {
15218                         pw.print("lib,");
15219                     }
15220                     pw.print(name);
15221                     if (!checkin) {
15222                         pw.print(" -> ");
15223                     }
15224                     if (ent.path != null) {
15225                         if (!checkin) {
15226                             pw.print("(jar) ");
15227                             pw.print(ent.path);
15228                         } else {
15229                             pw.print(",jar,");
15230                             pw.print(ent.path);
15231                         }
15232                     } else {
15233                         if (!checkin) {
15234                             pw.print("(apk) ");
15235                             pw.print(ent.apk);
15236                         } else {
15237                             pw.print(",apk,");
15238                             pw.print(ent.apk);
15239                         }
15240                     }
15241                     pw.println();
15242                 }
15243             }
15244
15245             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15246                 if (dumpState.onTitlePrinted())
15247                     pw.println();
15248                 if (!checkin) {
15249                     pw.println("Features:");
15250                 }
15251                 Iterator<String> it = mAvailableFeatures.keySet().iterator();
15252                 while (it.hasNext()) {
15253                     String name = it.next();
15254                     if (!checkin) {
15255                         pw.print("  ");
15256                     } else {
15257                         pw.print("feat,");
15258                     }
15259                     pw.println(name);
15260                 }
15261             }
15262
15263             if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15264                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15265                         : "Activity Resolver Table:", "  ", packageName,
15266                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15267                     dumpState.setTitlePrinted(true);
15268                 }
15269                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15270                         : "Receiver Resolver Table:", "  ", packageName,
15271                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15272                     dumpState.setTitlePrinted(true);
15273                 }
15274                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15275                         : "Service Resolver Table:", "  ", packageName,
15276                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15277                     dumpState.setTitlePrinted(true);
15278                 }
15279                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15280                         : "Provider Resolver Table:", "  ", packageName,
15281                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15282                     dumpState.setTitlePrinted(true);
15283                 }
15284             }
15285
15286             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15287                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15288                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15289                     int user = mSettings.mPreferredActivities.keyAt(i);
15290                     if (pir.dump(pw,
15291                             dumpState.getTitlePrinted()
15292                                 ? "\nPreferred Activities User " + user + ":"
15293                                 : "Preferred Activities User " + user + ":", "  ",
15294                             packageName, true, false)) {
15295                         dumpState.setTitlePrinted(true);
15296                     }
15297                 }
15298             }
15299
15300             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15301                 pw.flush();
15302                 FileOutputStream fout = new FileOutputStream(fd);
15303                 BufferedOutputStream str = new BufferedOutputStream(fout);
15304                 XmlSerializer serializer = new FastXmlSerializer();
15305                 try {
15306                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
15307                     serializer.startDocument(null, true);
15308                     serializer.setFeature(
15309                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15310                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15311                     serializer.endDocument();
15312                     serializer.flush();
15313                 } catch (IllegalArgumentException e) {
15314                     pw.println("Failed writing: " + e);
15315                 } catch (IllegalStateException e) {
15316                     pw.println("Failed writing: " + e);
15317                 } catch (IOException e) {
15318                     pw.println("Failed writing: " + e);
15319                 }
15320             }
15321
15322             if (!checkin
15323                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15324                     && packageName == null) {
15325                 pw.println();
15326                 int count = mSettings.mPackages.size();
15327                 if (count == 0) {
15328                     pw.println("No applications!");
15329                     pw.println();
15330                 } else {
15331                     final String prefix = "  ";
15332                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15333                     if (allPackageSettings.size() == 0) {
15334                         pw.println("No domain preferred apps!");
15335                         pw.println();
15336                     } else {
15337                         pw.println("App verification status:");
15338                         pw.println();
15339                         count = 0;
15340                         for (PackageSetting ps : allPackageSettings) {
15341                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15342                             if (ivi == null || ivi.getPackageName() == null) continue;
15343                             pw.println(prefix + "Package: " + ivi.getPackageName());
15344                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
15345                             pw.println(prefix + "Status:  " + ivi.getStatusString());
15346                             pw.println();
15347                             count++;
15348                         }
15349                         if (count == 0) {
15350                             pw.println(prefix + "No app verification established.");
15351                             pw.println();
15352                         }
15353                         for (int userId : sUserManager.getUserIds()) {
15354                             pw.println("App linkages for user " + userId + ":");
15355                             pw.println();
15356                             count = 0;
15357                             for (PackageSetting ps : allPackageSettings) {
15358                                 final long status = ps.getDomainVerificationStatusForUser(userId);
15359                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15360                                     continue;
15361                                 }
15362                                 pw.println(prefix + "Package: " + ps.name);
15363                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15364                                 String statusStr = IntentFilterVerificationInfo.
15365                                         getStatusStringFromValue(status);
15366                                 pw.println(prefix + "Status:  " + statusStr);
15367                                 pw.println();
15368                                 count++;
15369                             }
15370                             if (count == 0) {
15371                                 pw.println(prefix + "No configured app linkages.");
15372                                 pw.println();
15373                             }
15374                         }
15375                     }
15376                 }
15377             }
15378
15379             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15380                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15381                 if (packageName == null && permissionNames == null) {
15382                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15383                         if (iperm == 0) {
15384                             if (dumpState.onTitlePrinted())
15385                                 pw.println();
15386                             pw.println("AppOp Permissions:");
15387                         }
15388                         pw.print("  AppOp Permission ");
15389                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
15390                         pw.println(":");
15391                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15392                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15393                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15394                         }
15395                     }
15396                 }
15397             }
15398
15399             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15400                 boolean printedSomething = false;
15401                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
15402                     if (packageName != null && !packageName.equals(p.info.packageName)) {
15403                         continue;
15404                     }
15405                     if (!printedSomething) {
15406                         if (dumpState.onTitlePrinted())
15407                             pw.println();
15408                         pw.println("Registered ContentProviders:");
15409                         printedSomething = true;
15410                     }
15411                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15412                     pw.print("    "); pw.println(p.toString());
15413                 }
15414                 printedSomething = false;
15415                 for (Map.Entry<String, PackageParser.Provider> entry :
15416                         mProvidersByAuthority.entrySet()) {
15417                     PackageParser.Provider p = entry.getValue();
15418                     if (packageName != null && !packageName.equals(p.info.packageName)) {
15419                         continue;
15420                     }
15421                     if (!printedSomething) {
15422                         if (dumpState.onTitlePrinted())
15423                             pw.println();
15424                         pw.println("ContentProvider Authorities:");
15425                         printedSomething = true;
15426                     }
15427                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15428                     pw.print("    "); pw.println(p.toString());
15429                     if (p.info != null && p.info.applicationInfo != null) {
15430                         final String appInfo = p.info.applicationInfo.toString();
15431                         pw.print("      applicationInfo="); pw.println(appInfo);
15432                     }
15433                 }
15434             }
15435
15436             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15437                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15438             }
15439
15440             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15441                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15442             }
15443
15444             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15445                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15446             }
15447
15448             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15449                 // XXX should handle packageName != null by dumping only install data that
15450                 // the given package is involved with.
15451                 if (dumpState.onTitlePrinted()) pw.println();
15452                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15453             }
15454
15455             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15456                 if (dumpState.onTitlePrinted()) pw.println();
15457                 mSettings.dumpReadMessagesLPr(pw, dumpState);
15458
15459                 pw.println();
15460                 pw.println("Package warning messages:");
15461                 BufferedReader in = null;
15462                 String line = null;
15463                 try {
15464                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15465                     while ((line = in.readLine()) != null) {
15466                         if (line.contains("ignored: updated version")) continue;
15467                         pw.println(line);
15468                     }
15469                 } catch (IOException ignored) {
15470                 } finally {
15471                     IoUtils.closeQuietly(in);
15472                 }
15473             }
15474
15475             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15476                 BufferedReader in = null;
15477                 String line = null;
15478                 try {
15479                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15480                     while ((line = in.readLine()) != null) {
15481                         if (line.contains("ignored: updated version")) continue;
15482                         pw.print("msg,");
15483                         pw.println(line);
15484                     }
15485                 } catch (IOException ignored) {
15486                 } finally {
15487                     IoUtils.closeQuietly(in);
15488                 }
15489             }
15490         }
15491     }
15492
15493     private String dumpDomainString(String packageName) {
15494         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15495         List<IntentFilter> filters = getAllIntentFilters(packageName);
15496
15497         ArraySet<String> result = new ArraySet<>();
15498         if (iviList.size() > 0) {
15499             for (IntentFilterVerificationInfo ivi : iviList) {
15500                 for (String host : ivi.getDomains()) {
15501                     result.add(host);
15502                 }
15503             }
15504         }
15505         if (filters != null && filters.size() > 0) {
15506             for (IntentFilter filter : filters) {
15507                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15508                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15509                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15510                     result.addAll(filter.getHostsList());
15511                 }
15512             }
15513         }
15514
15515         StringBuilder sb = new StringBuilder(result.size() * 16);
15516         for (String domain : result) {
15517             if (sb.length() > 0) sb.append(" ");
15518             sb.append(domain);
15519         }
15520         return sb.toString();
15521     }
15522
15523     // ------- apps on sdcard specific code -------
15524     static final boolean DEBUG_SD_INSTALL = false;
15525
15526     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15527
15528     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15529
15530     private boolean mMediaMounted = false;
15531
15532     static String getEncryptKey() {
15533         try {
15534             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15535                     SD_ENCRYPTION_KEYSTORE_NAME);
15536             if (sdEncKey == null) {
15537                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15538                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15539                 if (sdEncKey == null) {
15540                     Slog.e(TAG, "Failed to create encryption keys");
15541                     return null;
15542                 }
15543             }
15544             return sdEncKey;
15545         } catch (NoSuchAlgorithmException nsae) {
15546             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15547             return null;
15548         } catch (IOException ioe) {
15549             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15550             return null;
15551         }
15552     }
15553
15554     /*
15555      * Update media status on PackageManager.
15556      */
15557     @Override
15558     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15559         int callingUid = Binder.getCallingUid();
15560         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15561             throw new SecurityException("Media status can only be updated by the system");
15562         }
15563         // reader; this apparently protects mMediaMounted, but should probably
15564         // be a different lock in that case.
15565         synchronized (mPackages) {
15566             Log.i(TAG, "Updating external media status from "
15567                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
15568                     + (mediaStatus ? "mounted" : "unmounted"));
15569             if (DEBUG_SD_INSTALL)
15570                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15571                         + ", mMediaMounted=" + mMediaMounted);
15572             if (mediaStatus == mMediaMounted) {
15573                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15574                         : 0, -1);
15575                 mHandler.sendMessage(msg);
15576                 return;
15577             }
15578             mMediaMounted = mediaStatus;
15579         }
15580         // Queue up an async operation since the package installation may take a
15581         // little while.
15582         mHandler.post(new Runnable() {
15583             public void run() {
15584                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15585             }
15586         });
15587     }
15588
15589     /**
15590      * Called by MountService when the initial ASECs to scan are available.
15591      * Should block until all the ASEC containers are finished being scanned.
15592      */
15593     public void scanAvailableAsecs() {
15594         updateExternalMediaStatusInner(true, false, false);
15595         if (mShouldRestoreconData) {
15596             SELinuxMMAC.setRestoreconDone();
15597             mShouldRestoreconData = false;
15598         }
15599     }
15600
15601     /*
15602      * Collect information of applications on external media, map them against
15603      * existing containers and update information based on current mount status.
15604      * Please note that we always have to report status if reportStatus has been
15605      * set to true especially when unloading packages.
15606      */
15607     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15608             boolean externalStorage) {
15609         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15610         int[] uidArr = EmptyArray.INT;
15611
15612         final String[] list = PackageHelper.getSecureContainerList();
15613         if (ArrayUtils.isEmpty(list)) {
15614             Log.i(TAG, "No secure containers found");
15615         } else {
15616             // Process list of secure containers and categorize them
15617             // as active or stale based on their package internal state.
15618
15619             // reader
15620             synchronized (mPackages) {
15621                 for (String cid : list) {
15622                     // Leave stages untouched for now; installer service owns them
15623                     if (PackageInstallerService.isStageName(cid)) continue;
15624
15625                     if (DEBUG_SD_INSTALL)
15626                         Log.i(TAG, "Processing container " + cid);
15627                     String pkgName = getAsecPackageName(cid);
15628                     if (pkgName == null) {
15629                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
15630                         continue;
15631                     }
15632                     if (DEBUG_SD_INSTALL)
15633                         Log.i(TAG, "Looking for pkg : " + pkgName);
15634
15635                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
15636                     if (ps == null) {
15637                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15638                         continue;
15639                     }
15640
15641                     /*
15642                      * Skip packages that are not external if we're unmounting
15643                      * external storage.
15644                      */
15645                     if (externalStorage && !isMounted && !isExternal(ps)) {
15646                         continue;
15647                     }
15648
15649                     final AsecInstallArgs args = new AsecInstallArgs(cid,
15650                             getAppDexInstructionSets(ps), ps.isForwardLocked());
15651                     // The package status is changed only if the code path
15652                     // matches between settings and the container id.
15653                     if (ps.codePathString != null
15654                             && ps.codePathString.startsWith(args.getCodePath())) {
15655                         if (DEBUG_SD_INSTALL) {
15656                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15657                                     + " at code path: " + ps.codePathString);
15658                         }
15659
15660                         // We do have a valid package installed on sdcard
15661                         processCids.put(args, ps.codePathString);
15662                         final int uid = ps.appId;
15663                         if (uid != -1) {
15664                             uidArr = ArrayUtils.appendInt(uidArr, uid);
15665                         }
15666                     } else {
15667                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15668                                 + ps.codePathString);
15669                     }
15670                 }
15671             }
15672
15673             Arrays.sort(uidArr);
15674         }
15675
15676         // Process packages with valid entries.
15677         if (isMounted) {
15678             if (DEBUG_SD_INSTALL)
15679                 Log.i(TAG, "Loading packages");
15680             loadMediaPackages(processCids, uidArr);
15681             startCleaningPackages();
15682             mInstallerService.onSecureContainersAvailable();
15683         } else {
15684             if (DEBUG_SD_INSTALL)
15685                 Log.i(TAG, "Unloading packages");
15686             unloadMediaPackages(processCids, uidArr, reportStatus);
15687         }
15688     }
15689
15690     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15691             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15692         final int size = infos.size();
15693         final String[] packageNames = new String[size];
15694         final int[] packageUids = new int[size];
15695         for (int i = 0; i < size; i++) {
15696             final ApplicationInfo info = infos.get(i);
15697             packageNames[i] = info.packageName;
15698             packageUids[i] = info.uid;
15699         }
15700         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15701                 finishedReceiver);
15702     }
15703
15704     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15705             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15706         sendResourcesChangedBroadcast(mediaStatus, replacing,
15707                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15708     }
15709
15710     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15711             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15712         int size = pkgList.length;
15713         if (size > 0) {
15714             // Send broadcasts here
15715             Bundle extras = new Bundle();
15716             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15717             if (uidArr != null) {
15718                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15719             }
15720             if (replacing) {
15721                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15722             }
15723             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15724                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15725             sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15726         }
15727     }
15728
15729    /*
15730      * Look at potentially valid container ids from processCids If package
15731      * information doesn't match the one on record or package scanning fails,
15732      * the cid is added to list of removeCids. We currently don't delete stale
15733      * containers.
15734      */
15735     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15736         ArrayList<String> pkgList = new ArrayList<String>();
15737         Set<AsecInstallArgs> keys = processCids.keySet();
15738
15739         for (AsecInstallArgs args : keys) {
15740             String codePath = processCids.get(args);
15741             if (DEBUG_SD_INSTALL)
15742                 Log.i(TAG, "Loading container : " + args.cid);
15743             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15744             try {
15745                 // Make sure there are no container errors first.
15746                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15747                     Slog.e(TAG, "Failed to mount cid : " + args.cid
15748                             + " when installing from sdcard");
15749                     continue;
15750                 }
15751                 // Check code path here.
15752                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15753                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15754                             + " does not match one in settings " + codePath);
15755                     continue;
15756                 }
15757                 // Parse package
15758                 int parseFlags = mDefParseFlags;
15759                 if (args.isExternalAsec()) {
15760                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15761                 }
15762                 if (args.isFwdLocked()) {
15763                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15764                 }
15765
15766                 synchronized (mInstallLock) {
15767                     PackageParser.Package pkg = null;
15768                     try {
15769                         pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15770                     } catch (PackageManagerException e) {
15771                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15772                     }
15773                     // Scan the package
15774                     if (pkg != null) {
15775                         /*
15776                          * TODO why is the lock being held? doPostInstall is
15777                          * called in other places without the lock. This needs
15778                          * to be straightened out.
15779                          */
15780                         // writer
15781                         synchronized (mPackages) {
15782                             retCode = PackageManager.INSTALL_SUCCEEDED;
15783                             pkgList.add(pkg.packageName);
15784                             // Post process args
15785                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15786                                     pkg.applicationInfo.uid);
15787                         }
15788                     } else {
15789                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15790                     }
15791                 }
15792
15793             } finally {
15794                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15795                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15796                 }
15797             }
15798         }
15799         // writer
15800         synchronized (mPackages) {
15801             // If the platform SDK has changed since the last time we booted,
15802             // we need to re-grant app permission to catch any new ones that
15803             // appear. This is really a hack, and means that apps can in some
15804             // cases get permissions that the user didn't initially explicitly
15805             // allow... it would be nice to have some better way to handle
15806             // this situation.
15807             final VersionInfo ver = mSettings.getExternalVersion();
15808
15809             int updateFlags = UPDATE_PERMISSIONS_ALL;
15810             if (ver.sdkVersion != mSdkVersion) {
15811                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15812                         + mSdkVersion + "; regranting permissions for external");
15813                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15814             }
15815             updatePermissionsLPw(null, null, updateFlags);
15816
15817             // Yay, everything is now upgraded
15818             ver.forceCurrent();
15819
15820             // can downgrade to reader
15821             // Persist settings
15822             mSettings.writeLPr();
15823         }
15824         // Send a broadcast to let everyone know we are done processing
15825         if (pkgList.size() > 0) {
15826             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15827         }
15828     }
15829
15830    /*
15831      * Utility method to unload a list of specified containers
15832      */
15833     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15834         // Just unmount all valid containers.
15835         for (AsecInstallArgs arg : cidArgs) {
15836             synchronized (mInstallLock) {
15837                 arg.doPostDeleteLI(false);
15838            }
15839        }
15840    }
15841
15842     /*
15843      * Unload packages mounted on external media. This involves deleting package
15844      * data from internal structures, sending broadcasts about diabled packages,
15845      * gc'ing to free up references, unmounting all secure containers
15846      * corresponding to packages on external media, and posting a
15847      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15848      * that we always have to post this message if status has been requested no
15849      * matter what.
15850      */
15851     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15852             final boolean reportStatus) {
15853         if (DEBUG_SD_INSTALL)
15854             Log.i(TAG, "unloading media packages");
15855         ArrayList<String> pkgList = new ArrayList<String>();
15856         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15857         final Set<AsecInstallArgs> keys = processCids.keySet();
15858         for (AsecInstallArgs args : keys) {
15859             String pkgName = args.getPackageName();
15860             if (DEBUG_SD_INSTALL)
15861                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
15862             // Delete package internally
15863             PackageRemovedInfo outInfo = new PackageRemovedInfo();
15864             synchronized (mInstallLock) {
15865                 boolean res = deletePackageLI(pkgName, null, false, null, null,
15866                         PackageManager.DELETE_KEEP_DATA, outInfo, false);
15867                 if (res) {
15868                     pkgList.add(pkgName);
15869                 } else {
15870                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15871                     failedList.add(args);
15872                 }
15873             }
15874         }
15875
15876         // reader
15877         synchronized (mPackages) {
15878             // We didn't update the settings after removing each package;
15879             // write them now for all packages.
15880             mSettings.writeLPr();
15881         }
15882
15883         // We have to absolutely send UPDATED_MEDIA_STATUS only
15884         // after confirming that all the receivers processed the ordered
15885         // broadcast when packages get disabled, force a gc to clean things up.
15886         // and unload all the containers.
15887         if (pkgList.size() > 0) {
15888             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15889                     new IIntentReceiver.Stub() {
15890                 public void performReceive(Intent intent, int resultCode, String data,
15891                         Bundle extras, boolean ordered, boolean sticky,
15892                         int sendingUser) throws RemoteException {
15893                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15894                             reportStatus ? 1 : 0, 1, keys);
15895                     mHandler.sendMessage(msg);
15896                 }
15897             });
15898         } else {
15899             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15900                     keys);
15901             mHandler.sendMessage(msg);
15902         }
15903     }
15904
15905     private void loadPrivatePackages(final VolumeInfo vol) {
15906         mHandler.post(new Runnable() {
15907             @Override
15908             public void run() {
15909                 loadPrivatePackagesInner(vol);
15910             }
15911         });
15912     }
15913
15914     private void loadPrivatePackagesInner(VolumeInfo vol) {
15915         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15916         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15917
15918         final VersionInfo ver;
15919         final List<PackageSetting> packages;
15920         synchronized (mPackages) {
15921             ver = mSettings.findOrCreateVersion(vol.fsUuid);
15922             packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15923         }
15924
15925         for (PackageSetting ps : packages) {
15926             synchronized (mInstallLock) {
15927                 final PackageParser.Package pkg;
15928                 try {
15929                     pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15930                     loaded.add(pkg.applicationInfo);
15931                 } catch (PackageManagerException e) {
15932                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15933                 }
15934
15935                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15936                     deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15937                 }
15938             }
15939         }
15940
15941         synchronized (mPackages) {
15942             int updateFlags = UPDATE_PERMISSIONS_ALL;
15943             if (ver.sdkVersion != mSdkVersion) {
15944                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15945                         + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15946                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15947             }
15948             updatePermissionsLPw(null, null, updateFlags);
15949
15950             // Yay, everything is now upgraded
15951             ver.forceCurrent();
15952
15953             mSettings.writeLPr();
15954         }
15955
15956         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15957         sendResourcesChangedBroadcast(true, false, loaded, null);
15958     }
15959
15960     private void unloadPrivatePackages(final VolumeInfo vol) {
15961         mHandler.post(new Runnable() {
15962             @Override
15963             public void run() {
15964                 unloadPrivatePackagesInner(vol);
15965             }
15966         });
15967     }
15968
15969     private void unloadPrivatePackagesInner(VolumeInfo vol) {
15970         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15971         synchronized (mInstallLock) {
15972         synchronized (mPackages) {
15973             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15974             for (PackageSetting ps : packages) {
15975                 if (ps.pkg == null) continue;
15976
15977                 final ApplicationInfo info = ps.pkg.applicationInfo;
15978                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15979                 if (deletePackageLI(ps.name, null, false, null, null,
15980                         PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15981                     unloaded.add(info);
15982                 } else {
15983                     Slog.w(TAG, "Failed to unload " + ps.codePath);
15984                 }
15985             }
15986
15987             mSettings.writeLPr();
15988         }
15989         }
15990
15991         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15992         sendResourcesChangedBroadcast(false, false, unloaded, null);
15993     }
15994
15995     /**
15996      * Examine all users present on given mounted volume, and destroy data
15997      * belonging to users that are no longer valid, or whose user ID has been
15998      * recycled.
15999      */
16000     private void reconcileUsers(String volumeUuid) {
16001         final File[] files = FileUtils
16002                 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16003         for (File file : files) {
16004             if (!file.isDirectory()) continue;
16005
16006             final int userId;
16007             final UserInfo info;
16008             try {
16009                 userId = Integer.parseInt(file.getName());
16010                 info = sUserManager.getUserInfo(userId);
16011             } catch (NumberFormatException e) {
16012                 Slog.w(TAG, "Invalid user directory " + file);
16013                 continue;
16014             }
16015
16016             boolean destroyUser = false;
16017             if (info == null) {
16018                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
16019                         + " because no matching user was found");
16020                 destroyUser = true;
16021             } else {
16022                 try {
16023                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
16024                 } catch (IOException e) {
16025                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
16026                             + " because we failed to enforce serial number: " + e);
16027                     destroyUser = true;
16028                 }
16029             }
16030
16031             if (destroyUser) {
16032                 synchronized (mInstallLock) {
16033                     mInstaller.removeUserDataDirs(volumeUuid, userId);
16034                 }
16035             }
16036         }
16037
16038         final UserManager um = mContext.getSystemService(UserManager.class);
16039         for (UserInfo user : um.getUsers()) {
16040             final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16041             if (userDir.exists()) continue;
16042
16043             try {
16044                 UserManagerService.prepareUserDirectory(userDir);
16045                 UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16046             } catch (IOException e) {
16047                 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16048             }
16049         }
16050     }
16051
16052     /**
16053      * Examine all apps present on given mounted volume, and destroy apps that
16054      * aren't expected, either due to uninstallation or reinstallation on
16055      * another volume.
16056      */
16057     private void reconcileApps(String volumeUuid) {
16058         final File[] files = FileUtils
16059                 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16060         for (File file : files) {
16061             final boolean isPackage = (isApkFile(file) || file.isDirectory())
16062                     && !PackageInstallerService.isStageName(file.getName());
16063             if (!isPackage) {
16064                 // Ignore entries which are not packages
16065                 continue;
16066             }
16067
16068             boolean destroyApp = false;
16069             String packageName = null;
16070             try {
16071                 final PackageLite pkg = PackageParser.parsePackageLite(file,
16072                         PackageParser.PARSE_MUST_BE_APK);
16073                 packageName = pkg.packageName;
16074
16075                 synchronized (mPackages) {
16076                     final PackageSetting ps = mSettings.mPackages.get(packageName);
16077                     if (ps == null) {
16078                         logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16079                                 + volumeUuid + " because we found no install record");
16080                         destroyApp = true;
16081                     } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16082                         logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16083                                 + volumeUuid + " because we expected it on " + ps.volumeUuid);
16084                         destroyApp = true;
16085                     }
16086                 }
16087
16088             } catch (PackageParserException e) {
16089                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16090                 destroyApp = true;
16091             }
16092
16093             if (destroyApp) {
16094                 synchronized (mInstallLock) {
16095                     if (packageName != null) {
16096                         removeDataDirsLI(volumeUuid, packageName);
16097                     }
16098                     if (file.isDirectory()) {
16099                         mInstaller.rmPackageDir(file.getAbsolutePath());
16100                     } else {
16101                         file.delete();
16102                     }
16103                 }
16104             }
16105         }
16106     }
16107
16108     private void unfreezePackage(String packageName) {
16109         synchronized (mPackages) {
16110             final PackageSetting ps = mSettings.mPackages.get(packageName);
16111             if (ps != null) {
16112                 ps.frozen = false;
16113             }
16114         }
16115     }
16116
16117     @Override
16118     public int movePackage(final String packageName, final String volumeUuid) {
16119         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16120
16121         final int moveId = mNextMoveId.getAndIncrement();
16122         try {
16123             movePackageInternal(packageName, volumeUuid, moveId);
16124         } catch (PackageManagerException e) {
16125             Slog.w(TAG, "Failed to move " + packageName, e);
16126             mMoveCallbacks.notifyStatusChanged(moveId,
16127                     PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16128         }
16129         return moveId;
16130     }
16131
16132     private void movePackageInternal(final String packageName, final String volumeUuid,
16133             final int moveId) throws PackageManagerException {
16134         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16135         final StorageManager storage = mContext.getSystemService(StorageManager.class);
16136         final PackageManager pm = mContext.getPackageManager();
16137
16138         final boolean currentAsec;
16139         final String currentVolumeUuid;
16140         final File codeFile;
16141         final String installerPackageName;
16142         final String packageAbiOverride;
16143         final int appId;
16144         final String seinfo;
16145         final String label;
16146
16147         // reader
16148         synchronized (mPackages) {
16149             final PackageParser.Package pkg = mPackages.get(packageName);
16150             final PackageSetting ps = mSettings.mPackages.get(packageName);
16151             if (pkg == null || ps == null) {
16152                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16153             }
16154
16155             if (pkg.applicationInfo.isSystemApp()) {
16156                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16157                         "Cannot move system application");
16158             }
16159
16160             if (pkg.applicationInfo.isExternalAsec()) {
16161                 currentAsec = true;
16162                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16163             } else if (pkg.applicationInfo.isForwardLocked()) {
16164                 currentAsec = true;
16165                 currentVolumeUuid = "forward_locked";
16166             } else {
16167                 currentAsec = false;
16168                 currentVolumeUuid = ps.volumeUuid;
16169
16170                 final File probe = new File(pkg.codePath);
16171                 final File probeOat = new File(probe, "oat");
16172                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
16173                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16174                             "Move only supported for modern cluster style installs");
16175                 }
16176             }
16177
16178             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16179                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16180                         "Package already moved to " + volumeUuid);
16181             }
16182
16183             if (ps.frozen) {
16184                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16185                         "Failed to move already frozen package");
16186             }
16187             ps.frozen = true;
16188
16189             codeFile = new File(pkg.codePath);
16190             installerPackageName = ps.installerPackageName;
16191             packageAbiOverride = ps.cpuAbiOverrideString;
16192             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16193             seinfo = pkg.applicationInfo.seinfo;
16194             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16195         }
16196
16197         // Now that we're guarded by frozen state, kill app during move
16198         final long token = Binder.clearCallingIdentity();
16199         try {
16200             killApplication(packageName, appId, "move pkg");
16201         } finally {
16202             Binder.restoreCallingIdentity(token);
16203         }
16204
16205         final Bundle extras = new Bundle();
16206         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16207         extras.putString(Intent.EXTRA_TITLE, label);
16208         mMoveCallbacks.notifyCreated(moveId, extras);
16209
16210         int installFlags;
16211         final boolean moveCompleteApp;
16212         final File measurePath;
16213
16214         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16215             installFlags = INSTALL_INTERNAL;
16216             moveCompleteApp = !currentAsec;
16217             measurePath = Environment.getDataAppDirectory(volumeUuid);
16218         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16219             installFlags = INSTALL_EXTERNAL;
16220             moveCompleteApp = false;
16221             measurePath = storage.getPrimaryPhysicalVolume().getPath();
16222         } else {
16223             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16224             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16225                     || !volume.isMountedWritable()) {
16226                 unfreezePackage(packageName);
16227                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16228                         "Move location not mounted private volume");
16229             }
16230
16231             Preconditions.checkState(!currentAsec);
16232
16233             installFlags = INSTALL_INTERNAL;
16234             moveCompleteApp = true;
16235             measurePath = Environment.getDataAppDirectory(volumeUuid);
16236         }
16237
16238         final PackageStats stats = new PackageStats(null, -1);
16239         synchronized (mInstaller) {
16240             if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16241                 unfreezePackage(packageName);
16242                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16243                         "Failed to measure package size");
16244             }
16245         }
16246
16247         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16248                 + stats.dataSize);
16249
16250         final long startFreeBytes = measurePath.getFreeSpace();
16251         final long sizeBytes;
16252         if (moveCompleteApp) {
16253             sizeBytes = stats.codeSize + stats.dataSize;
16254         } else {
16255             sizeBytes = stats.codeSize;
16256         }
16257
16258         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16259             unfreezePackage(packageName);
16260             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16261                     "Not enough free space to move");
16262         }
16263
16264         mMoveCallbacks.notifyStatusChanged(moveId, 10);
16265
16266         final CountDownLatch installedLatch = new CountDownLatch(1);
16267         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16268             @Override
16269             public void onUserActionRequired(Intent intent) throws RemoteException {
16270                 throw new IllegalStateException();
16271             }
16272
16273             @Override
16274             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16275                     Bundle extras) throws RemoteException {
16276                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16277                         + PackageManager.installStatusToString(returnCode, msg));
16278
16279                 installedLatch.countDown();
16280
16281                 // Regardless of success or failure of the move operation,
16282                 // always unfreeze the package
16283                 unfreezePackage(packageName);
16284
16285                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
16286                 switch (status) {
16287                     case PackageInstaller.STATUS_SUCCESS:
16288                         mMoveCallbacks.notifyStatusChanged(moveId,
16289                                 PackageManager.MOVE_SUCCEEDED);
16290                         break;
16291                     case PackageInstaller.STATUS_FAILURE_STORAGE:
16292                         mMoveCallbacks.notifyStatusChanged(moveId,
16293                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16294                         break;
16295                     default:
16296                         mMoveCallbacks.notifyStatusChanged(moveId,
16297                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16298                         break;
16299                 }
16300             }
16301         };
16302
16303         final MoveInfo move;
16304         if (moveCompleteApp) {
16305             // Kick off a thread to report progress estimates
16306             new Thread() {
16307                 @Override
16308                 public void run() {
16309                     while (true) {
16310                         try {
16311                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
16312                                 break;
16313                             }
16314                         } catch (InterruptedException ignored) {
16315                         }
16316
16317                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16318                         final int progress = 10 + (int) MathUtils.constrain(
16319                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16320                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
16321                     }
16322                 }
16323             }.start();
16324
16325             final String dataAppName = codeFile.getName();
16326             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16327                     dataAppName, appId, seinfo);
16328         } else {
16329             move = null;
16330         }
16331
16332         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16333
16334         final Message msg = mHandler.obtainMessage(INIT_COPY);
16335         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16336         msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16337                 installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16338         mHandler.sendMessage(msg);
16339     }
16340
16341     @Override
16342     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16343         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16344
16345         final int realMoveId = mNextMoveId.getAndIncrement();
16346         final Bundle extras = new Bundle();
16347         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16348         mMoveCallbacks.notifyCreated(realMoveId, extras);
16349
16350         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16351             @Override
16352             public void onCreated(int moveId, Bundle extras) {
16353                 // Ignored
16354             }
16355
16356             @Override
16357             public void onStatusChanged(int moveId, int status, long estMillis) {
16358                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16359             }
16360         };
16361
16362         final StorageManager storage = mContext.getSystemService(StorageManager.class);
16363         storage.setPrimaryStorageUuid(volumeUuid, callback);
16364         return realMoveId;
16365     }
16366
16367     @Override
16368     public int getMoveStatus(int moveId) {
16369         mContext.enforceCallingOrSelfPermission(
16370                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16371         return mMoveCallbacks.mLastStatus.get(moveId);
16372     }
16373
16374     @Override
16375     public void registerMoveCallback(IPackageMoveObserver callback) {
16376         mContext.enforceCallingOrSelfPermission(
16377                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16378         mMoveCallbacks.register(callback);
16379     }
16380
16381     @Override
16382     public void unregisterMoveCallback(IPackageMoveObserver callback) {
16383         mContext.enforceCallingOrSelfPermission(
16384                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16385         mMoveCallbacks.unregister(callback);
16386     }
16387
16388     @Override
16389     public boolean setInstallLocation(int loc) {
16390         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16391                 null);
16392         if (getInstallLocation() == loc) {
16393             return true;
16394         }
16395         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16396                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16397             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16398                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16399             return true;
16400         }
16401         return false;
16402    }
16403
16404     @Override
16405     public int getInstallLocation() {
16406         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16407                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16408                 PackageHelper.APP_INSTALL_AUTO);
16409     }
16410
16411     /** Called by UserManagerService */
16412     void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16413         mDirtyUsers.remove(userHandle);
16414         mSettings.removeUserLPw(userHandle);
16415         mPendingBroadcasts.remove(userHandle);
16416         if (mInstaller != null) {
16417             // Technically, we shouldn't be doing this with the package lock
16418             // held.  However, this is very rare, and there is already so much
16419             // other disk I/O going on, that we'll let it slide for now.
16420             final StorageManager storage = mContext.getSystemService(StorageManager.class);
16421             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16422                 final String volumeUuid = vol.getFsUuid();
16423                 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16424                 mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16425             }
16426         }
16427         mUserNeedsBadging.delete(userHandle);
16428         removeUnusedPackagesLILPw(userManager, userHandle);
16429     }
16430
16431     /**
16432      * We're removing userHandle and would like to remove any downloaded packages
16433      * that are no longer in use by any other user.
16434      * @param userHandle the user being removed
16435      */
16436     private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16437         final boolean DEBUG_CLEAN_APKS = false;
16438         int [] users = userManager.getUserIdsLPr();
16439         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16440         while (psit.hasNext()) {
16441             PackageSetting ps = psit.next();
16442             if (ps.pkg == null) {
16443                 continue;
16444             }
16445             final String packageName = ps.pkg.packageName;
16446             // Skip over if system app
16447             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16448                 continue;
16449             }
16450             if (DEBUG_CLEAN_APKS) {
16451                 Slog.i(TAG, "Checking package " + packageName);
16452             }
16453             boolean keep = false;
16454             for (int i = 0; i < users.length; i++) {
16455                 if (users[i] != userHandle && ps.getInstalled(users[i])) {
16456                     keep = true;
16457                     if (DEBUG_CLEAN_APKS) {
16458                         Slog.i(TAG, "  Keeping package " + packageName + " for user "
16459                                 + users[i]);
16460                     }
16461                     break;
16462                 }
16463             }
16464             if (!keep) {
16465                 if (DEBUG_CLEAN_APKS) {
16466                     Slog.i(TAG, "  Removing package " + packageName);
16467                 }
16468                 mHandler.post(new Runnable() {
16469                     public void run() {
16470                         deletePackageX(packageName, userHandle, 0);
16471                     } //end run
16472                 });
16473             }
16474         }
16475     }
16476
16477     /** Called by UserManagerService */
16478     void createNewUserLILPw(int userHandle) {
16479         if (mInstaller != null) {
16480             mInstaller.createUserConfig(userHandle);
16481             mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16482             applyFactoryDefaultBrowserLPw(userHandle);
16483             primeDomainVerificationsLPw(userHandle);
16484         }
16485     }
16486
16487     void newUserCreated(final int userHandle) {
16488         mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16489     }
16490
16491     @Override
16492     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16493         mContext.enforceCallingOrSelfPermission(
16494                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16495                 "Only package verification agents can read the verifier device identity");
16496
16497         synchronized (mPackages) {
16498             return mSettings.getVerifierDeviceIdentityLPw();
16499         }
16500     }
16501
16502     @Override
16503     public void setPermissionEnforced(String permission, boolean enforced) {
16504         // TODO: Now that we no longer change GID for storage, this should to away.
16505         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16506                 "setPermissionEnforced");
16507         if (READ_EXTERNAL_STORAGE.equals(permission)) {
16508             synchronized (mPackages) {
16509                 if (mSettings.mReadExternalStorageEnforced == null
16510                         || mSettings.mReadExternalStorageEnforced != enforced) {
16511                     mSettings.mReadExternalStorageEnforced = enforced;
16512                     mSettings.writeLPr();
16513                 }
16514             }
16515             // kill any non-foreground processes so we restart them and
16516             // grant/revoke the GID.
16517             final IActivityManager am = ActivityManagerNative.getDefault();
16518             if (am != null) {
16519                 final long token = Binder.clearCallingIdentity();
16520                 try {
16521                     am.killProcessesBelowForeground("setPermissionEnforcement");
16522                 } catch (RemoteException e) {
16523                 } finally {
16524                     Binder.restoreCallingIdentity(token);
16525                 }
16526             }
16527         } else {
16528             throw new IllegalArgumentException("No selective enforcement for " + permission);
16529         }
16530     }
16531
16532     @Override
16533     @Deprecated
16534     public boolean isPermissionEnforced(String permission) {
16535         return true;
16536     }
16537
16538     @Override
16539     public boolean isStorageLow() {
16540         final long token = Binder.clearCallingIdentity();
16541         try {
16542             final DeviceStorageMonitorInternal
16543                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16544             if (dsm != null) {
16545                 return dsm.isMemoryLow();
16546             } else {
16547                 return false;
16548             }
16549         } finally {
16550             Binder.restoreCallingIdentity(token);
16551         }
16552     }
16553
16554     @Override
16555     public IPackageInstaller getPackageInstaller() {
16556         return mInstallerService;
16557     }
16558
16559     private boolean userNeedsBadging(int userId) {
16560         int index = mUserNeedsBadging.indexOfKey(userId);
16561         if (index < 0) {
16562             final UserInfo userInfo;
16563             final long token = Binder.clearCallingIdentity();
16564             try {
16565                 userInfo = sUserManager.getUserInfo(userId);
16566             } finally {
16567                 Binder.restoreCallingIdentity(token);
16568             }
16569             final boolean b;
16570             if (userInfo != null && userInfo.isManagedProfile()) {
16571                 b = true;
16572             } else {
16573                 b = false;
16574             }
16575             mUserNeedsBadging.put(userId, b);
16576             return b;
16577         }
16578         return mUserNeedsBadging.valueAt(index);
16579     }
16580
16581     @Override
16582     public KeySet getKeySetByAlias(String packageName, String alias) {
16583         if (packageName == null || alias == null) {
16584             return null;
16585         }
16586         synchronized(mPackages) {
16587             final PackageParser.Package pkg = mPackages.get(packageName);
16588             if (pkg == null) {
16589                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16590                 throw new IllegalArgumentException("Unknown package: " + packageName);
16591             }
16592             KeySetManagerService ksms = mSettings.mKeySetManagerService;
16593             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16594         }
16595     }
16596
16597     @Override
16598     public KeySet getSigningKeySet(String packageName) {
16599         if (packageName == null) {
16600             return null;
16601         }
16602         synchronized(mPackages) {
16603             final PackageParser.Package pkg = mPackages.get(packageName);
16604             if (pkg == null) {
16605                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16606                 throw new IllegalArgumentException("Unknown package: " + packageName);
16607             }
16608             if (pkg.applicationInfo.uid != Binder.getCallingUid()
16609                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
16610                 throw new SecurityException("May not access signing KeySet of other apps.");
16611             }
16612             KeySetManagerService ksms = mSettings.mKeySetManagerService;
16613             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16614         }
16615     }
16616
16617     @Override
16618     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16619         if (packageName == null || ks == null) {
16620             return false;
16621         }
16622         synchronized(mPackages) {
16623             final PackageParser.Package pkg = mPackages.get(packageName);
16624             if (pkg == null) {
16625                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16626                 throw new IllegalArgumentException("Unknown package: " + packageName);
16627             }
16628             IBinder ksh = ks.getToken();
16629             if (ksh instanceof KeySetHandle) {
16630                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16631                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16632             }
16633             return false;
16634         }
16635     }
16636
16637     @Override
16638     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16639         if (packageName == null || ks == null) {
16640             return false;
16641         }
16642         synchronized(mPackages) {
16643             final PackageParser.Package pkg = mPackages.get(packageName);
16644             if (pkg == null) {
16645                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16646                 throw new IllegalArgumentException("Unknown package: " + packageName);
16647             }
16648             IBinder ksh = ks.getToken();
16649             if (ksh instanceof KeySetHandle) {
16650                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
16651                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16652             }
16653             return false;
16654         }
16655     }
16656
16657     public void getUsageStatsIfNoPackageUsageInfo() {
16658         if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16659             UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16660             if (usm == null) {
16661                 throw new IllegalStateException("UsageStatsManager must be initialized");
16662             }
16663             long now = System.currentTimeMillis();
16664             Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16665             for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16666                 String packageName = entry.getKey();
16667                 PackageParser.Package pkg = mPackages.get(packageName);
16668                 if (pkg == null) {
16669                     continue;
16670                 }
16671                 UsageStats usage = entry.getValue();
16672                 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16673                 mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16674             }
16675         }
16676     }
16677
16678     /**
16679      * Check and throw if the given before/after packages would be considered a
16680      * downgrade.
16681      */
16682     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16683             throws PackageManagerException {
16684         if (after.versionCode < before.mVersionCode) {
16685             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16686                     "Update version code " + after.versionCode + " is older than current "
16687                     + before.mVersionCode);
16688         } else if (after.versionCode == before.mVersionCode) {
16689             if (after.baseRevisionCode < before.baseRevisionCode) {
16690                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16691                         "Update base revision code " + after.baseRevisionCode
16692                         + " is older than current " + before.baseRevisionCode);
16693             }
16694
16695             if (!ArrayUtils.isEmpty(after.splitNames)) {
16696                 for (int i = 0; i < after.splitNames.length; i++) {
16697                     final String splitName = after.splitNames[i];
16698                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16699                     if (j != -1) {
16700                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16701                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16702                                     "Update split " + splitName + " revision code "
16703                                     + after.splitRevisionCodes[i] + " is older than current "
16704                                     + before.splitRevisionCodes[j]);
16705                         }
16706                     }
16707                 }
16708             }
16709         }
16710     }
16711
16712     private static class MoveCallbacks extends Handler {
16713         private static final int MSG_CREATED = 1;
16714         private static final int MSG_STATUS_CHANGED = 2;
16715
16716         private final RemoteCallbackList<IPackageMoveObserver>
16717                 mCallbacks = new RemoteCallbackList<>();
16718
16719         private final SparseIntArray mLastStatus = new SparseIntArray();
16720
16721         public MoveCallbacks(Looper looper) {
16722             super(looper);
16723         }
16724
16725         public void register(IPackageMoveObserver callback) {
16726             mCallbacks.register(callback);
16727         }
16728
16729         public void unregister(IPackageMoveObserver callback) {
16730             mCallbacks.unregister(callback);
16731         }
16732
16733         @Override
16734         public void handleMessage(Message msg) {
16735             final SomeArgs args = (SomeArgs) msg.obj;
16736             final int n = mCallbacks.beginBroadcast();
16737             for (int i = 0; i < n; i++) {
16738                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16739                 try {
16740                     invokeCallback(callback, msg.what, args);
16741                 } catch (RemoteException ignored) {
16742                 }
16743             }
16744             mCallbacks.finishBroadcast();
16745             args.recycle();
16746         }
16747
16748         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16749                 throws RemoteException {
16750             switch (what) {
16751                 case MSG_CREATED: {
16752                     callback.onCreated(args.argi1, (Bundle) args.arg2);
16753                     break;
16754                 }
16755                 case MSG_STATUS_CHANGED: {
16756                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16757                     break;
16758                 }
16759             }
16760         }
16761
16762         private void notifyCreated(int moveId, Bundle extras) {
16763             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16764
16765             final SomeArgs args = SomeArgs.obtain();
16766             args.argi1 = moveId;
16767             args.arg2 = extras;
16768             obtainMessage(MSG_CREATED, args).sendToTarget();
16769         }
16770
16771         private void notifyStatusChanged(int moveId, int status) {
16772             notifyStatusChanged(moveId, status, -1);
16773         }
16774
16775         private void notifyStatusChanged(int moveId, int status, long estMillis) {
16776             Slog.v(TAG, "Move " + moveId + " status " + status);
16777
16778             final SomeArgs args = SomeArgs.obtain();
16779             args.argi1 = moveId;
16780             args.argi2 = status;
16781             args.arg3 = estMillis;
16782             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16783
16784             synchronized (mLastStatus) {
16785                 mLastStatus.put(moveId, status);
16786             }
16787         }
16788     }
16789
16790     private final class OnPermissionChangeListeners extends Handler {
16791         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16792
16793         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16794                 new RemoteCallbackList<>();
16795
16796         public OnPermissionChangeListeners(Looper looper) {
16797             super(looper);
16798         }
16799
16800         @Override
16801         public void handleMessage(Message msg) {
16802             switch (msg.what) {
16803                 case MSG_ON_PERMISSIONS_CHANGED: {
16804                     final int uid = msg.arg1;
16805                     handleOnPermissionsChanged(uid);
16806                 } break;
16807             }
16808         }
16809
16810         public void addListenerLocked(IOnPermissionsChangeListener listener) {
16811             mPermissionListeners.register(listener);
16812
16813         }
16814
16815         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16816             mPermissionListeners.unregister(listener);
16817         }
16818
16819         public void onPermissionsChanged(int uid) {
16820             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16821                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16822             }
16823         }
16824
16825         private void handleOnPermissionsChanged(int uid) {
16826             final int count = mPermissionListeners.beginBroadcast();
16827             try {
16828                 for (int i = 0; i < count; i++) {
16829                     IOnPermissionsChangeListener callback = mPermissionListeners
16830                             .getBroadcastItem(i);
16831                     try {
16832                         callback.onPermissionsChanged(uid);
16833                     } catch (RemoteException e) {
16834                         Log.e(TAG, "Permission listener is dead", e);
16835                     }
16836                 }
16837             } finally {
16838                 mPermissionListeners.finishBroadcast();
16839             }
16840         }
16841     }
16842
16843     private class PackageManagerInternalImpl extends PackageManagerInternal {
16844         @Override
16845         public void setLocationPackagesProvider(PackagesProvider provider) {
16846             synchronized (mPackages) {
16847                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16848             }
16849         }
16850
16851         @Override
16852         public void setImePackagesProvider(PackagesProvider provider) {
16853             synchronized (mPackages) {
16854                 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16855             }
16856         }
16857
16858         @Override
16859         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16860             synchronized (mPackages) {
16861                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16862             }
16863         }
16864
16865         @Override
16866         public void setSmsAppPackagesProvider(PackagesProvider provider) {
16867             synchronized (mPackages) {
16868                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16869             }
16870         }
16871
16872         @Override
16873         public void setDialerAppPackagesProvider(PackagesProvider provider) {
16874             synchronized (mPackages) {
16875                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16876             }
16877         }
16878
16879         @Override
16880         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16881             synchronized (mPackages) {
16882                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16883             }
16884         }
16885
16886         @Override
16887         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16888             synchronized (mPackages) {
16889                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16890             }
16891         }
16892
16893         @Override
16894         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16895             synchronized (mPackages) {
16896                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16897                         packageName, userId);
16898             }
16899         }
16900
16901         @Override
16902         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16903             synchronized (mPackages) {
16904                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16905                         packageName, userId);
16906             }
16907         }
16908         @Override
16909         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16910             synchronized (mPackages) {
16911                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16912                         packageName, userId);
16913             }
16914         }
16915     }
16916
16917     @Override
16918     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16919         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16920         synchronized (mPackages) {
16921             final long identity = Binder.clearCallingIdentity();
16922             try {
16923                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16924                         packageNames, userId);
16925             } finally {
16926                 Binder.restoreCallingIdentity(identity);
16927             }
16928         }
16929     }
16930
16931     private static void enforceSystemOrPhoneCaller(String tag) {
16932         int callingUid = Binder.getCallingUid();
16933         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16934             throw new SecurityException(
16935                     "Cannot call " + tag + " from UID " + callingUid);
16936         }
16937     }
16938 }