PackageManagerService.java revision e75c0b9873d56e2569d0c5dff78f8872b8c8e97f
1760943b5e7a09b602aba04ec451e97662f48b0a4James Dong/*
2760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Copyright (C) 2006 The Android Open Source Project
3760943b5e7a09b602aba04ec451e97662f48b0a4James Dong *
4760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Licensed under the Apache License, Version 2.0 (the "License");
5760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * you may not use this file except in compliance with the License.
6760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * You may obtain a copy of the License at
7760943b5e7a09b602aba04ec451e97662f48b0a4James Dong *
8760943b5e7a09b602aba04ec451e97662f48b0a4James Dong *      http://www.apache.org/licenses/LICENSE-2.0
9760943b5e7a09b602aba04ec451e97662f48b0a4James Dong *
10760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Unless required by applicable law or agreed to in writing, software
11760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * distributed under the License is distributed on an "AS IS" BASIS,
12760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * See the License for the specific language governing permissions and
14760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * limitations under the License.
15760943b5e7a09b602aba04ec451e97662f48b0a4James Dong */
16760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
17a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzynpackage com.android.server.pm;
18a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzyn
19a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzynimport static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzynimport static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzynimport static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzynimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27aeb8fd460ed87d032b3fb8bb61e21eb542ce0f5bDave Burkeimport static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45c6ac859f5a82ea8642bc6351a45508a15f224f32Marco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46c6ac859f5a82ea8642bc6351a45508a15f224f32Marco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47c6ac859f5a82ea8642bc6351a45508a15f224f32Marco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
499fa3db9a8c164daaf0d7334595dbd0ca24fe97bfMarco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50c6ac859f5a82ea8642bc6351a45508a15f224f32Marco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51c6ac859f5a82ea8642bc6351a45508a15f224f32Marco Nelissenimport static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INSTALL_INTERNAL;
568bcc65c753085fe3328592cceda0cf0e8f8b0a45James Dongimport static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_ALL;
63760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70b2487f03f12dcafdb801fc0007c8df8412397f44Marco Nelissenimport static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageManager.PERMISSION_DENIED;
7629357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Blockimport static android.content.pm.PackageManager.PERMISSION_GRANTED;
77760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.content.pm.PackageParser.isApkFile;
79760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.os.Process.PACKAGE_INFO_GID;
80760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.os.Process.SYSTEM_UID;
81760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.system.OsConstants.O_CREAT;
83760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static android.system.OsConstants.O_RDWR;
84760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
85760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.internal.util.ArrayUtils.appendInt;
902d94235a343151bed9aa74e86697fa01241ea5cfJames Dongimport static com.android.server.pm.Installer.DEXOPT_PUBLIC;
912d94235a343151bed9aa74e86697fa01241ea5cfJames Dongimport static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
922d94235a343151bed9aa74e86697fa01241ea5cfJames Dongimport static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
932d94235a343151bed9aa74e86697fa01241ea5cfJames Dongimport static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
942d94235a343151bed9aa74e86697fa01241ea5cfJames Dongimport static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
9984333e0475bc911adc16417f4ca327c975cf6c36Andreas Huberimport static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
102760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.Manifest;
103760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.annotation.NonNull;
104760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.annotation.Nullable;
105760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.ActivityManager;
106760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.ActivityManagerNative;
107760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.IActivityManager;
108760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.admin.DevicePolicyManagerInternal;
109760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.admin.IDevicePolicyManager;
110760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.admin.SecurityLog;
111760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.app.backup.IBackupManager;
112760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.BroadcastReceiver;
113760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.ComponentName;
114760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.Context;
115760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.IIntentReceiver;
116760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.Intent;
117760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.IntentFilter;
118760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.IntentSender;
119760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.IntentSender.SendIntentException;
120760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.ServiceConnection;
121760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ActivityInfo;
122760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ApplicationInfo;
123760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.AppsQueryHelper;
124760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ComponentInfo;
125760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.EphemeralApplicationInfo;
126760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.EphemeralResolveInfo;
127760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.FeatureInfo;
129760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IOnPermissionsChangeListener;
130760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageDataObserver;
131760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageDeleteObserver;
132760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageDeleteObserver2;
133760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageInstallObserver2;
134760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageInstaller;
135760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageManager;
136760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageMoveObserver;
137760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IPackageStatsObserver;
138760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.InstrumentationInfo;
139760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.IntentFilterVerificationInfo;
140760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.KeySet;
141760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageCleanItem;
142760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageInfo;
143760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageInfoLite;
144760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageInstaller;
145760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageManager;
146760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageManagerInternal;
148760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageParser;
1498bcc65c753085fe3328592cceda0cf0e8f8b0a45James Dongimport android.content.pm.PackageParser.ActivityIntentInfo;
150760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageParser.PackageLite;
151760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageParser.PackageParserException;
152760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageStats;
153760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PackageUserState;
154760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ParceledListSlice;
155760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PermissionGroupInfo;
156760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.PermissionInfo;
157760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ProviderInfo;
158760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.ResolveInfo;
159377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETITimport android.content.pm.ServiceInfo;
160760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.Signature;
161760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.UserInfo;
162760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.VerifierDeviceIdentity;
163760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.pm.VerifierInfo;
164760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.content.res.Resources;
165760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.graphics.Bitmap;
166760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.hardware.display.DisplayManager;
167760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.net.Uri;
168760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Binder;
169760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Build;
170760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Bundle;
171760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Debug;
172760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Environment;
173760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Environment.UserEnvironment;
174760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.FileUtils;
175760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Handler;
176760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.IBinder;
177760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Looper;
178760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Message;
179760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Parcel;
180760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.ParcelFileDescriptor;
181760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Process;
182760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.RemoteCallbackList;
183760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.RemoteException;
184760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.ResultReceiver;
185760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.SELinux;
186760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.ServiceManager;
187760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.SystemClock;
188377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETITimport android.os.SystemProperties;
189760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.Trace;
190760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.UserHandle;
191760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.UserManager;
192760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.IMountService;
193760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.MountServiceInternal;
194760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.StorageEventListener;
195760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.StorageManager;
196760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.VolumeInfo;
197760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.os.storage.VolumeRecord;
198760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.security.KeyStore;
199760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.security.SystemKeyStore;
200760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.system.ErrnoException;
201760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.system.Os;
202760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.text.TextUtils;
203760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.text.format.DateUtils;
204760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.ArrayMap;
205760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.ArraySet;
2063856b090cd04ba5dd4a59a12430ed724d5995909Steve Blockimport android.util.AtomicFile;
207760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.DisplayMetrics;
208760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.EventLog;
209760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.ExceptionUtils;
210760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.Log;
211760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.LogPrinter;
212760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.MathUtils;
21329357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Blockimport android.util.PrintStreamPrinter;
214760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.Slog;
215760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.SparseArray;
216760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.SparseBooleanArray;
217760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.SparseIntArray;
218760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.Xml;
219760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.util.jar.StrictJarFile;
220760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport android.view.Display;
221760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
222760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.R;
223760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.annotations.GuardedBy;
224760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.app.IMediaContainerService;
225760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.app.ResolverActivity;
226760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.content.NativeLibraryHelper;
227760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.content.PackageHelper;
228760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.os.IParcelFileDescriptorFactory;
229760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.os.InstallerConnection.InstallerException;
230760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.os.SomeArgs;
231760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.os.Zygote;
232760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.telephony.CarrierAppUtils;
233760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.ArrayUtils;
234760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.FastPrintWriter;
235760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.FastXmlSerializer;
236760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.IndentingPrintWriter;
237760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.Preconditions;
238760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.internal.util.XmlUtils;
239760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.EventLogTags;
240760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.FgThread;
241760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.IntentResolver;
242760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.LocalServices;
243760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.ServiceThread;
244760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.SystemConfig;
245760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.Watchdog;
246760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.pm.PermissionsState.PermissionState;
247760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.pm.Settings.DatabaseVersion;
248760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.pm.Settings.VersionInfo;
249760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport com.android.server.storage.DeviceStorageMonitorInternal;
250760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
251aeb8fd460ed87d032b3fb8bb61e21eb542ce0f5bDave Burkeimport dalvik.system.CloseGuard;
252760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport dalvik.system.DexFile;
253760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport dalvik.system.VMRuntime;
254760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
255760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport libcore.io.IoUtils;
256760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport libcore.util.EmptyArray;
257760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
258760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport org.xmlpull.v1.XmlPullParser;
259760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport org.xmlpull.v1.XmlPullParserException;
260760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport org.xmlpull.v1.XmlSerializer;
261760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
262760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.BufferedInputStream;
263760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.BufferedOutputStream;
264760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.BufferedReader;
265760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.ByteArrayInputStream;
266760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.ByteArrayOutputStream;
267760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.File;
268760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.FileDescriptor;
269760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.FileNotFoundException;
270760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.FileOutputStream;
271760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.FileReader;
272760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.FilenameFilter;
273760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.IOException;
274760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.InputStream;
275760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.io.PrintWriter;
276760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.nio.charset.StandardCharsets;
277760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.MessageDigest;
278760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.NoSuchAlgorithmException;
279760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.PublicKey;
280760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.cert.Certificate;
281760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.cert.CertificateEncodingException;
282760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.security.cert.CertificateException;
283760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.text.SimpleDateFormat;
284760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.ArrayList;
285760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Arrays;
286760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Collection;
287760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Collections;
288760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Comparator;
289760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Date;
290760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.HashSet;
291760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Iterator;
292fa514f007bd144eb99cdd68f2fe5302a4508db28James Dongimport java.util.List;
293760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Map;
294760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Objects;
295760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.Set;
296760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.concurrent.CountDownLatch;
297760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.concurrent.TimeUnit;
298760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.concurrent.atomic.AtomicBoolean;
299760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.concurrent.atomic.AtomicInteger;
300760943b5e7a09b602aba04ec451e97662f48b0a4James Dongimport java.util.concurrent.atomic.AtomicLong;
301760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
302760943b5e7a09b602aba04ec451e97662f48b0a4James Dong/**
303760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Keep track of all those APKs everywhere.
304760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <p>
305760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Internally there are two important locks:
306760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <ul>
307760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * and other related state. It is a fine-grained lock that should only be held
309760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * momentarily, as it's one of the most contended locks in the system.
310760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * operations typically involve heavy lifting of application data on disk. Since
312760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * {@code installd} is single-threaded, and it's operations can often be slow,
313760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * this lock should never be acquired while already holding {@link #mPackages}.
314760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * holding {@link #mInstallLock}.
316760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * </ul>
317760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Many internal methods rely on the caller to hold the appropriate locks, and
318760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * this contract is expressed through method name suffixes:
319760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <ul>
3203856b090cd04ba5dd4a59a12430ed724d5995909Steve Block * <li>fooLI(): the caller must hold {@link #mInstallLock}
321760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * being modified must be frozen
323760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * </ul>
326760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <p>
327760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * Because this class is very central to the platform's security; please run all
328760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * CTS and unit tests whenever making modifications:
329760943b5e7a09b602aba04ec451e97662f48b0a4James Dong *
330760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * <pre>
331760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333760943b5e7a09b602aba04ec451e97662f48b0a4James Dong * </pre>
334760943b5e7a09b602aba04ec451e97662f48b0a4James Dong */
335760943b5e7a09b602aba04ec451e97662f48b0a4James Dongpublic class PackageManagerService extends IPackageManager.Stub {
336a5750e0dad9e90f2195ce36f2c4457fa04b2b83eMark Salyzyn    static final String TAG = "PackageManager";
337760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final boolean DEBUG_SETTINGS = false;
338760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final boolean DEBUG_PREFERRED = false;
339760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final boolean DEBUG_UPGRADE = false;
340760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_BACKUP = false;
342760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_INSTALL = false;
343760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_REMOVE = false;
344760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_BROADCASTS = false;
345760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_SHOW_INFO = false;
346760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_PACKAGE_INFO = false;
347760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_INTENT_MATCHING = false;
348760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_VERIFY = false;
350760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_FILTERS = false;
351760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
352760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    // user, but by default initialize to this.
355760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final boolean DEBUG_DEXOPT = false;
356760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
357760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_ABI_SELECTION = false;
358760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_EPHEMERAL = false;
359760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_TRIAGED_MISSING = false;
360760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final boolean DEBUG_APP_DATA = false;
361fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong
362fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong
364fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong
366fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final int RADIO_UID = Process.PHONE_UID;
367fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final int LOG_UID = Process.LOG_UID;
368fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final int NFC_UID = Process.NFC_UID;
369fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    private static final int SHELL_UID = Process.SHELL_UID;
371fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong
372fa514f007bd144eb99cdd68f2fe5302a4508db28James Dong    // Cap the size of permission trees that 3rd party apps can define
373760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
375760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    // Suffix used during package installation when copying/moving
376760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    // package apks to install directory.
377760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378760943b5e7a09b602aba04ec451e97662f48b0a4James Dong
379760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_NO_DEX = 1<<1;
380760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_FORCE_DEX = 1<<2;
381760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_NEW_INSTALL = 1<<4;
383760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_NO_PATHS = 1<<5;
384760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_UPDATE_TIME = 1<<6;
385760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_DEFER_DEX = 1<<7;
386760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_BOOTING = 1<<8;
387760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388760943b5e7a09b602aba04ec451e97662f48b0a4James Dong    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    final ServiceThread mHandlerThread;
502
503    final PackageHandler mHandler;
504
505    private final ProcessLoggingHandler mProcessLoggingHandler;
506
507    /**
508     * Messages for {@link #mHandler} that need to wait for system ready before
509     * being dispatched.
510     */
511    private ArrayList<Message> mPostSystemReadyMessages;
512
513    final int mSdkVersion = Build.VERSION.SDK_INT;
514
515    final Context mContext;
516    final boolean mFactoryTest;
517    final boolean mOnlyCore;
518    final DisplayMetrics mMetrics;
519    final int mDefParseFlags;
520    final String[] mSeparateProcesses;
521    final boolean mIsUpgrade;
522    final boolean mIsPreNUpgrade;
523
524    /** The location for ASEC container files on internal storage. */
525    final String mAsecInternalPath;
526
527    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
528    // LOCK HELD.  Can be called with mInstallLock held.
529    @GuardedBy("mInstallLock")
530    final Installer mInstaller;
531
532    /** Directory where installed third-party apps stored */
533    final File mAppInstallDir;
534    final File mEphemeralInstallDir;
535
536    /**
537     * Directory to which applications installed internally have their
538     * 32 bit native libraries copied.
539     */
540    private File mAppLib32InstallDir;
541
542    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
543    // apps.
544    final File mDrmAppPrivateInstallDir;
545
546    // ----------------------------------------------------------------
547
548    // Lock for state used when installing and doing other long running
549    // operations.  Methods that must be called with this lock held have
550    // the suffix "LI".
551    final Object mInstallLock = new Object();
552
553    // ----------------------------------------------------------------
554
555    // Keys are String (package name), values are Package.  This also serves
556    // as the lock for the global state.  Methods that must be called with
557    // this lock held have the prefix "LP".
558    @GuardedBy("mPackages")
559    final ArrayMap<String, PackageParser.Package> mPackages =
560            new ArrayMap<String, PackageParser.Package>();
561
562    final ArrayMap<String, Set<String>> mKnownCodebase =
563            new ArrayMap<String, Set<String>>();
564
565    // Tracks available target package names -> overlay package paths.
566    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
567        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
568
569    /**
570     * Tracks new system packages [received in an OTA] that we expect to
571     * find updated user-installed versions. Keys are package name, values
572     * are package location.
573     */
574    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
575    /**
576     * Tracks high priority intent filters for protected actions. During boot, certain
577     * filter actions are protected and should never be allowed to have a high priority
578     * intent filter for them. However, there is one, and only one exception -- the
579     * setup wizard. It must be able to define a high priority intent filter for these
580     * actions to ensure there are no escapes from the wizard. We need to delay processing
581     * of these during boot as we need to look at all of the system packages in order
582     * to know which component is the setup wizard.
583     */
584    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
585    /**
586     * Whether or not processing protected filters should be deferred.
587     */
588    private boolean mDeferProtectedFilters = true;
589
590    /**
591     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
592     */
593    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
594    /**
595     * Whether or not system app permissions should be promoted from install to runtime.
596     */
597    boolean mPromoteSystemApps;
598
599    @GuardedBy("mPackages")
600    final Settings mSettings;
601
602    /**
603     * Set of package names that are currently "frozen", which means active
604     * surgery is being done on the code/data for that package. The platform
605     * will refuse to launch frozen packages to avoid race conditions.
606     *
607     * @see PackageFreezer
608     */
609    @GuardedBy("mPackages")
610    final ArraySet<String> mFrozenPackages = new ArraySet<>();
611
612    boolean mRestoredSettings;
613
614    // System configuration read by SystemConfig.
615    final int[] mGlobalGids;
616    final SparseArray<ArraySet<String>> mSystemPermissions;
617    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
618
619    // If mac_permissions.xml was found for seinfo labeling.
620    boolean mFoundPolicyFile;
621
622    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
623
624    public static final class SharedLibraryEntry {
625        public final String path;
626        public final String apk;
627
628        SharedLibraryEntry(String _path, String _apk) {
629            path = _path;
630            apk = _apk;
631        }
632    }
633
634    // Currently known shared libraries.
635    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
636            new ArrayMap<String, SharedLibraryEntry>();
637
638    // All available activities, for your resolving pleasure.
639    final ActivityIntentResolver mActivities =
640            new ActivityIntentResolver();
641
642    // All available receivers, for your resolving pleasure.
643    final ActivityIntentResolver mReceivers =
644            new ActivityIntentResolver();
645
646    // All available services, for your resolving pleasure.
647    final ServiceIntentResolver mServices = new ServiceIntentResolver();
648
649    // All available providers, for your resolving pleasure.
650    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
651
652    // Mapping from provider base names (first directory in content URI codePath)
653    // to the provider information.
654    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
655            new ArrayMap<String, PackageParser.Provider>();
656
657    // Mapping from instrumentation class names to info about them.
658    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
659            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
660
661    // Mapping from permission names to info about them.
662    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
663            new ArrayMap<String, PackageParser.PermissionGroup>();
664
665    // Packages whose data we have transfered into another package, thus
666    // should no longer exist.
667    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
668
669    // Broadcast actions that are only available to the system.
670    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
671
672    /** List of packages waiting for verification. */
673    final SparseArray<PackageVerificationState> mPendingVerification
674            = new SparseArray<PackageVerificationState>();
675
676    /** Set of packages associated with each app op permission. */
677    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
678
679    final PackageInstallerService mInstallerService;
680
681    private final PackageDexOptimizer mPackageDexOptimizer;
682
683    private AtomicInteger mNextMoveId = new AtomicInteger();
684    private final MoveCallbacks mMoveCallbacks;
685
686    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
687
688    // Cache of users who need badging.
689    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
690
691    /** Token for keys in mPendingVerification. */
692    private int mPendingVerificationToken = 0;
693
694    volatile boolean mSystemReady;
695    volatile boolean mSafeMode;
696    volatile boolean mHasSystemUidErrors;
697
698    ApplicationInfo mAndroidApplication;
699    final ActivityInfo mResolveActivity = new ActivityInfo();
700    final ResolveInfo mResolveInfo = new ResolveInfo();
701    ComponentName mResolveComponentName;
702    PackageParser.Package mPlatformPackage;
703    ComponentName mCustomResolverComponentName;
704
705    boolean mResolverReplaced = false;
706
707    private final @Nullable ComponentName mIntentFilterVerifierComponent;
708    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
709
710    private int mIntentFilterVerificationToken = 0;
711
712    /** Component that knows whether or not an ephemeral application exists */
713    final ComponentName mEphemeralResolverComponent;
714    /** The service connection to the ephemeral resolver */
715    final EphemeralResolverConnection mEphemeralResolverConnection;
716
717    /** Component used to install ephemeral applications */
718    final ComponentName mEphemeralInstallerComponent;
719    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
720    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
721
722    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
723            = new SparseArray<IntentFilterVerificationState>();
724
725    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
726            new DefaultPermissionGrantPolicy(this);
727
728    // List of packages names to keep cached, even if they are uninstalled for all users
729    private List<String> mKeepUninstalledPackages;
730
731    private static class IFVerificationParams {
732        PackageParser.Package pkg;
733        boolean replacing;
734        int userId;
735        int verifierUid;
736
737        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
738                int _userId, int _verifierUid) {
739            pkg = _pkg;
740            replacing = _replacing;
741            userId = _userId;
742            replacing = _replacing;
743            verifierUid = _verifierUid;
744        }
745    }
746
747    private interface IntentFilterVerifier<T extends IntentFilter> {
748        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
749                                               T filter, String packageName);
750        void startVerifications(int userId);
751        void receiveVerificationResponse(int verificationId);
752    }
753
754    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
755        private Context mContext;
756        private ComponentName mIntentFilterVerifierComponent;
757        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
758
759        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
760            mContext = context;
761            mIntentFilterVerifierComponent = verifierComponent;
762        }
763
764        private String getDefaultScheme() {
765            return IntentFilter.SCHEME_HTTPS;
766        }
767
768        @Override
769        public void startVerifications(int userId) {
770            // Launch verifications requests
771            int count = mCurrentIntentFilterVerifications.size();
772            for (int n=0; n<count; n++) {
773                int verificationId = mCurrentIntentFilterVerifications.get(n);
774                final IntentFilterVerificationState ivs =
775                        mIntentFilterVerificationStates.get(verificationId);
776
777                String packageName = ivs.getPackageName();
778
779                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
780                final int filterCount = filters.size();
781                ArraySet<String> domainsSet = new ArraySet<>();
782                for (int m=0; m<filterCount; m++) {
783                    PackageParser.ActivityIntentInfo filter = filters.get(m);
784                    domainsSet.addAll(filter.getHostsList());
785                }
786                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
787                synchronized (mPackages) {
788                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
789                            packageName, domainsList) != null) {
790                        scheduleWriteSettingsLocked();
791                    }
792                }
793                sendVerificationRequest(userId, verificationId, ivs);
794            }
795            mCurrentIntentFilterVerifications.clear();
796        }
797
798        private void sendVerificationRequest(int userId, int verificationId,
799                IntentFilterVerificationState ivs) {
800
801            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
802            verificationIntent.putExtra(
803                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
804                    verificationId);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
807                    getDefaultScheme());
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
810                    ivs.getHostsString());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
813                    ivs.getPackageName());
814            verificationIntent.setComponent(mIntentFilterVerifierComponent);
815            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
816
817            UserHandle user = new UserHandle(userId);
818            mContext.sendBroadcastAsUser(verificationIntent, user);
819            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
820                    "Sending IntentFilter verification broadcast");
821        }
822
823        public void receiveVerificationResponse(int verificationId) {
824            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
825
826            final boolean verified = ivs.isVerified();
827
828            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
829            final int count = filters.size();
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.i(TAG, "Received verification response " + verificationId
832                        + " for " + count + " filters, verified=" + verified);
833            }
834            for (int n=0; n<count; n++) {
835                PackageParser.ActivityIntentInfo filter = filters.get(n);
836                filter.setVerified(verified);
837
838                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
839                        + " verified with result:" + verified + " and hosts:"
840                        + ivs.getHostsString());
841            }
842
843            mIntentFilterVerificationStates.remove(verificationId);
844
845            final String packageName = ivs.getPackageName();
846            IntentFilterVerificationInfo ivi = null;
847
848            synchronized (mPackages) {
849                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
850            }
851            if (ivi == null) {
852                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
853                        + verificationId + " packageName:" + packageName);
854                return;
855            }
856            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
857                    "Updating IntentFilterVerificationInfo for package " + packageName
858                            +" verificationId:" + verificationId);
859
860            synchronized (mPackages) {
861                if (verified) {
862                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
863                } else {
864                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
865                }
866                scheduleWriteSettingsLocked();
867
868                final int userId = ivs.getUserId();
869                if (userId != UserHandle.USER_ALL) {
870                    final int userStatus =
871                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
872
873                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
874                    boolean needUpdate = false;
875
876                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
877                    // already been set by the User thru the Disambiguation dialog
878                    switch (userStatus) {
879                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
880                            if (verified) {
881                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
882                            } else {
883                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
884                            }
885                            needUpdate = true;
886                            break;
887
888                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
889                            if (verified) {
890                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
891                                needUpdate = true;
892                            }
893                            break;
894
895                        default:
896                            // Nothing to do
897                    }
898
899                    if (needUpdate) {
900                        mSettings.updateIntentFilterVerificationStatusLPw(
901                                packageName, updatedStatus, userId);
902                        scheduleWritePackageRestrictionsLocked(userId);
903                    }
904                }
905            }
906        }
907
908        @Override
909        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
910                    ActivityIntentInfo filter, String packageName) {
911            if (!hasValidDomains(filter)) {
912                return false;
913            }
914            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
915            if (ivs == null) {
916                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
917                        packageName);
918            }
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
921            }
922            ivs.addFilter(filter);
923            return true;
924        }
925
926        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
927                int userId, int verificationId, String packageName) {
928            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
929                    verifierUid, userId, packageName);
930            ivs.setPendingState();
931            synchronized (mPackages) {
932                mIntentFilterVerificationStates.append(verificationId, ivs);
933                mCurrentIntentFilterVerifications.add(verificationId);
934            }
935            return ivs;
936        }
937    }
938
939    private static boolean hasValidDomains(ActivityIntentInfo filter) {
940        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
941                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
942                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
943    }
944
945    // Set of pending broadcasts for aggregating enable/disable of components.
946    static class PendingPackageBroadcasts {
947        // for each user id, a map of <package name -> components within that package>
948        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
949
950        public PendingPackageBroadcasts() {
951            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
952        }
953
954        public ArrayList<String> get(int userId, String packageName) {
955            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
956            return packages.get(packageName);
957        }
958
959        public void put(int userId, String packageName, ArrayList<String> components) {
960            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
961            packages.put(packageName, components);
962        }
963
964        public void remove(int userId, String packageName) {
965            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
966            if (packages != null) {
967                packages.remove(packageName);
968            }
969        }
970
971        public void remove(int userId) {
972            mUidMap.remove(userId);
973        }
974
975        public int userIdCount() {
976            return mUidMap.size();
977        }
978
979        public int userIdAt(int n) {
980            return mUidMap.keyAt(n);
981        }
982
983        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
984            return mUidMap.get(userId);
985        }
986
987        public int size() {
988            // total number of pending broadcast entries across all userIds
989            int num = 0;
990            for (int i = 0; i< mUidMap.size(); i++) {
991                num += mUidMap.valueAt(i).size();
992            }
993            return num;
994        }
995
996        public void clear() {
997            mUidMap.clear();
998        }
999
1000        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1001            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1002            if (map == null) {
1003                map = new ArrayMap<String, ArrayList<String>>();
1004                mUidMap.put(userId, map);
1005            }
1006            return map;
1007        }
1008    }
1009    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1010
1011    // Service Connection to remote media container service to copy
1012    // package uri's from external media onto secure containers
1013    // or internal storage.
1014    private IMediaContainerService mContainerService = null;
1015
1016    static final int SEND_PENDING_BROADCAST = 1;
1017    static final int MCS_BOUND = 3;
1018    static final int END_COPY = 4;
1019    static final int INIT_COPY = 5;
1020    static final int MCS_UNBIND = 6;
1021    static final int START_CLEANING_PACKAGE = 7;
1022    static final int FIND_INSTALL_LOC = 8;
1023    static final int POST_INSTALL = 9;
1024    static final int MCS_RECONNECT = 10;
1025    static final int MCS_GIVE_UP = 11;
1026    static final int UPDATED_MEDIA_STATUS = 12;
1027    static final int WRITE_SETTINGS = 13;
1028    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1029    static final int PACKAGE_VERIFIED = 15;
1030    static final int CHECK_PENDING_VERIFICATION = 16;
1031    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1032    static final int INTENT_FILTER_VERIFIED = 18;
1033
1034    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1035
1036    // Delay time in millisecs
1037    static final int BROADCAST_DELAY = 10 * 1000;
1038
1039    static UserManagerService sUserManager;
1040
1041    // Stores a list of users whose package restrictions file needs to be updated
1042    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1043
1044    final private DefaultContainerConnection mDefContainerConn =
1045            new DefaultContainerConnection();
1046    class DefaultContainerConnection implements ServiceConnection {
1047        public void onServiceConnected(ComponentName name, IBinder service) {
1048            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1049            IMediaContainerService imcs =
1050                IMediaContainerService.Stub.asInterface(service);
1051            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1052        }
1053
1054        public void onServiceDisconnected(ComponentName name) {
1055            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1056        }
1057    }
1058
1059    // Recordkeeping of restore-after-install operations that are currently in flight
1060    // between the Package Manager and the Backup Manager
1061    static class PostInstallData {
1062        public InstallArgs args;
1063        public PackageInstalledInfo res;
1064
1065        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1066            args = _a;
1067            res = _r;
1068        }
1069    }
1070
1071    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1072    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1073
1074    // XML tags for backup/restore of various bits of state
1075    private static final String TAG_PREFERRED_BACKUP = "pa";
1076    private static final String TAG_DEFAULT_APPS = "da";
1077    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1078
1079    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1080    private static final String TAG_ALL_GRANTS = "rt-grants";
1081    private static final String TAG_GRANT = "grant";
1082    private static final String ATTR_PACKAGE_NAME = "pkg";
1083
1084    private static final String TAG_PERMISSION = "perm";
1085    private static final String ATTR_PERMISSION_NAME = "name";
1086    private static final String ATTR_IS_GRANTED = "g";
1087    private static final String ATTR_USER_SET = "set";
1088    private static final String ATTR_USER_FIXED = "fixed";
1089    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1090
1091    // System/policy permission grants are not backed up
1092    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1093            FLAG_PERMISSION_POLICY_FIXED
1094            | FLAG_PERMISSION_SYSTEM_FIXED
1095            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1096
1097    // And we back up these user-adjusted states
1098    private static final int USER_RUNTIME_GRANT_MASK =
1099            FLAG_PERMISSION_USER_SET
1100            | FLAG_PERMISSION_USER_FIXED
1101            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1102
1103    final @Nullable String mRequiredVerifierPackage;
1104    final @NonNull String mRequiredInstallerPackage;
1105    final @Nullable String mSetupWizardPackage;
1106    final @NonNull String mServicesSystemSharedLibraryPackageName;
1107    final @NonNull String mSharedSystemSharedLibraryPackageName;
1108
1109    private final PackageUsage mPackageUsage = new PackageUsage();
1110
1111    private class PackageUsage {
1112        private static final int WRITE_INTERVAL
1113            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1114
1115        private final Object mFileLock = new Object();
1116        private final AtomicLong mLastWritten = new AtomicLong(0);
1117        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1118
1119        private boolean mIsHistoricalPackageUsageAvailable = true;
1120
1121        boolean isHistoricalPackageUsageAvailable() {
1122            return mIsHistoricalPackageUsageAvailable;
1123        }
1124
1125        void write(boolean force) {
1126            if (force) {
1127                writeInternal();
1128                return;
1129            }
1130            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1131                && !DEBUG_DEXOPT) {
1132                return;
1133            }
1134            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1135                new Thread("PackageUsage_DiskWriter") {
1136                    @Override
1137                    public void run() {
1138                        try {
1139                            writeInternal();
1140                        } finally {
1141                            mBackgroundWriteRunning.set(false);
1142                        }
1143                    }
1144                }.start();
1145            }
1146        }
1147
1148        private void writeInternal() {
1149            synchronized (mPackages) {
1150                synchronized (mFileLock) {
1151                    AtomicFile file = getFile();
1152                    FileOutputStream f = null;
1153                    try {
1154                        f = file.startWrite();
1155                        BufferedOutputStream out = new BufferedOutputStream(f);
1156                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1157                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1158                        StringBuilder sb = new StringBuilder();
1159
1160                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1161                        sb.append('\n');
1162                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1163
1164                        for (PackageParser.Package pkg : mPackages.values()) {
1165                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1166                                continue;
1167                            }
1168                            sb.setLength(0);
1169                            sb.append(pkg.packageName);
1170                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1171                                sb.append(' ');
1172                                sb.append(usageTimeInMillis);
1173                            }
1174                            sb.append('\n');
1175                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1176                        }
1177                        out.flush();
1178                        file.finishWrite(f);
1179                    } catch (IOException e) {
1180                        if (f != null) {
1181                            file.failWrite(f);
1182                        }
1183                        Log.e(TAG, "Failed to write package usage times", e);
1184                    }
1185                }
1186            }
1187            mLastWritten.set(SystemClock.elapsedRealtime());
1188        }
1189
1190        void readLP() {
1191            synchronized (mFileLock) {
1192                AtomicFile file = getFile();
1193                BufferedInputStream in = null;
1194                try {
1195                    in = new BufferedInputStream(file.openRead());
1196                    StringBuffer sb = new StringBuffer();
1197
1198                    String firstLine = readLine(in, sb);
1199                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1200                        readVersion1LP(in, sb);
1201                    } else {
1202                        readVersion0LP(in, sb, firstLine);
1203                    }
1204                } catch (FileNotFoundException expected) {
1205                    mIsHistoricalPackageUsageAvailable = false;
1206                } catch (IOException e) {
1207                    Log.w(TAG, "Failed to read package usage times", e);
1208                } finally {
1209                    IoUtils.closeQuietly(in);
1210                }
1211            }
1212            mLastWritten.set(SystemClock.elapsedRealtime());
1213        }
1214
1215        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1216                throws IOException {
1217            // Initial version of the file had no version number and stored one
1218            // package-timestamp pair per line.
1219            // Note that the first line has already been read from the InputStream.
1220            String line = firstLine;
1221            while (true) {
1222                if (line == null) {
1223                    break;
1224                }
1225
1226                String[] tokens = line.split(" ");
1227                if (tokens.length != 2) {
1228                    throw new IOException("Failed to parse " + line +
1229                            " as package-timestamp pair.");
1230                }
1231
1232                String packageName = tokens[0];
1233                PackageParser.Package pkg = mPackages.get(packageName);
1234                if (pkg == null) {
1235                    continue;
1236                }
1237
1238                long timestamp = parseAsLong(tokens[1]);
1239                for (int reason = 0;
1240                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1241                        reason++) {
1242                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1243                }
1244
1245                line = readLine(in, sb);
1246            }
1247        }
1248
1249        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1250            // Version 1 of the file started with the corresponding version
1251            // number and then stored a package name and eight timestamps per line.
1252            String line;
1253            while ((line = readLine(in, sb)) != null) {
1254                String[] tokens = line.split(" ");
1255                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1256                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1257                }
1258
1259                String packageName = tokens[0];
1260                PackageParser.Package pkg = mPackages.get(packageName);
1261                if (pkg == null) {
1262                    continue;
1263                }
1264
1265                for (int reason = 0;
1266                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1267                        reason++) {
1268                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1269                }
1270            }
1271        }
1272
1273        private long parseAsLong(String token) throws IOException {
1274            try {
1275                return Long.parseLong(token);
1276            } catch (NumberFormatException e) {
1277                throw new IOException("Failed to parse " + token + " as a long.", e);
1278            }
1279        }
1280
1281        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1282            return readToken(in, sb, '\n');
1283        }
1284
1285        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1286                throws IOException {
1287            sb.setLength(0);
1288            while (true) {
1289                int ch = in.read();
1290                if (ch == -1) {
1291                    if (sb.length() == 0) {
1292                        return null;
1293                    }
1294                    throw new IOException("Unexpected EOF");
1295                }
1296                if (ch == endOfToken) {
1297                    return sb.toString();
1298                }
1299                sb.append((char)ch);
1300            }
1301        }
1302
1303        private AtomicFile getFile() {
1304            File dataDir = Environment.getDataDirectory();
1305            File systemDir = new File(dataDir, "system");
1306            File fname = new File(systemDir, "package-usage.list");
1307            return new AtomicFile(fname);
1308        }
1309
1310        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1311        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1312    }
1313
1314    class PackageHandler extends Handler {
1315        private boolean mBound = false;
1316        final ArrayList<HandlerParams> mPendingInstalls =
1317            new ArrayList<HandlerParams>();
1318
1319        private boolean connectToService() {
1320            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1321                    " DefaultContainerService");
1322            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1323            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1324            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1325                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1326                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1327                mBound = true;
1328                return true;
1329            }
1330            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1331            return false;
1332        }
1333
1334        private void disconnectService() {
1335            mContainerService = null;
1336            mBound = false;
1337            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1338            mContext.unbindService(mDefContainerConn);
1339            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1340        }
1341
1342        PackageHandler(Looper looper) {
1343            super(looper);
1344        }
1345
1346        public void handleMessage(Message msg) {
1347            try {
1348                doHandleMessage(msg);
1349            } finally {
1350                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351            }
1352        }
1353
1354        void doHandleMessage(Message msg) {
1355            switch (msg.what) {
1356                case INIT_COPY: {
1357                    HandlerParams params = (HandlerParams) msg.obj;
1358                    int idx = mPendingInstalls.size();
1359                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1360                    // If a bind was already initiated we dont really
1361                    // need to do anything. The pending install
1362                    // will be processed later on.
1363                    if (!mBound) {
1364                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1365                                System.identityHashCode(mHandler));
1366                        // If this is the only one pending we might
1367                        // have to bind to the service again.
1368                        if (!connectToService()) {
1369                            Slog.e(TAG, "Failed to bind to media container service");
1370                            params.serviceError();
1371                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1372                                    System.identityHashCode(mHandler));
1373                            if (params.traceMethod != null) {
1374                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1375                                        params.traceCookie);
1376                            }
1377                            return;
1378                        } else {
1379                            // Once we bind to the service, the first
1380                            // pending request will be processed.
1381                            mPendingInstalls.add(idx, params);
1382                        }
1383                    } else {
1384                        mPendingInstalls.add(idx, params);
1385                        // Already bound to the service. Just make
1386                        // sure we trigger off processing the first request.
1387                        if (idx == 0) {
1388                            mHandler.sendEmptyMessage(MCS_BOUND);
1389                        }
1390                    }
1391                    break;
1392                }
1393                case MCS_BOUND: {
1394                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1395                    if (msg.obj != null) {
1396                        mContainerService = (IMediaContainerService) msg.obj;
1397                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1398                                System.identityHashCode(mHandler));
1399                    }
1400                    if (mContainerService == null) {
1401                        if (!mBound) {
1402                            // Something seriously wrong since we are not bound and we are not
1403                            // waiting for connection. Bail out.
1404                            Slog.e(TAG, "Cannot bind to media container service");
1405                            for (HandlerParams params : mPendingInstalls) {
1406                                // Indicate service bind error
1407                                params.serviceError();
1408                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1409                                        System.identityHashCode(params));
1410                                if (params.traceMethod != null) {
1411                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1412                                            params.traceMethod, params.traceCookie);
1413                                }
1414                                return;
1415                            }
1416                            mPendingInstalls.clear();
1417                        } else {
1418                            Slog.w(TAG, "Waiting to connect to media container service");
1419                        }
1420                    } else if (mPendingInstalls.size() > 0) {
1421                        HandlerParams params = mPendingInstalls.get(0);
1422                        if (params != null) {
1423                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1424                                    System.identityHashCode(params));
1425                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1426                            if (params.startCopy()) {
1427                                // We are done...  look for more work or to
1428                                // go idle.
1429                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1430                                        "Checking for more work or unbind...");
1431                                // Delete pending install
1432                                if (mPendingInstalls.size() > 0) {
1433                                    mPendingInstalls.remove(0);
1434                                }
1435                                if (mPendingInstalls.size() == 0) {
1436                                    if (mBound) {
1437                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1438                                                "Posting delayed MCS_UNBIND");
1439                                        removeMessages(MCS_UNBIND);
1440                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1441                                        // Unbind after a little delay, to avoid
1442                                        // continual thrashing.
1443                                        sendMessageDelayed(ubmsg, 10000);
1444                                    }
1445                                } else {
1446                                    // There are more pending requests in queue.
1447                                    // Just post MCS_BOUND message to trigger processing
1448                                    // of next pending install.
1449                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1450                                            "Posting MCS_BOUND for next work");
1451                                    mHandler.sendEmptyMessage(MCS_BOUND);
1452                                }
1453                            }
1454                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1455                        }
1456                    } else {
1457                        // Should never happen ideally.
1458                        Slog.w(TAG, "Empty queue");
1459                    }
1460                    break;
1461                }
1462                case MCS_RECONNECT: {
1463                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1464                    if (mPendingInstalls.size() > 0) {
1465                        if (mBound) {
1466                            disconnectService();
1467                        }
1468                        if (!connectToService()) {
1469                            Slog.e(TAG, "Failed to bind to media container service");
1470                            for (HandlerParams params : mPendingInstalls) {
1471                                // Indicate service bind error
1472                                params.serviceError();
1473                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1474                                        System.identityHashCode(params));
1475                            }
1476                            mPendingInstalls.clear();
1477                        }
1478                    }
1479                    break;
1480                }
1481                case MCS_UNBIND: {
1482                    // If there is no actual work left, then time to unbind.
1483                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1484
1485                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1486                        if (mBound) {
1487                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1488
1489                            disconnectService();
1490                        }
1491                    } else if (mPendingInstalls.size() > 0) {
1492                        // There are more pending requests in queue.
1493                        // Just post MCS_BOUND message to trigger processing
1494                        // of next pending install.
1495                        mHandler.sendEmptyMessage(MCS_BOUND);
1496                    }
1497
1498                    break;
1499                }
1500                case MCS_GIVE_UP: {
1501                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1502                    HandlerParams params = mPendingInstalls.remove(0);
1503                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1504                            System.identityHashCode(params));
1505                    break;
1506                }
1507                case SEND_PENDING_BROADCAST: {
1508                    String packages[];
1509                    ArrayList<String> components[];
1510                    int size = 0;
1511                    int uids[];
1512                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1513                    synchronized (mPackages) {
1514                        if (mPendingBroadcasts == null) {
1515                            return;
1516                        }
1517                        size = mPendingBroadcasts.size();
1518                        if (size <= 0) {
1519                            // Nothing to be done. Just return
1520                            return;
1521                        }
1522                        packages = new String[size];
1523                        components = new ArrayList[size];
1524                        uids = new int[size];
1525                        int i = 0;  // filling out the above arrays
1526
1527                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1528                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1529                            Iterator<Map.Entry<String, ArrayList<String>>> it
1530                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1531                                            .entrySet().iterator();
1532                            while (it.hasNext() && i < size) {
1533                                Map.Entry<String, ArrayList<String>> ent = it.next();
1534                                packages[i] = ent.getKey();
1535                                components[i] = ent.getValue();
1536                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1537                                uids[i] = (ps != null)
1538                                        ? UserHandle.getUid(packageUserId, ps.appId)
1539                                        : -1;
1540                                i++;
1541                            }
1542                        }
1543                        size = i;
1544                        mPendingBroadcasts.clear();
1545                    }
1546                    // Send broadcasts
1547                    for (int i = 0; i < size; i++) {
1548                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1549                    }
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1551                    break;
1552                }
1553                case START_CLEANING_PACKAGE: {
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1555                    final String packageName = (String)msg.obj;
1556                    final int userId = msg.arg1;
1557                    final boolean andCode = msg.arg2 != 0;
1558                    synchronized (mPackages) {
1559                        if (userId == UserHandle.USER_ALL) {
1560                            int[] users = sUserManager.getUserIds();
1561                            for (int user : users) {
1562                                mSettings.addPackageToCleanLPw(
1563                                        new PackageCleanItem(user, packageName, andCode));
1564                            }
1565                        } else {
1566                            mSettings.addPackageToCleanLPw(
1567                                    new PackageCleanItem(userId, packageName, andCode));
1568                        }
1569                    }
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1571                    startCleaningPackages();
1572                } break;
1573                case POST_INSTALL: {
1574                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1575
1576                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1577                    mRunningInstalls.delete(msg.arg1);
1578
1579                    if (data != null) {
1580                        InstallArgs args = data.args;
1581                        PackageInstalledInfo parentRes = data.res;
1582
1583                        final boolean grantPermissions = (args.installFlags
1584                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1585                        final boolean killApp = (args.installFlags
1586                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1587                        final String[] grantedPermissions = args.installGrantPermissions;
1588
1589                        // Handle the parent package
1590                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1591                                grantedPermissions, args.observer);
1592
1593                        // Handle the child packages
1594                        final int childCount = (parentRes.addedChildPackages != null)
1595                                ? parentRes.addedChildPackages.size() : 0;
1596                        for (int i = 0; i < childCount; i++) {
1597                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1598                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1599                                    grantedPermissions, args.observer);
1600                        }
1601
1602                        // Log tracing if needed
1603                        if (args.traceMethod != null) {
1604                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1605                                    args.traceCookie);
1606                        }
1607                    } else {
1608                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1609                    }
1610
1611                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1612                } break;
1613                case UPDATED_MEDIA_STATUS: {
1614                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1615                    boolean reportStatus = msg.arg1 == 1;
1616                    boolean doGc = msg.arg2 == 1;
1617                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1618                    if (doGc) {
1619                        // Force a gc to clear up stale containers.
1620                        Runtime.getRuntime().gc();
1621                    }
1622                    if (msg.obj != null) {
1623                        @SuppressWarnings("unchecked")
1624                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1625                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1626                        // Unload containers
1627                        unloadAllContainers(args);
1628                    }
1629                    if (reportStatus) {
1630                        try {
1631                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1632                            PackageHelper.getMountService().finishMediaUpdate();
1633                        } catch (RemoteException e) {
1634                            Log.e(TAG, "MountService not running?");
1635                        }
1636                    }
1637                } break;
1638                case WRITE_SETTINGS: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    synchronized (mPackages) {
1641                        removeMessages(WRITE_SETTINGS);
1642                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1643                        mSettings.writeLPr();
1644                        mDirtyUsers.clear();
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                } break;
1648                case WRITE_PACKAGE_RESTRICTIONS: {
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1650                    synchronized (mPackages) {
1651                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1652                        for (int userId : mDirtyUsers) {
1653                            mSettings.writePackageRestrictionsLPr(userId);
1654                        }
1655                        mDirtyUsers.clear();
1656                    }
1657                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1658                } break;
1659                case CHECK_PENDING_VERIFICATION: {
1660                    final int verificationId = msg.arg1;
1661                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1662
1663                    if ((state != null) && !state.timeoutExtended()) {
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        Slog.i(TAG, "Verification timed out for " + originUri);
1668                        mPendingVerification.remove(verificationId);
1669
1670                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1671
1672                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1673                            Slog.i(TAG, "Continuing with installation of " + originUri);
1674                            state.setVerifierResponse(Binder.getCallingUid(),
1675                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1676                            broadcastPackageVerified(verificationId, originUri,
1677                                    PackageManager.VERIFICATION_ALLOW,
1678                                    state.getInstallArgs().getUser());
1679                            try {
1680                                ret = args.copyApk(mContainerService, true);
1681                            } catch (RemoteException e) {
1682                                Slog.e(TAG, "Could not contact the ContainerService");
1683                            }
1684                        } else {
1685                            broadcastPackageVerified(verificationId, originUri,
1686                                    PackageManager.VERIFICATION_REJECT,
1687                                    state.getInstallArgs().getUser());
1688                        }
1689
1690                        Trace.asyncTraceEnd(
1691                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1692
1693                        processPendingInstall(args, ret);
1694                        mHandler.sendEmptyMessage(MCS_UNBIND);
1695                    }
1696                    break;
1697                }
1698                case PACKAGE_VERIFIED: {
1699                    final int verificationId = msg.arg1;
1700
1701                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1702                    if (state == null) {
1703                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1708
1709                    state.setVerifierResponse(response.callerUid, response.code);
1710
1711                    if (state.isVerificationComplete()) {
1712                        mPendingVerification.remove(verificationId);
1713
1714                        final InstallArgs args = state.getInstallArgs();
1715                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1716
1717                        int ret;
1718                        if (state.isInstallAllowed()) {
1719                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1720                            broadcastPackageVerified(verificationId, originUri,
1721                                    response.code, state.getInstallArgs().getUser());
1722                            try {
1723                                ret = args.copyApk(mContainerService, true);
1724                            } catch (RemoteException e) {
1725                                Slog.e(TAG, "Could not contact the ContainerService");
1726                            }
1727                        } else {
1728                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1729                        }
1730
1731                        Trace.asyncTraceEnd(
1732                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1733
1734                        processPendingInstall(args, ret);
1735                        mHandler.sendEmptyMessage(MCS_UNBIND);
1736                    }
1737
1738                    break;
1739                }
1740                case START_INTENT_FILTER_VERIFICATIONS: {
1741                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1742                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1743                            params.replacing, params.pkg);
1744                    break;
1745                }
1746                case INTENT_FILTER_VERIFIED: {
1747                    final int verificationId = msg.arg1;
1748
1749                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1750                            verificationId);
1751                    if (state == null) {
1752                        Slog.w(TAG, "Invalid IntentFilter verification token "
1753                                + verificationId + " received");
1754                        break;
1755                    }
1756
1757                    final int userId = state.getUserId();
1758
1759                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1760                            "Processing IntentFilter verification with token:"
1761                            + verificationId + " and userId:" + userId);
1762
1763                    final IntentFilterVerificationResponse response =
1764                            (IntentFilterVerificationResponse) msg.obj;
1765
1766                    state.setVerifierResponse(response.callerUid, response.code);
1767
1768                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1769                            "IntentFilter verification with token:" + verificationId
1770                            + " and userId:" + userId
1771                            + " is settings verifier response with response code:"
1772                            + response.code);
1773
1774                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1775                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1776                                + response.getFailedDomainsString());
1777                    }
1778
1779                    if (state.isVerificationComplete()) {
1780                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1781                    } else {
1782                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1783                                "IntentFilter verification with token:" + verificationId
1784                                + " was not said to be complete");
1785                    }
1786
1787                    break;
1788                }
1789            }
1790        }
1791    }
1792
1793    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1794            boolean killApp, String[] grantedPermissions,
1795            IPackageInstallObserver2 installObserver) {
1796        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1797            // Send the removed broadcasts
1798            if (res.removedInfo != null) {
1799                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1800            }
1801
1802            // Now that we successfully installed the package, grant runtime
1803            // permissions if requested before broadcasting the install.
1804            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1805                    >= Build.VERSION_CODES.M) {
1806                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1807            }
1808
1809            final boolean update = res.removedInfo != null
1810                    && res.removedInfo.removedPackage != null;
1811
1812            // If this is the first time we have child packages for a disabled privileged
1813            // app that had no children, we grant requested runtime permissions to the new
1814            // children if the parent on the system image had them already granted.
1815            if (res.pkg.parentPackage != null) {
1816                synchronized (mPackages) {
1817                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1818                }
1819            }
1820
1821            synchronized (mPackages) {
1822                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1823            }
1824
1825            final String packageName = res.pkg.applicationInfo.packageName;
1826            Bundle extras = new Bundle(1);
1827            extras.putInt(Intent.EXTRA_UID, res.uid);
1828
1829            // Determine the set of users who are adding this package for
1830            // the first time vs. those who are seeing an update.
1831            int[] firstUsers = EMPTY_INT_ARRAY;
1832            int[] updateUsers = EMPTY_INT_ARRAY;
1833            if (res.origUsers == null || res.origUsers.length == 0) {
1834                firstUsers = res.newUsers;
1835            } else {
1836                for (int newUser : res.newUsers) {
1837                    boolean isNew = true;
1838                    for (int origUser : res.origUsers) {
1839                        if (origUser == newUser) {
1840                            isNew = false;
1841                            break;
1842                        }
1843                    }
1844                    if (isNew) {
1845                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1846                    } else {
1847                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1848                    }
1849                }
1850            }
1851
1852            // Send installed broadcasts if the install/update is not ephemeral
1853            if (!isEphemeral(res.pkg)) {
1854                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1855
1856                // Send added for users that see the package for the first time
1857                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1858                        extras, 0 /*flags*/, null /*targetPackage*/,
1859                        null /*finishedReceiver*/, firstUsers);
1860
1861                // Send added for users that don't see the package for the first time
1862                if (update) {
1863                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1864                }
1865                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1866                        extras, 0 /*flags*/, null /*targetPackage*/,
1867                        null /*finishedReceiver*/, updateUsers);
1868
1869                // Send replaced for users that don't see the package for the first time
1870                if (update) {
1871                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1872                            packageName, extras, 0 /*flags*/,
1873                            null /*targetPackage*/, null /*finishedReceiver*/,
1874                            updateUsers);
1875                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1876                            null /*package*/, null /*extras*/, 0 /*flags*/,
1877                            packageName /*targetPackage*/,
1878                            null /*finishedReceiver*/, updateUsers);
1879                }
1880
1881                // Send broadcast package appeared if forward locked/external for all users
1882                // treat asec-hosted packages like removable media on upgrade
1883                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1884                    if (DEBUG_INSTALL) {
1885                        Slog.i(TAG, "upgrading pkg " + res.pkg
1886                                + " is ASEC-hosted -> AVAILABLE");
1887                    }
1888                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1889                    ArrayList<String> pkgList = new ArrayList<>(1);
1890                    pkgList.add(packageName);
1891                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1892                }
1893            }
1894
1895            // Work that needs to happen on first install within each user
1896            if (firstUsers != null && firstUsers.length > 0) {
1897                synchronized (mPackages) {
1898                    for (int userId : firstUsers) {
1899                        // If this app is a browser and it's newly-installed for some
1900                        // users, clear any default-browser state in those users. The
1901                        // app's nature doesn't depend on the user, so we can just check
1902                        // its browser nature in any user and generalize.
1903                        if (packageIsBrowser(packageName, userId)) {
1904                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1905                        }
1906
1907                        // We may also need to apply pending (restored) runtime
1908                        // permission grants within these users.
1909                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1910                    }
1911                }
1912            }
1913
1914            // Log current value of "unknown sources" setting
1915            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1916                    getUnknownSourcesSettings());
1917
1918            // Force a gc to clear up things
1919            Runtime.getRuntime().gc();
1920
1921            // Remove the replaced package's older resources safely now
1922            // We delete after a gc for applications  on sdcard.
1923            if (res.removedInfo != null && res.removedInfo.args != null) {
1924                synchronized (mInstallLock) {
1925                    res.removedInfo.args.doPostDeleteLI(true);
1926                }
1927            }
1928        }
1929
1930        // If someone is watching installs - notify them
1931        if (installObserver != null) {
1932            try {
1933                Bundle extras = extrasForInstallResult(res);
1934                installObserver.onPackageInstalled(res.name, res.returnCode,
1935                        res.returnMsg, extras);
1936            } catch (RemoteException e) {
1937                Slog.i(TAG, "Observer no longer exists.");
1938            }
1939        }
1940    }
1941
1942    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1943            PackageParser.Package pkg) {
1944        if (pkg.parentPackage == null) {
1945            return;
1946        }
1947        if (pkg.requestedPermissions == null) {
1948            return;
1949        }
1950        final PackageSetting disabledSysParentPs = mSettings
1951                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1952        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1953                || !disabledSysParentPs.isPrivileged()
1954                || (disabledSysParentPs.childPackageNames != null
1955                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1956            return;
1957        }
1958        final int[] allUserIds = sUserManager.getUserIds();
1959        final int permCount = pkg.requestedPermissions.size();
1960        for (int i = 0; i < permCount; i++) {
1961            String permission = pkg.requestedPermissions.get(i);
1962            BasePermission bp = mSettings.mPermissions.get(permission);
1963            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1964                continue;
1965            }
1966            for (int userId : allUserIds) {
1967                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1968                        permission, userId)) {
1969                    grantRuntimePermission(pkg.packageName, permission, userId);
1970                }
1971            }
1972        }
1973    }
1974
1975    private StorageEventListener mStorageListener = new StorageEventListener() {
1976        @Override
1977        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1978            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1979                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1980                    final String volumeUuid = vol.getFsUuid();
1981
1982                    // Clean up any users or apps that were removed or recreated
1983                    // while this volume was missing
1984                    reconcileUsers(volumeUuid);
1985                    reconcileApps(volumeUuid);
1986
1987                    // Clean up any install sessions that expired or were
1988                    // cancelled while this volume was missing
1989                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1990
1991                    loadPrivatePackages(vol);
1992
1993                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1994                    unloadPrivatePackages(vol);
1995                }
1996            }
1997
1998            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1999                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2000                    updateExternalMediaStatus(true, false);
2001                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2002                    updateExternalMediaStatus(false, false);
2003                }
2004            }
2005        }
2006
2007        @Override
2008        public void onVolumeForgotten(String fsUuid) {
2009            if (TextUtils.isEmpty(fsUuid)) {
2010                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2011                return;
2012            }
2013
2014            // Remove any apps installed on the forgotten volume
2015            synchronized (mPackages) {
2016                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2017                for (PackageSetting ps : packages) {
2018                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2019                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2020                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2021                }
2022
2023                mSettings.onVolumeForgotten(fsUuid);
2024                mSettings.writeLPr();
2025            }
2026        }
2027    };
2028
2029    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2030            String[] grantedPermissions) {
2031        for (int userId : userIds) {
2032            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2033        }
2034
2035        // We could have touched GID membership, so flush out packages.list
2036        synchronized (mPackages) {
2037            mSettings.writePackageListLPr();
2038        }
2039    }
2040
2041    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2042            String[] grantedPermissions) {
2043        SettingBase sb = (SettingBase) pkg.mExtras;
2044        if (sb == null) {
2045            return;
2046        }
2047
2048        PermissionsState permissionsState = sb.getPermissionsState();
2049
2050        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2051                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2052
2053        synchronized (mPackages) {
2054            for (String permission : pkg.requestedPermissions) {
2055                BasePermission bp = mSettings.mPermissions.get(permission);
2056                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2057                        && (grantedPermissions == null
2058                               || ArrayUtils.contains(grantedPermissions, permission))) {
2059                    final int flags = permissionsState.getPermissionFlags(permission, userId);
2060                    // Installer cannot change immutable permissions.
2061                    if ((flags & immutableFlags) == 0) {
2062                        grantRuntimePermission(pkg.packageName, permission, userId);
2063                    }
2064                }
2065            }
2066        }
2067    }
2068
2069    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2070        Bundle extras = null;
2071        switch (res.returnCode) {
2072            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2073                extras = new Bundle();
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2075                        res.origPermission);
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2077                        res.origPackage);
2078                break;
2079            }
2080            case PackageManager.INSTALL_SUCCEEDED: {
2081                extras = new Bundle();
2082                extras.putBoolean(Intent.EXTRA_REPLACING,
2083                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2084                break;
2085            }
2086        }
2087        return extras;
2088    }
2089
2090    void scheduleWriteSettingsLocked() {
2091        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2092            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2097        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2098        scheduleWritePackageRestrictionsLocked(userId);
2099    }
2100
2101    void scheduleWritePackageRestrictionsLocked(int userId) {
2102        final int[] userIds = (userId == UserHandle.USER_ALL)
2103                ? sUserManager.getUserIds() : new int[]{userId};
2104        for (int nextUserId : userIds) {
2105            if (!sUserManager.exists(nextUserId)) return;
2106            mDirtyUsers.add(nextUserId);
2107            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2108                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2109            }
2110        }
2111    }
2112
2113    public static PackageManagerService main(Context context, Installer installer,
2114            boolean factoryTest, boolean onlyCore) {
2115        // Self-check for initial settings.
2116        PackageManagerServiceCompilerMapping.checkProperties();
2117
2118        PackageManagerService m = new PackageManagerService(context, installer,
2119                factoryTest, onlyCore);
2120        m.enableSystemUserPackages();
2121        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2122        // disabled after already being started.
2123        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2124                UserHandle.USER_SYSTEM);
2125        ServiceManager.addService("package", m);
2126        return m;
2127    }
2128
2129    private void enableSystemUserPackages() {
2130        if (!UserManager.isSplitSystemUser()) {
2131            return;
2132        }
2133        // For system user, enable apps based on the following conditions:
2134        // - app is whitelisted or belong to one of these groups:
2135        //   -- system app which has no launcher icons
2136        //   -- system app which has INTERACT_ACROSS_USERS permission
2137        //   -- system IME app
2138        // - app is not in the blacklist
2139        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2140        Set<String> enableApps = new ArraySet<>();
2141        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2142                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2143                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2144        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2145        enableApps.addAll(wlApps);
2146        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2147                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2148        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2149        enableApps.removeAll(blApps);
2150        Log.i(TAG, "Applications installed for system user: " + enableApps);
2151        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2152                UserHandle.SYSTEM);
2153        final int allAppsSize = allAps.size();
2154        synchronized (mPackages) {
2155            for (int i = 0; i < allAppsSize; i++) {
2156                String pName = allAps.get(i);
2157                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2158                // Should not happen, but we shouldn't be failing if it does
2159                if (pkgSetting == null) {
2160                    continue;
2161                }
2162                boolean install = enableApps.contains(pName);
2163                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2164                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2165                            + " for system user");
2166                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2167                }
2168            }
2169        }
2170    }
2171
2172    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2173        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2174                Context.DISPLAY_SERVICE);
2175        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2176    }
2177
2178    public PackageManagerService(Context context, Installer installer,
2179            boolean factoryTest, boolean onlyCore) {
2180        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2181                SystemClock.uptimeMillis());
2182
2183        if (mSdkVersion <= 0) {
2184            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2185        }
2186
2187        mContext = context;
2188        mFactoryTest = factoryTest;
2189        mOnlyCore = onlyCore;
2190        mMetrics = new DisplayMetrics();
2191        mSettings = new Settings(mPackages);
2192        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2193                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2194        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2195                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2196        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2197                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2198        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2199                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2200        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2201                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2202        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2203                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2204
2205        String separateProcesses = SystemProperties.get("debug.separate_processes");
2206        if (separateProcesses != null && separateProcesses.length() > 0) {
2207            if ("*".equals(separateProcesses)) {
2208                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2209                mSeparateProcesses = null;
2210                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2211            } else {
2212                mDefParseFlags = 0;
2213                mSeparateProcesses = separateProcesses.split(",");
2214                Slog.w(TAG, "Running with debug.separate_processes: "
2215                        + separateProcesses);
2216            }
2217        } else {
2218            mDefParseFlags = 0;
2219            mSeparateProcesses = null;
2220        }
2221
2222        mInstaller = installer;
2223        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2224                "*dexopt*");
2225        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2226
2227        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2228                FgThread.get().getLooper());
2229
2230        getDefaultDisplayMetrics(context, mMetrics);
2231
2232        SystemConfig systemConfig = SystemConfig.getInstance();
2233        mGlobalGids = systemConfig.getGlobalGids();
2234        mSystemPermissions = systemConfig.getSystemPermissions();
2235        mAvailableFeatures = systemConfig.getAvailableFeatures();
2236
2237        synchronized (mInstallLock) {
2238        // writer
2239        synchronized (mPackages) {
2240            mHandlerThread = new ServiceThread(TAG,
2241                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2242            mHandlerThread.start();
2243            mHandler = new PackageHandler(mHandlerThread.getLooper());
2244            mProcessLoggingHandler = new ProcessLoggingHandler();
2245            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2246
2247            File dataDir = Environment.getDataDirectory();
2248            mAppInstallDir = new File(dataDir, "app");
2249            mAppLib32InstallDir = new File(dataDir, "app-lib");
2250            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2251            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2252            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2253
2254            sUserManager = new UserManagerService(context, this, mPackages);
2255
2256            // Propagate permission configuration in to package manager.
2257            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2258                    = systemConfig.getPermissions();
2259            for (int i=0; i<permConfig.size(); i++) {
2260                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2261                BasePermission bp = mSettings.mPermissions.get(perm.name);
2262                if (bp == null) {
2263                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2264                    mSettings.mPermissions.put(perm.name, bp);
2265                }
2266                if (perm.gids != null) {
2267                    bp.setGids(perm.gids, perm.perUser);
2268                }
2269            }
2270
2271            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2272            for (int i=0; i<libConfig.size(); i++) {
2273                mSharedLibraries.put(libConfig.keyAt(i),
2274                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2275            }
2276
2277            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2278
2279            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2280
2281            String customResolverActivity = Resources.getSystem().getString(
2282                    R.string.config_customResolverActivity);
2283            if (TextUtils.isEmpty(customResolverActivity)) {
2284                customResolverActivity = null;
2285            } else {
2286                mCustomResolverComponentName = ComponentName.unflattenFromString(
2287                        customResolverActivity);
2288            }
2289
2290            long startTime = SystemClock.uptimeMillis();
2291
2292            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2293                    startTime);
2294
2295            // Set flag to monitor and not change apk file paths when
2296            // scanning install directories.
2297            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2298
2299            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2300            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2301
2302            if (bootClassPath == null) {
2303                Slog.w(TAG, "No BOOTCLASSPATH found!");
2304            }
2305
2306            if (systemServerClassPath == null) {
2307                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2308            }
2309
2310            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2311            final String[] dexCodeInstructionSets =
2312                    getDexCodeInstructionSets(
2313                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2314
2315            /**
2316             * Ensure all external libraries have had dexopt run on them.
2317             */
2318            if (mSharedLibraries.size() > 0) {
2319                // NOTE: For now, we're compiling these system "shared libraries"
2320                // (and framework jars) into all available architectures. It's possible
2321                // to compile them only when we come across an app that uses them (there's
2322                // already logic for that in scanPackageLI) but that adds some complexity.
2323                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2324                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2325                        final String lib = libEntry.path;
2326                        if (lib == null) {
2327                            continue;
2328                        }
2329
2330                        try {
2331                            // Shared libraries do not have profiles so we perform a full
2332                            // AOT compilation (if needed).
2333                            int dexoptNeeded = DexFile.getDexOptNeeded(
2334                                    lib, dexCodeInstructionSet,
2335                                    getCompilerFilterForReason(REASON_SHARED_APK),
2336                                    false /* newProfile */);
2337                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2338                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2339                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2340                                        getCompilerFilterForReason(REASON_SHARED_APK),
2341                                        StorageManager.UUID_PRIVATE_INTERNAL);
2342                            }
2343                        } catch (FileNotFoundException e) {
2344                            Slog.w(TAG, "Library not found: " + lib);
2345                        } catch (IOException | InstallerException e) {
2346                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2347                                    + e.getMessage());
2348                        }
2349                    }
2350                }
2351            }
2352
2353            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2354
2355            final VersionInfo ver = mSettings.getInternalVersion();
2356            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2357
2358            // when upgrading from pre-M, promote system app permissions from install to runtime
2359            mPromoteSystemApps =
2360                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2361
2362            // save off the names of pre-existing system packages prior to scanning; we don't
2363            // want to automatically grant runtime permissions for new system apps
2364            if (mPromoteSystemApps) {
2365                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2366                while (pkgSettingIter.hasNext()) {
2367                    PackageSetting ps = pkgSettingIter.next();
2368                    if (isSystemApp(ps)) {
2369                        mExistingSystemPackages.add(ps.name);
2370                    }
2371                }
2372            }
2373
2374            // When upgrading from pre-N, we need to handle package extraction like first boot,
2375            // as there is no profiling data available.
2376            mIsPreNUpgrade = !mSettings.isNWorkDone();
2377            mSettings.setNWorkDone();
2378
2379            // Collect vendor overlay packages.
2380            // (Do this before scanning any apps.)
2381            // For security and version matching reason, only consider
2382            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2383            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2384            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2385                    | PackageParser.PARSE_IS_SYSTEM
2386                    | PackageParser.PARSE_IS_SYSTEM_DIR
2387                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2388
2389            // Find base frameworks (resource packages without code).
2390            scanDirTracedLI(frameworkDir, mDefParseFlags
2391                    | PackageParser.PARSE_IS_SYSTEM
2392                    | PackageParser.PARSE_IS_SYSTEM_DIR
2393                    | PackageParser.PARSE_IS_PRIVILEGED,
2394                    scanFlags | SCAN_NO_DEX, 0);
2395
2396            // Collected privileged system packages.
2397            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2398            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2399                    | PackageParser.PARSE_IS_SYSTEM
2400                    | PackageParser.PARSE_IS_SYSTEM_DIR
2401                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2402
2403            // Collect ordinary system packages.
2404            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2405            scanDirTracedLI(systemAppDir, mDefParseFlags
2406                    | PackageParser.PARSE_IS_SYSTEM
2407                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2408
2409            // Collect all vendor packages.
2410            File vendorAppDir = new File("/vendor/app");
2411            try {
2412                vendorAppDir = vendorAppDir.getCanonicalFile();
2413            } catch (IOException e) {
2414                // failed to look up canonical path, continue with original one
2415            }
2416            scanDirTracedLI(vendorAppDir, mDefParseFlags
2417                    | PackageParser.PARSE_IS_SYSTEM
2418                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2419
2420            // Collect all OEM packages.
2421            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2422            scanDirTracedLI(oemAppDir, mDefParseFlags
2423                    | PackageParser.PARSE_IS_SYSTEM
2424                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2425
2426            // Prune any system packages that no longer exist.
2427            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2428            if (!mOnlyCore) {
2429                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2430                while (psit.hasNext()) {
2431                    PackageSetting ps = psit.next();
2432
2433                    /*
2434                     * If this is not a system app, it can't be a
2435                     * disable system app.
2436                     */
2437                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2438                        continue;
2439                    }
2440
2441                    /*
2442                     * If the package is scanned, it's not erased.
2443                     */
2444                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2445                    if (scannedPkg != null) {
2446                        /*
2447                         * If the system app is both scanned and in the
2448                         * disabled packages list, then it must have been
2449                         * added via OTA. Remove it from the currently
2450                         * scanned package so the previously user-installed
2451                         * application can be scanned.
2452                         */
2453                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2454                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2455                                    + ps.name + "; removing system app.  Last known codePath="
2456                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2457                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2458                                    + scannedPkg.mVersionCode);
2459                            removePackageLI(scannedPkg, true);
2460                            mExpectingBetter.put(ps.name, ps.codePath);
2461                        }
2462
2463                        continue;
2464                    }
2465
2466                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2467                        psit.remove();
2468                        logCriticalInfo(Log.WARN, "System package " + ps.name
2469                                + " no longer exists; it's data will be wiped");
2470                        // Actual deletion of code and data will be handled by later
2471                        // reconciliation step
2472                    } else {
2473                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2474                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2475                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2476                        }
2477                    }
2478                }
2479            }
2480
2481            //look for any incomplete package installations
2482            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2483            for (int i = 0; i < deletePkgsList.size(); i++) {
2484                // Actual deletion of code and data will be handled by later
2485                // reconciliation step
2486                final String packageName = deletePkgsList.get(i).name;
2487                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2488                synchronized (mPackages) {
2489                    mSettings.removePackageLPw(packageName);
2490                }
2491            }
2492
2493            //delete tmp files
2494            deleteTempPackageFiles();
2495
2496            // Remove any shared userIDs that have no associated packages
2497            mSettings.pruneSharedUsersLPw();
2498
2499            if (!mOnlyCore) {
2500                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2501                        SystemClock.uptimeMillis());
2502                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2503
2504                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2505                        | PackageParser.PARSE_FORWARD_LOCK,
2506                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2507
2508                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2509                        | PackageParser.PARSE_IS_EPHEMERAL,
2510                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2511
2512                /**
2513                 * Remove disable package settings for any updated system
2514                 * apps that were removed via an OTA. If they're not a
2515                 * previously-updated app, remove them completely.
2516                 * Otherwise, just revoke their system-level permissions.
2517                 */
2518                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2519                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2520                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2521
2522                    String msg;
2523                    if (deletedPkg == null) {
2524                        msg = "Updated system package " + deletedAppName
2525                                + " no longer exists; it's data will be wiped";
2526                        // Actual deletion of code and data will be handled by later
2527                        // reconciliation step
2528                    } else {
2529                        msg = "Updated system app + " + deletedAppName
2530                                + " no longer present; removing system privileges for "
2531                                + deletedAppName;
2532
2533                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2534
2535                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2536                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2537                    }
2538                    logCriticalInfo(Log.WARN, msg);
2539                }
2540
2541                /**
2542                 * Make sure all system apps that we expected to appear on
2543                 * the userdata partition actually showed up. If they never
2544                 * appeared, crawl back and revive the system version.
2545                 */
2546                for (int i = 0; i < mExpectingBetter.size(); i++) {
2547                    final String packageName = mExpectingBetter.keyAt(i);
2548                    if (!mPackages.containsKey(packageName)) {
2549                        final File scanFile = mExpectingBetter.valueAt(i);
2550
2551                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2552                                + " but never showed up; reverting to system");
2553
2554                        int reparseFlags = mDefParseFlags;
2555                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2556                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2557                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2558                                    | PackageParser.PARSE_IS_PRIVILEGED;
2559                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2560                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2561                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2562                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2563                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2564                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2565                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2566                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2567                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2568                        } else {
2569                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2570                            continue;
2571                        }
2572
2573                        mSettings.enableSystemPackageLPw(packageName);
2574
2575                        try {
2576                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2577                        } catch (PackageManagerException e) {
2578                            Slog.e(TAG, "Failed to parse original system package: "
2579                                    + e.getMessage());
2580                        }
2581                    }
2582                }
2583            }
2584            mExpectingBetter.clear();
2585
2586            // Resolve protected action filters. Only the setup wizard is allowed to
2587            // have a high priority filter for these actions.
2588            mSetupWizardPackage = getSetupWizardPackageName();
2589            if (mProtectedFilters.size() > 0) {
2590                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2591                    Slog.i(TAG, "No setup wizard;"
2592                        + " All protected intents capped to priority 0");
2593                }
2594                for (ActivityIntentInfo filter : mProtectedFilters) {
2595                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2596                        if (DEBUG_FILTERS) {
2597                            Slog.i(TAG, "Found setup wizard;"
2598                                + " allow priority " + filter.getPriority() + ";"
2599                                + " package: " + filter.activity.info.packageName
2600                                + " activity: " + filter.activity.className
2601                                + " priority: " + filter.getPriority());
2602                        }
2603                        // skip setup wizard; allow it to keep the high priority filter
2604                        continue;
2605                    }
2606                    Slog.w(TAG, "Protected action; cap priority to 0;"
2607                            + " package: " + filter.activity.info.packageName
2608                            + " activity: " + filter.activity.className
2609                            + " origPrio: " + filter.getPriority());
2610                    filter.setPriority(0);
2611                }
2612            }
2613            mDeferProtectedFilters = false;
2614            mProtectedFilters.clear();
2615
2616            // Now that we know all of the shared libraries, update all clients to have
2617            // the correct library paths.
2618            updateAllSharedLibrariesLPw();
2619
2620            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2621                // NOTE: We ignore potential failures here during a system scan (like
2622                // the rest of the commands above) because there's precious little we
2623                // can do about it. A settings error is reported, though.
2624                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2625                        false /* boot complete */);
2626            }
2627
2628            // Now that we know all the packages we are keeping,
2629            // read and update their last usage times.
2630            mPackageUsage.readLP();
2631
2632            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2633                    SystemClock.uptimeMillis());
2634            Slog.i(TAG, "Time to scan packages: "
2635                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2636                    + " seconds");
2637
2638            // If the platform SDK has changed since the last time we booted,
2639            // we need to re-grant app permission to catch any new ones that
2640            // appear.  This is really a hack, and means that apps can in some
2641            // cases get permissions that the user didn't initially explicitly
2642            // allow...  it would be nice to have some better way to handle
2643            // this situation.
2644            int updateFlags = UPDATE_PERMISSIONS_ALL;
2645            if (ver.sdkVersion != mSdkVersion) {
2646                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2647                        + mSdkVersion + "; regranting permissions for internal storage");
2648                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2649            }
2650            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2651            ver.sdkVersion = mSdkVersion;
2652
2653            // If this is the first boot or an update from pre-M, and it is a normal
2654            // boot, then we need to initialize the default preferred apps across
2655            // all defined users.
2656            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2657                for (UserInfo user : sUserManager.getUsers(true)) {
2658                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2659                    applyFactoryDefaultBrowserLPw(user.id);
2660                    primeDomainVerificationsLPw(user.id);
2661                }
2662            }
2663
2664            // Prepare storage for system user really early during boot,
2665            // since core system apps like SettingsProvider and SystemUI
2666            // can't wait for user to start
2667            final int storageFlags;
2668            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2669                storageFlags = StorageManager.FLAG_STORAGE_DE;
2670            } else {
2671                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2672            }
2673            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2674                    storageFlags);
2675
2676            // If this is first boot after an OTA, and a normal boot, then
2677            // we need to clear code cache directories.
2678            if (mIsUpgrade && !onlyCore) {
2679                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2680                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2681                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2682                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2683                        // No apps are running this early, so no need to freeze
2684                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2685                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2686                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2687                    }
2688                    clearAppProfilesLIF(ps.pkg);
2689                }
2690                ver.fingerprint = Build.FINGERPRINT;
2691            }
2692
2693            checkDefaultBrowser();
2694
2695            // clear only after permissions and other defaults have been updated
2696            mExistingSystemPackages.clear();
2697            mPromoteSystemApps = false;
2698
2699            // All the changes are done during package scanning.
2700            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2701
2702            // can downgrade to reader
2703            mSettings.writeLPr();
2704
2705            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2706                    SystemClock.uptimeMillis());
2707
2708            if (!mOnlyCore) {
2709                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2710                mRequiredInstallerPackage = getRequiredInstallerLPr();
2711                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2712                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2713                        mIntentFilterVerifierComponent);
2714                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2715                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2716                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2717                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2718            } else {
2719                mRequiredVerifierPackage = null;
2720                mRequiredInstallerPackage = null;
2721                mIntentFilterVerifierComponent = null;
2722                mIntentFilterVerifier = null;
2723                mServicesSystemSharedLibraryPackageName = null;
2724                mSharedSystemSharedLibraryPackageName = null;
2725            }
2726
2727            mInstallerService = new PackageInstallerService(context, this);
2728
2729            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2730            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2731            // both the installer and resolver must be present to enable ephemeral
2732            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2733                if (DEBUG_EPHEMERAL) {
2734                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2735                            + " installer:" + ephemeralInstallerComponent);
2736                }
2737                mEphemeralResolverComponent = ephemeralResolverComponent;
2738                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2739                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2740                mEphemeralResolverConnection =
2741                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2742            } else {
2743                if (DEBUG_EPHEMERAL) {
2744                    final String missingComponent =
2745                            (ephemeralResolverComponent == null)
2746                            ? (ephemeralInstallerComponent == null)
2747                                    ? "resolver and installer"
2748                                    : "resolver"
2749                            : "installer";
2750                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2751                }
2752                mEphemeralResolverComponent = null;
2753                mEphemeralInstallerComponent = null;
2754                mEphemeralResolverConnection = null;
2755            }
2756
2757            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2758        } // synchronized (mPackages)
2759        } // synchronized (mInstallLock)
2760
2761        // Now after opening every single application zip, make sure they
2762        // are all flushed.  Not really needed, but keeps things nice and
2763        // tidy.
2764        Runtime.getRuntime().gc();
2765
2766        // The initial scanning above does many calls into installd while
2767        // holding the mPackages lock, but we're mostly interested in yelling
2768        // once we have a booted system.
2769        mInstaller.setWarnIfHeld(mPackages);
2770
2771        // Expose private service for system components to use.
2772        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2773    }
2774
2775    @Override
2776    public boolean isFirstBoot() {
2777        return !mRestoredSettings;
2778    }
2779
2780    @Override
2781    public boolean isOnlyCoreApps() {
2782        return mOnlyCore;
2783    }
2784
2785    @Override
2786    public boolean isUpgrade() {
2787        return mIsUpgrade;
2788    }
2789
2790    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2791        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2792
2793        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2794                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2795                UserHandle.USER_SYSTEM);
2796        if (matches.size() == 1) {
2797            return matches.get(0).getComponentInfo().packageName;
2798        } else {
2799            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2800            return null;
2801        }
2802    }
2803
2804    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2805        synchronized (mPackages) {
2806            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2807            if (libraryEntry == null) {
2808                throw new IllegalStateException("Missing required shared library:" + libraryName);
2809            }
2810            return libraryEntry.apk;
2811        }
2812    }
2813
2814    private @NonNull String getRequiredInstallerLPr() {
2815        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2816        intent.addCategory(Intent.CATEGORY_DEFAULT);
2817        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2818
2819        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2820                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2821                UserHandle.USER_SYSTEM);
2822        if (matches.size() == 1) {
2823            ResolveInfo resolveInfo = matches.get(0);
2824            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2825                throw new RuntimeException("The installer must be a privileged app");
2826            }
2827            return matches.get(0).getComponentInfo().packageName;
2828        } else {
2829            throw new RuntimeException("There must be exactly one installer; found " + matches);
2830        }
2831    }
2832
2833    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2834        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2835
2836        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2837                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2838                UserHandle.USER_SYSTEM);
2839        ResolveInfo best = null;
2840        final int N = matches.size();
2841        for (int i = 0; i < N; i++) {
2842            final ResolveInfo cur = matches.get(i);
2843            final String packageName = cur.getComponentInfo().packageName;
2844            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2845                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2846                continue;
2847            }
2848
2849            if (best == null || cur.priority > best.priority) {
2850                best = cur;
2851            }
2852        }
2853
2854        if (best != null) {
2855            return best.getComponentInfo().getComponentName();
2856        } else {
2857            throw new RuntimeException("There must be at least one intent filter verifier");
2858        }
2859    }
2860
2861    private @Nullable ComponentName getEphemeralResolverLPr() {
2862        final String[] packageArray =
2863                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2864        if (packageArray.length == 0) {
2865            if (DEBUG_EPHEMERAL) {
2866                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2867            }
2868            return null;
2869        }
2870
2871        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2872        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2873                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2874                UserHandle.USER_SYSTEM);
2875
2876        final int N = resolvers.size();
2877        if (N == 0) {
2878            if (DEBUG_EPHEMERAL) {
2879                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2880            }
2881            return null;
2882        }
2883
2884        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2885        for (int i = 0; i < N; i++) {
2886            final ResolveInfo info = resolvers.get(i);
2887
2888            if (info.serviceInfo == null) {
2889                continue;
2890            }
2891
2892            final String packageName = info.serviceInfo.packageName;
2893            if (!possiblePackages.contains(packageName)) {
2894                if (DEBUG_EPHEMERAL) {
2895                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2896                            + " pkg: " + packageName + ", info:" + info);
2897                }
2898                continue;
2899            }
2900
2901            if (DEBUG_EPHEMERAL) {
2902                Slog.v(TAG, "Ephemeral resolver found;"
2903                        + " pkg: " + packageName + ", info:" + info);
2904            }
2905            return new ComponentName(packageName, info.serviceInfo.name);
2906        }
2907        if (DEBUG_EPHEMERAL) {
2908            Slog.v(TAG, "Ephemeral resolver NOT found");
2909        }
2910        return null;
2911    }
2912
2913    private @Nullable ComponentName getEphemeralInstallerLPr() {
2914        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2915        intent.addCategory(Intent.CATEGORY_DEFAULT);
2916        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2917
2918        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2919                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2920                UserHandle.USER_SYSTEM);
2921        if (matches.size() == 0) {
2922            return null;
2923        } else if (matches.size() == 1) {
2924            return matches.get(0).getComponentInfo().getComponentName();
2925        } else {
2926            throw new RuntimeException(
2927                    "There must be at most one ephemeral installer; found " + matches);
2928        }
2929    }
2930
2931    private void primeDomainVerificationsLPw(int userId) {
2932        if (DEBUG_DOMAIN_VERIFICATION) {
2933            Slog.d(TAG, "Priming domain verifications in user " + userId);
2934        }
2935
2936        SystemConfig systemConfig = SystemConfig.getInstance();
2937        ArraySet<String> packages = systemConfig.getLinkedApps();
2938        ArraySet<String> domains = new ArraySet<String>();
2939
2940        for (String packageName : packages) {
2941            PackageParser.Package pkg = mPackages.get(packageName);
2942            if (pkg != null) {
2943                if (!pkg.isSystemApp()) {
2944                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2945                    continue;
2946                }
2947
2948                domains.clear();
2949                for (PackageParser.Activity a : pkg.activities) {
2950                    for (ActivityIntentInfo filter : a.intents) {
2951                        if (hasValidDomains(filter)) {
2952                            domains.addAll(filter.getHostsList());
2953                        }
2954                    }
2955                }
2956
2957                if (domains.size() > 0) {
2958                    if (DEBUG_DOMAIN_VERIFICATION) {
2959                        Slog.v(TAG, "      + " + packageName);
2960                    }
2961                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2962                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2963                    // and then 'always' in the per-user state actually used for intent resolution.
2964                    final IntentFilterVerificationInfo ivi;
2965                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2966                            new ArrayList<String>(domains));
2967                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2968                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2969                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2970                } else {
2971                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2972                            + "' does not handle web links");
2973                }
2974            } else {
2975                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2976            }
2977        }
2978
2979        scheduleWritePackageRestrictionsLocked(userId);
2980        scheduleWriteSettingsLocked();
2981    }
2982
2983    private void applyFactoryDefaultBrowserLPw(int userId) {
2984        // The default browser app's package name is stored in a string resource,
2985        // with a product-specific overlay used for vendor customization.
2986        String browserPkg = mContext.getResources().getString(
2987                com.android.internal.R.string.default_browser);
2988        if (!TextUtils.isEmpty(browserPkg)) {
2989            // non-empty string => required to be a known package
2990            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2991            if (ps == null) {
2992                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2993                browserPkg = null;
2994            } else {
2995                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2996            }
2997        }
2998
2999        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3000        // default.  If there's more than one, just leave everything alone.
3001        if (browserPkg == null) {
3002            calculateDefaultBrowserLPw(userId);
3003        }
3004    }
3005
3006    private void calculateDefaultBrowserLPw(int userId) {
3007        List<String> allBrowsers = resolveAllBrowserApps(userId);
3008        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3009        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3010    }
3011
3012    private List<String> resolveAllBrowserApps(int userId) {
3013        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3014        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3015                PackageManager.MATCH_ALL, userId);
3016
3017        final int count = list.size();
3018        List<String> result = new ArrayList<String>(count);
3019        for (int i=0; i<count; i++) {
3020            ResolveInfo info = list.get(i);
3021            if (info.activityInfo == null
3022                    || !info.handleAllWebDataURI
3023                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3024                    || result.contains(info.activityInfo.packageName)) {
3025                continue;
3026            }
3027            result.add(info.activityInfo.packageName);
3028        }
3029
3030        return result;
3031    }
3032
3033    private boolean packageIsBrowser(String packageName, int userId) {
3034        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3035                PackageManager.MATCH_ALL, userId);
3036        final int N = list.size();
3037        for (int i = 0; i < N; i++) {
3038            ResolveInfo info = list.get(i);
3039            if (packageName.equals(info.activityInfo.packageName)) {
3040                return true;
3041            }
3042        }
3043        return false;
3044    }
3045
3046    private void checkDefaultBrowser() {
3047        final int myUserId = UserHandle.myUserId();
3048        final String packageName = getDefaultBrowserPackageName(myUserId);
3049        if (packageName != null) {
3050            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3051            if (info == null) {
3052                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3053                synchronized (mPackages) {
3054                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3055                }
3056            }
3057        }
3058    }
3059
3060    @Override
3061    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3062            throws RemoteException {
3063        try {
3064            return super.onTransact(code, data, reply, flags);
3065        } catch (RuntimeException e) {
3066            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3067                Slog.wtf(TAG, "Package Manager Crash", e);
3068            }
3069            throw e;
3070        }
3071    }
3072
3073    static int[] appendInts(int[] cur, int[] add) {
3074        if (add == null) return cur;
3075        if (cur == null) return add;
3076        final int N = add.length;
3077        for (int i=0; i<N; i++) {
3078            cur = appendInt(cur, add[i]);
3079        }
3080        return cur;
3081    }
3082
3083    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3084        if (!sUserManager.exists(userId)) return null;
3085        if (ps == null) {
3086            return null;
3087        }
3088        final PackageParser.Package p = ps.pkg;
3089        if (p == null) {
3090            return null;
3091        }
3092
3093        final PermissionsState permissionsState = ps.getPermissionsState();
3094
3095        final int[] gids = permissionsState.computeGids(userId);
3096        final Set<String> permissions = permissionsState.getPermissions(userId);
3097        final PackageUserState state = ps.readUserState(userId);
3098
3099        return PackageParser.generatePackageInfo(p, gids, flags,
3100                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3101    }
3102
3103    @Override
3104    public void checkPackageStartable(String packageName, int userId) {
3105        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3106
3107        synchronized (mPackages) {
3108            final PackageSetting ps = mSettings.mPackages.get(packageName);
3109            if (ps == null) {
3110                throw new SecurityException("Package " + packageName + " was not found!");
3111            }
3112
3113            if (!ps.getInstalled(userId)) {
3114                throw new SecurityException(
3115                        "Package " + packageName + " was not installed for user " + userId + "!");
3116            }
3117
3118            if (mSafeMode && !ps.isSystem()) {
3119                throw new SecurityException("Package " + packageName + " not a system app!");
3120            }
3121
3122            if (mFrozenPackages.contains(packageName)) {
3123                throw new SecurityException("Package " + packageName + " is currently frozen!");
3124            }
3125
3126            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3127                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3128                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3129            }
3130        }
3131    }
3132
3133    @Override
3134    public boolean isPackageAvailable(String packageName, int userId) {
3135        if (!sUserManager.exists(userId)) return false;
3136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3137                false /* requireFullPermission */, false /* checkShell */, "is package available");
3138        synchronized (mPackages) {
3139            PackageParser.Package p = mPackages.get(packageName);
3140            if (p != null) {
3141                final PackageSetting ps = (PackageSetting) p.mExtras;
3142                if (ps != null) {
3143                    final PackageUserState state = ps.readUserState(userId);
3144                    if (state != null) {
3145                        return PackageParser.isAvailable(state);
3146                    }
3147                }
3148            }
3149        }
3150        return false;
3151    }
3152
3153    @Override
3154    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3155        if (!sUserManager.exists(userId)) return null;
3156        flags = updateFlagsForPackage(flags, userId, packageName);
3157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3158                false /* requireFullPermission */, false /* checkShell */, "get package info");
3159        // reader
3160        synchronized (mPackages) {
3161            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3162            PackageParser.Package p = null;
3163            if (matchFactoryOnly) {
3164                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3165                if (ps != null) {
3166                    return generatePackageInfo(ps, flags, userId);
3167                }
3168            }
3169            if (p == null) {
3170                p = mPackages.get(packageName);
3171                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3172                    return null;
3173                }
3174            }
3175            if (DEBUG_PACKAGE_INFO)
3176                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3177            if (p != null) {
3178                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3179            }
3180            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3181                final PackageSetting ps = mSettings.mPackages.get(packageName);
3182                return generatePackageInfo(ps, flags, userId);
3183            }
3184        }
3185        return null;
3186    }
3187
3188    @Override
3189    public String[] currentToCanonicalPackageNames(String[] names) {
3190        String[] out = new String[names.length];
3191        // reader
3192        synchronized (mPackages) {
3193            for (int i=names.length-1; i>=0; i--) {
3194                PackageSetting ps = mSettings.mPackages.get(names[i]);
3195                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3196            }
3197        }
3198        return out;
3199    }
3200
3201    @Override
3202    public String[] canonicalToCurrentPackageNames(String[] names) {
3203        String[] out = new String[names.length];
3204        // reader
3205        synchronized (mPackages) {
3206            for (int i=names.length-1; i>=0; i--) {
3207                String cur = mSettings.mRenamedPackages.get(names[i]);
3208                out[i] = cur != null ? cur : names[i];
3209            }
3210        }
3211        return out;
3212    }
3213
3214    @Override
3215    public int getPackageUid(String packageName, int flags, int userId) {
3216        if (!sUserManager.exists(userId)) return -1;
3217        flags = updateFlagsForPackage(flags, userId, packageName);
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3219                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3220
3221        // reader
3222        synchronized (mPackages) {
3223            final PackageParser.Package p = mPackages.get(packageName);
3224            if (p != null && p.isMatch(flags)) {
3225                return UserHandle.getUid(userId, p.applicationInfo.uid);
3226            }
3227            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3228                final PackageSetting ps = mSettings.mPackages.get(packageName);
3229                if (ps != null && ps.isMatch(flags)) {
3230                    return UserHandle.getUid(userId, ps.appId);
3231                }
3232            }
3233        }
3234
3235        return -1;
3236    }
3237
3238    @Override
3239    public int[] getPackageGids(String packageName, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return null;
3241        flags = updateFlagsForPackage(flags, userId, packageName);
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3243                false /* requireFullPermission */, false /* checkShell */,
3244                "getPackageGids");
3245
3246        // reader
3247        synchronized (mPackages) {
3248            final PackageParser.Package p = mPackages.get(packageName);
3249            if (p != null && p.isMatch(flags)) {
3250                PackageSetting ps = (PackageSetting) p.mExtras;
3251                return ps.getPermissionsState().computeGids(userId);
3252            }
3253            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3254                final PackageSetting ps = mSettings.mPackages.get(packageName);
3255                if (ps != null && ps.isMatch(flags)) {
3256                    return ps.getPermissionsState().computeGids(userId);
3257                }
3258            }
3259        }
3260
3261        return null;
3262    }
3263
3264    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3265        if (bp.perm != null) {
3266            return PackageParser.generatePermissionInfo(bp.perm, flags);
3267        }
3268        PermissionInfo pi = new PermissionInfo();
3269        pi.name = bp.name;
3270        pi.packageName = bp.sourcePackage;
3271        pi.nonLocalizedLabel = bp.name;
3272        pi.protectionLevel = bp.protectionLevel;
3273        return pi;
3274    }
3275
3276    @Override
3277    public PermissionInfo getPermissionInfo(String name, int flags) {
3278        // reader
3279        synchronized (mPackages) {
3280            final BasePermission p = mSettings.mPermissions.get(name);
3281            if (p != null) {
3282                return generatePermissionInfo(p, flags);
3283            }
3284            return null;
3285        }
3286    }
3287
3288    @Override
3289    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3290            int flags) {
3291        // reader
3292        synchronized (mPackages) {
3293            if (group != null && !mPermissionGroups.containsKey(group)) {
3294                // This is thrown as NameNotFoundException
3295                return null;
3296            }
3297
3298            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3299            for (BasePermission p : mSettings.mPermissions.values()) {
3300                if (group == null) {
3301                    if (p.perm == null || p.perm.info.group == null) {
3302                        out.add(generatePermissionInfo(p, flags));
3303                    }
3304                } else {
3305                    if (p.perm != null && group.equals(p.perm.info.group)) {
3306                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3307                    }
3308                }
3309            }
3310            return new ParceledListSlice<>(out);
3311        }
3312    }
3313
3314    @Override
3315    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3316        // reader
3317        synchronized (mPackages) {
3318            return PackageParser.generatePermissionGroupInfo(
3319                    mPermissionGroups.get(name), flags);
3320        }
3321    }
3322
3323    @Override
3324    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3325        // reader
3326        synchronized (mPackages) {
3327            final int N = mPermissionGroups.size();
3328            ArrayList<PermissionGroupInfo> out
3329                    = new ArrayList<PermissionGroupInfo>(N);
3330            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3331                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3332            }
3333            return new ParceledListSlice<>(out);
3334        }
3335    }
3336
3337    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3338            int userId) {
3339        if (!sUserManager.exists(userId)) return null;
3340        PackageSetting ps = mSettings.mPackages.get(packageName);
3341        if (ps != null) {
3342            if (ps.pkg == null) {
3343                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3344                if (pInfo != null) {
3345                    return pInfo.applicationInfo;
3346                }
3347                return null;
3348            }
3349            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3350                    ps.readUserState(userId), userId);
3351        }
3352        return null;
3353    }
3354
3355    @Override
3356    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3357        if (!sUserManager.exists(userId)) return null;
3358        flags = updateFlagsForApplication(flags, userId, packageName);
3359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3360                false /* requireFullPermission */, false /* checkShell */, "get application info");
3361        // writer
3362        synchronized (mPackages) {
3363            PackageParser.Package p = mPackages.get(packageName);
3364            if (DEBUG_PACKAGE_INFO) Log.v(
3365                    TAG, "getApplicationInfo " + packageName
3366                    + ": " + p);
3367            if (p != null) {
3368                PackageSetting ps = mSettings.mPackages.get(packageName);
3369                if (ps == null) return null;
3370                // Note: isEnabledLP() does not apply here - always return info
3371                return PackageParser.generateApplicationInfo(
3372                        p, flags, ps.readUserState(userId), userId);
3373            }
3374            if ("android".equals(packageName)||"system".equals(packageName)) {
3375                return mAndroidApplication;
3376            }
3377            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3378                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3379            }
3380        }
3381        return null;
3382    }
3383
3384    @Override
3385    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3386            final IPackageDataObserver observer) {
3387        mContext.enforceCallingOrSelfPermission(
3388                android.Manifest.permission.CLEAR_APP_CACHE, null);
3389        // Queue up an async operation since clearing cache may take a little while.
3390        mHandler.post(new Runnable() {
3391            public void run() {
3392                mHandler.removeCallbacks(this);
3393                boolean success = true;
3394                synchronized (mInstallLock) {
3395                    try {
3396                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3397                    } catch (InstallerException e) {
3398                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3399                        success = false;
3400                    }
3401                }
3402                if (observer != null) {
3403                    try {
3404                        observer.onRemoveCompleted(null, success);
3405                    } catch (RemoteException e) {
3406                        Slog.w(TAG, "RemoveException when invoking call back");
3407                    }
3408                }
3409            }
3410        });
3411    }
3412
3413    @Override
3414    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3415            final IntentSender pi) {
3416        mContext.enforceCallingOrSelfPermission(
3417                android.Manifest.permission.CLEAR_APP_CACHE, null);
3418        // Queue up an async operation since clearing cache may take a little while.
3419        mHandler.post(new Runnable() {
3420            public void run() {
3421                mHandler.removeCallbacks(this);
3422                boolean success = true;
3423                synchronized (mInstallLock) {
3424                    try {
3425                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3426                    } catch (InstallerException e) {
3427                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3428                        success = false;
3429                    }
3430                }
3431                if(pi != null) {
3432                    try {
3433                        // Callback via pending intent
3434                        int code = success ? 1 : 0;
3435                        pi.sendIntent(null, code, null,
3436                                null, null);
3437                    } catch (SendIntentException e1) {
3438                        Slog.i(TAG, "Failed to send pending intent");
3439                    }
3440                }
3441            }
3442        });
3443    }
3444
3445    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3446        synchronized (mInstallLock) {
3447            try {
3448                mInstaller.freeCache(volumeUuid, freeStorageSize);
3449            } catch (InstallerException e) {
3450                throw new IOException("Failed to free enough space", e);
3451            }
3452        }
3453    }
3454
3455    /**
3456     * Return if the user key is currently unlocked.
3457     */
3458    private boolean isUserKeyUnlocked(int userId) {
3459        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3460            final IMountService mount = IMountService.Stub
3461                    .asInterface(ServiceManager.getService("mount"));
3462            if (mount == null) {
3463                Slog.w(TAG, "Early during boot, assuming locked");
3464                return false;
3465            }
3466            final long token = Binder.clearCallingIdentity();
3467            try {
3468                return mount.isUserKeyUnlocked(userId);
3469            } catch (RemoteException e) {
3470                throw e.rethrowAsRuntimeException();
3471            } finally {
3472                Binder.restoreCallingIdentity(token);
3473            }
3474        } else {
3475            return true;
3476        }
3477    }
3478
3479    /**
3480     * Update given flags based on encryption status of current user.
3481     */
3482    private int updateFlags(int flags, int userId) {
3483        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3484                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3485            // Caller expressed an explicit opinion about what encryption
3486            // aware/unaware components they want to see, so fall through and
3487            // give them what they want
3488        } else {
3489            // Caller expressed no opinion, so match based on user state
3490            if (isUserKeyUnlocked(userId)) {
3491                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3492            } else {
3493                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3494            }
3495        }
3496        return flags;
3497    }
3498
3499    /**
3500     * Update given flags when being used to request {@link PackageInfo}.
3501     */
3502    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3503        boolean triaged = true;
3504        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3505                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3506            // Caller is asking for component details, so they'd better be
3507            // asking for specific encryption matching behavior, or be triaged
3508            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3509                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3510                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3511                triaged = false;
3512            }
3513        }
3514        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3515                | PackageManager.MATCH_SYSTEM_ONLY
3516                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3517            triaged = false;
3518        }
3519        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3520            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3521                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3522        }
3523        return updateFlags(flags, userId);
3524    }
3525
3526    /**
3527     * Update given flags when being used to request {@link ApplicationInfo}.
3528     */
3529    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3530        return updateFlagsForPackage(flags, userId, cookie);
3531    }
3532
3533    /**
3534     * Update given flags when being used to request {@link ComponentInfo}.
3535     */
3536    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3537        if (cookie instanceof Intent) {
3538            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3539                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3540            }
3541        }
3542
3543        boolean triaged = true;
3544        // Caller is asking for component details, so they'd better be
3545        // asking for specific encryption matching behavior, or be triaged
3546        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3547                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3548                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3549            triaged = false;
3550        }
3551        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3552            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3553                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3554        }
3555
3556        return updateFlags(flags, userId);
3557    }
3558
3559    /**
3560     * Update given flags when being used to request {@link ResolveInfo}.
3561     */
3562    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3563        // Safe mode means we shouldn't match any third-party components
3564        if (mSafeMode) {
3565            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3566        }
3567
3568        return updateFlagsForComponent(flags, userId, cookie);
3569    }
3570
3571    @Override
3572    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3573        if (!sUserManager.exists(userId)) return null;
3574        flags = updateFlagsForComponent(flags, userId, component);
3575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3576                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3577        synchronized (mPackages) {
3578            PackageParser.Activity a = mActivities.mActivities.get(component);
3579
3580            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3581            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3582                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3583                if (ps == null) return null;
3584                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3585                        userId);
3586            }
3587            if (mResolveComponentName.equals(component)) {
3588                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3589                        new PackageUserState(), userId);
3590            }
3591        }
3592        return null;
3593    }
3594
3595    @Override
3596    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3597            String resolvedType) {
3598        synchronized (mPackages) {
3599            if (component.equals(mResolveComponentName)) {
3600                // The resolver supports EVERYTHING!
3601                return true;
3602            }
3603            PackageParser.Activity a = mActivities.mActivities.get(component);
3604            if (a == null) {
3605                return false;
3606            }
3607            for (int i=0; i<a.intents.size(); i++) {
3608                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3609                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3610                    return true;
3611                }
3612            }
3613            return false;
3614        }
3615    }
3616
3617    @Override
3618    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3619        if (!sUserManager.exists(userId)) return null;
3620        flags = updateFlagsForComponent(flags, userId, component);
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3622                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3623        synchronized (mPackages) {
3624            PackageParser.Activity a = mReceivers.mActivities.get(component);
3625            if (DEBUG_PACKAGE_INFO) Log.v(
3626                TAG, "getReceiverInfo " + component + ": " + a);
3627            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3628                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3629                if (ps == null) return null;
3630                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3631                        userId);
3632            }
3633        }
3634        return null;
3635    }
3636
3637    @Override
3638    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3639        if (!sUserManager.exists(userId)) return null;
3640        flags = updateFlagsForComponent(flags, userId, component);
3641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3642                false /* requireFullPermission */, false /* checkShell */, "get service info");
3643        synchronized (mPackages) {
3644            PackageParser.Service s = mServices.mServices.get(component);
3645            if (DEBUG_PACKAGE_INFO) Log.v(
3646                TAG, "getServiceInfo " + component + ": " + s);
3647            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3648                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3649                if (ps == null) return null;
3650                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3651                        userId);
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3659        if (!sUserManager.exists(userId)) return null;
3660        flags = updateFlagsForComponent(flags, userId, component);
3661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3662                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3663        synchronized (mPackages) {
3664            PackageParser.Provider p = mProviders.mProviders.get(component);
3665            if (DEBUG_PACKAGE_INFO) Log.v(
3666                TAG, "getProviderInfo " + component + ": " + p);
3667            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3668                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3669                if (ps == null) return null;
3670                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3671                        userId);
3672            }
3673        }
3674        return null;
3675    }
3676
3677    @Override
3678    public String[] getSystemSharedLibraryNames() {
3679        Set<String> libSet;
3680        synchronized (mPackages) {
3681            libSet = mSharedLibraries.keySet();
3682            int size = libSet.size();
3683            if (size > 0) {
3684                String[] libs = new String[size];
3685                libSet.toArray(libs);
3686                return libs;
3687            }
3688        }
3689        return null;
3690    }
3691
3692    @Override
3693    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3694        synchronized (mPackages) {
3695            return mServicesSystemSharedLibraryPackageName;
3696        }
3697    }
3698
3699    @Override
3700    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3701        synchronized (mPackages) {
3702            return mSharedSystemSharedLibraryPackageName;
3703        }
3704    }
3705
3706    @Override
3707    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3708        synchronized (mPackages) {
3709            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3710
3711            final FeatureInfo fi = new FeatureInfo();
3712            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3713                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3714            res.add(fi);
3715
3716            return new ParceledListSlice<>(res);
3717        }
3718    }
3719
3720    @Override
3721    public boolean hasSystemFeature(String name, int version) {
3722        synchronized (mPackages) {
3723            final FeatureInfo feat = mAvailableFeatures.get(name);
3724            if (feat == null) {
3725                return false;
3726            } else {
3727                return feat.version >= version;
3728            }
3729        }
3730    }
3731
3732    @Override
3733    public int checkPermission(String permName, String pkgName, int userId) {
3734        if (!sUserManager.exists(userId)) {
3735            return PackageManager.PERMISSION_DENIED;
3736        }
3737
3738        synchronized (mPackages) {
3739            final PackageParser.Package p = mPackages.get(pkgName);
3740            if (p != null && p.mExtras != null) {
3741                final PackageSetting ps = (PackageSetting) p.mExtras;
3742                final PermissionsState permissionsState = ps.getPermissionsState();
3743                if (permissionsState.hasPermission(permName, userId)) {
3744                    return PackageManager.PERMISSION_GRANTED;
3745                }
3746                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3747                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3748                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3749                    return PackageManager.PERMISSION_GRANTED;
3750                }
3751            }
3752        }
3753
3754        return PackageManager.PERMISSION_DENIED;
3755    }
3756
3757    @Override
3758    public int checkUidPermission(String permName, int uid) {
3759        final int userId = UserHandle.getUserId(uid);
3760
3761        if (!sUserManager.exists(userId)) {
3762            return PackageManager.PERMISSION_DENIED;
3763        }
3764
3765        synchronized (mPackages) {
3766            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3767            if (obj != null) {
3768                final SettingBase ps = (SettingBase) obj;
3769                final PermissionsState permissionsState = ps.getPermissionsState();
3770                if (permissionsState.hasPermission(permName, userId)) {
3771                    return PackageManager.PERMISSION_GRANTED;
3772                }
3773                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3774                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3775                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3776                    return PackageManager.PERMISSION_GRANTED;
3777                }
3778            } else {
3779                ArraySet<String> perms = mSystemPermissions.get(uid);
3780                if (perms != null) {
3781                    if (perms.contains(permName)) {
3782                        return PackageManager.PERMISSION_GRANTED;
3783                    }
3784                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3785                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3786                        return PackageManager.PERMISSION_GRANTED;
3787                    }
3788                }
3789            }
3790        }
3791
3792        return PackageManager.PERMISSION_DENIED;
3793    }
3794
3795    @Override
3796    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3797        if (UserHandle.getCallingUserId() != userId) {
3798            mContext.enforceCallingPermission(
3799                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3800                    "isPermissionRevokedByPolicy for user " + userId);
3801        }
3802
3803        if (checkPermission(permission, packageName, userId)
3804                == PackageManager.PERMISSION_GRANTED) {
3805            return false;
3806        }
3807
3808        final long identity = Binder.clearCallingIdentity();
3809        try {
3810            final int flags = getPermissionFlags(permission, packageName, userId);
3811            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3812        } finally {
3813            Binder.restoreCallingIdentity(identity);
3814        }
3815    }
3816
3817    @Override
3818    public String getPermissionControllerPackageName() {
3819        synchronized (mPackages) {
3820            return mRequiredInstallerPackage;
3821        }
3822    }
3823
3824    /**
3825     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3826     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3827     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3828     * @param message the message to log on security exception
3829     */
3830    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3831            boolean checkShell, String message) {
3832        if (userId < 0) {
3833            throw new IllegalArgumentException("Invalid userId " + userId);
3834        }
3835        if (checkShell) {
3836            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3837        }
3838        if (userId == UserHandle.getUserId(callingUid)) return;
3839        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3840            if (requireFullPermission) {
3841                mContext.enforceCallingOrSelfPermission(
3842                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3843            } else {
3844                try {
3845                    mContext.enforceCallingOrSelfPermission(
3846                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3847                } catch (SecurityException se) {
3848                    mContext.enforceCallingOrSelfPermission(
3849                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3850                }
3851            }
3852        }
3853    }
3854
3855    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3856        if (callingUid == Process.SHELL_UID) {
3857            if (userHandle >= 0
3858                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3859                throw new SecurityException("Shell does not have permission to access user "
3860                        + userHandle);
3861            } else if (userHandle < 0) {
3862                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3863                        + Debug.getCallers(3));
3864            }
3865        }
3866    }
3867
3868    private BasePermission findPermissionTreeLP(String permName) {
3869        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3870            if (permName.startsWith(bp.name) &&
3871                    permName.length() > bp.name.length() &&
3872                    permName.charAt(bp.name.length()) == '.') {
3873                return bp;
3874            }
3875        }
3876        return null;
3877    }
3878
3879    private BasePermission checkPermissionTreeLP(String permName) {
3880        if (permName != null) {
3881            BasePermission bp = findPermissionTreeLP(permName);
3882            if (bp != null) {
3883                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3884                    return bp;
3885                }
3886                throw new SecurityException("Calling uid "
3887                        + Binder.getCallingUid()
3888                        + " is not allowed to add to permission tree "
3889                        + bp.name + " owned by uid " + bp.uid);
3890            }
3891        }
3892        throw new SecurityException("No permission tree found for " + permName);
3893    }
3894
3895    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3896        if (s1 == null) {
3897            return s2 == null;
3898        }
3899        if (s2 == null) {
3900            return false;
3901        }
3902        if (s1.getClass() != s2.getClass()) {
3903            return false;
3904        }
3905        return s1.equals(s2);
3906    }
3907
3908    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3909        if (pi1.icon != pi2.icon) return false;
3910        if (pi1.logo != pi2.logo) return false;
3911        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3912        if (!compareStrings(pi1.name, pi2.name)) return false;
3913        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3914        // We'll take care of setting this one.
3915        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3916        // These are not currently stored in settings.
3917        //if (!compareStrings(pi1.group, pi2.group)) return false;
3918        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3919        //if (pi1.labelRes != pi2.labelRes) return false;
3920        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3921        return true;
3922    }
3923
3924    int permissionInfoFootprint(PermissionInfo info) {
3925        int size = info.name.length();
3926        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3927        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3928        return size;
3929    }
3930
3931    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3932        int size = 0;
3933        for (BasePermission perm : mSettings.mPermissions.values()) {
3934            if (perm.uid == tree.uid) {
3935                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3936            }
3937        }
3938        return size;
3939    }
3940
3941    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3942        // We calculate the max size of permissions defined by this uid and throw
3943        // if that plus the size of 'info' would exceed our stated maximum.
3944        if (tree.uid != Process.SYSTEM_UID) {
3945            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3946            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3947                throw new SecurityException("Permission tree size cap exceeded");
3948            }
3949        }
3950    }
3951
3952    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3953        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3954            throw new SecurityException("Label must be specified in permission");
3955        }
3956        BasePermission tree = checkPermissionTreeLP(info.name);
3957        BasePermission bp = mSettings.mPermissions.get(info.name);
3958        boolean added = bp == null;
3959        boolean changed = true;
3960        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3961        if (added) {
3962            enforcePermissionCapLocked(info, tree);
3963            bp = new BasePermission(info.name, tree.sourcePackage,
3964                    BasePermission.TYPE_DYNAMIC);
3965        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3966            throw new SecurityException(
3967                    "Not allowed to modify non-dynamic permission "
3968                    + info.name);
3969        } else {
3970            if (bp.protectionLevel == fixedLevel
3971                    && bp.perm.owner.equals(tree.perm.owner)
3972                    && bp.uid == tree.uid
3973                    && comparePermissionInfos(bp.perm.info, info)) {
3974                changed = false;
3975            }
3976        }
3977        bp.protectionLevel = fixedLevel;
3978        info = new PermissionInfo(info);
3979        info.protectionLevel = fixedLevel;
3980        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3981        bp.perm.info.packageName = tree.perm.info.packageName;
3982        bp.uid = tree.uid;
3983        if (added) {
3984            mSettings.mPermissions.put(info.name, bp);
3985        }
3986        if (changed) {
3987            if (!async) {
3988                mSettings.writeLPr();
3989            } else {
3990                scheduleWriteSettingsLocked();
3991            }
3992        }
3993        return added;
3994    }
3995
3996    @Override
3997    public boolean addPermission(PermissionInfo info) {
3998        synchronized (mPackages) {
3999            return addPermissionLocked(info, false);
4000        }
4001    }
4002
4003    @Override
4004    public boolean addPermissionAsync(PermissionInfo info) {
4005        synchronized (mPackages) {
4006            return addPermissionLocked(info, true);
4007        }
4008    }
4009
4010    @Override
4011    public void removePermission(String name) {
4012        synchronized (mPackages) {
4013            checkPermissionTreeLP(name);
4014            BasePermission bp = mSettings.mPermissions.get(name);
4015            if (bp != null) {
4016                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4017                    throw new SecurityException(
4018                            "Not allowed to modify non-dynamic permission "
4019                            + name);
4020                }
4021                mSettings.mPermissions.remove(name);
4022                mSettings.writeLPr();
4023            }
4024        }
4025    }
4026
4027    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4028            BasePermission bp) {
4029        int index = pkg.requestedPermissions.indexOf(bp.name);
4030        if (index == -1) {
4031            throw new SecurityException("Package " + pkg.packageName
4032                    + " has not requested permission " + bp.name);
4033        }
4034        if (!bp.isRuntime() && !bp.isDevelopment()) {
4035            throw new SecurityException("Permission " + bp.name
4036                    + " is not a changeable permission type");
4037        }
4038    }
4039
4040    @Override
4041    public void grantRuntimePermission(String packageName, String name, final int userId) {
4042        if (!sUserManager.exists(userId)) {
4043            Log.e(TAG, "No such user:" + userId);
4044            return;
4045        }
4046
4047        mContext.enforceCallingOrSelfPermission(
4048                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4049                "grantRuntimePermission");
4050
4051        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4052                true /* requireFullPermission */, true /* checkShell */,
4053                "grantRuntimePermission");
4054
4055        final int uid;
4056        final SettingBase sb;
4057
4058        synchronized (mPackages) {
4059            final PackageParser.Package pkg = mPackages.get(packageName);
4060            if (pkg == null) {
4061                throw new IllegalArgumentException("Unknown package: " + packageName);
4062            }
4063
4064            final BasePermission bp = mSettings.mPermissions.get(name);
4065            if (bp == null) {
4066                throw new IllegalArgumentException("Unknown permission: " + name);
4067            }
4068
4069            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4070
4071            // If a permission review is required for legacy apps we represent
4072            // their permissions as always granted runtime ones since we need
4073            // to keep the review required permission flag per user while an
4074            // install permission's state is shared across all users.
4075            if (Build.PERMISSIONS_REVIEW_REQUIRED
4076                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4077                    && bp.isRuntime()) {
4078                return;
4079            }
4080
4081            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4082            sb = (SettingBase) pkg.mExtras;
4083            if (sb == null) {
4084                throw new IllegalArgumentException("Unknown package: " + packageName);
4085            }
4086
4087            final PermissionsState permissionsState = sb.getPermissionsState();
4088
4089            final int flags = permissionsState.getPermissionFlags(name, userId);
4090            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4091                throw new SecurityException("Cannot grant system fixed permission "
4092                        + name + " for package " + packageName);
4093            }
4094
4095            if (bp.isDevelopment()) {
4096                // Development permissions must be handled specially, since they are not
4097                // normal runtime permissions.  For now they apply to all users.
4098                if (permissionsState.grantInstallPermission(bp) !=
4099                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4100                    scheduleWriteSettingsLocked();
4101                }
4102                return;
4103            }
4104
4105            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4106                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4107                return;
4108            }
4109
4110            final int result = permissionsState.grantRuntimePermission(bp, userId);
4111            switch (result) {
4112                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4113                    return;
4114                }
4115
4116                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4117                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4118                    mHandler.post(new Runnable() {
4119                        @Override
4120                        public void run() {
4121                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4122                        }
4123                    });
4124                }
4125                break;
4126            }
4127
4128            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4129
4130            // Not critical if that is lost - app has to request again.
4131            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4132        }
4133
4134        // Only need to do this if user is initialized. Otherwise it's a new user
4135        // and there are no processes running as the user yet and there's no need
4136        // to make an expensive call to remount processes for the changed permissions.
4137        if (READ_EXTERNAL_STORAGE.equals(name)
4138                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4139            final long token = Binder.clearCallingIdentity();
4140            try {
4141                if (sUserManager.isInitialized(userId)) {
4142                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4143                            MountServiceInternal.class);
4144                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4145                }
4146            } finally {
4147                Binder.restoreCallingIdentity(token);
4148            }
4149        }
4150    }
4151
4152    @Override
4153    public void revokeRuntimePermission(String packageName, String name, int userId) {
4154        if (!sUserManager.exists(userId)) {
4155            Log.e(TAG, "No such user:" + userId);
4156            return;
4157        }
4158
4159        mContext.enforceCallingOrSelfPermission(
4160                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4161                "revokeRuntimePermission");
4162
4163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4164                true /* requireFullPermission */, true /* checkShell */,
4165                "revokeRuntimePermission");
4166
4167        final int appId;
4168
4169        synchronized (mPackages) {
4170            final PackageParser.Package pkg = mPackages.get(packageName);
4171            if (pkg == null) {
4172                throw new IllegalArgumentException("Unknown package: " + packageName);
4173            }
4174
4175            final BasePermission bp = mSettings.mPermissions.get(name);
4176            if (bp == null) {
4177                throw new IllegalArgumentException("Unknown permission: " + name);
4178            }
4179
4180            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4181
4182            // If a permission review is required for legacy apps we represent
4183            // their permissions as always granted runtime ones since we need
4184            // to keep the review required permission flag per user while an
4185            // install permission's state is shared across all users.
4186            if (Build.PERMISSIONS_REVIEW_REQUIRED
4187                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4188                    && bp.isRuntime()) {
4189                return;
4190            }
4191
4192            SettingBase sb = (SettingBase) pkg.mExtras;
4193            if (sb == null) {
4194                throw new IllegalArgumentException("Unknown package: " + packageName);
4195            }
4196
4197            final PermissionsState permissionsState = sb.getPermissionsState();
4198
4199            final int flags = permissionsState.getPermissionFlags(name, userId);
4200            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4201                throw new SecurityException("Cannot revoke system fixed permission "
4202                        + name + " for package " + packageName);
4203            }
4204
4205            if (bp.isDevelopment()) {
4206                // Development permissions must be handled specially, since they are not
4207                // normal runtime permissions.  For now they apply to all users.
4208                if (permissionsState.revokeInstallPermission(bp) !=
4209                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4210                    scheduleWriteSettingsLocked();
4211                }
4212                return;
4213            }
4214
4215            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4216                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4217                return;
4218            }
4219
4220            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4221
4222            // Critical, after this call app should never have the permission.
4223            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4224
4225            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4226        }
4227
4228        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4229    }
4230
4231    @Override
4232    public void resetRuntimePermissions() {
4233        mContext.enforceCallingOrSelfPermission(
4234                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4235                "revokeRuntimePermission");
4236
4237        int callingUid = Binder.getCallingUid();
4238        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4239            mContext.enforceCallingOrSelfPermission(
4240                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4241                    "resetRuntimePermissions");
4242        }
4243
4244        synchronized (mPackages) {
4245            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4246            for (int userId : UserManagerService.getInstance().getUserIds()) {
4247                final int packageCount = mPackages.size();
4248                for (int i = 0; i < packageCount; i++) {
4249                    PackageParser.Package pkg = mPackages.valueAt(i);
4250                    if (!(pkg.mExtras instanceof PackageSetting)) {
4251                        continue;
4252                    }
4253                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4254                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4255                }
4256            }
4257        }
4258    }
4259
4260    @Override
4261    public int getPermissionFlags(String name, String packageName, int userId) {
4262        if (!sUserManager.exists(userId)) {
4263            return 0;
4264        }
4265
4266        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4267
4268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4269                true /* requireFullPermission */, false /* checkShell */,
4270                "getPermissionFlags");
4271
4272        synchronized (mPackages) {
4273            final PackageParser.Package pkg = mPackages.get(packageName);
4274            if (pkg == null) {
4275                throw new IllegalArgumentException("Unknown package: " + packageName);
4276            }
4277
4278            final BasePermission bp = mSettings.mPermissions.get(name);
4279            if (bp == null) {
4280                throw new IllegalArgumentException("Unknown permission: " + name);
4281            }
4282
4283            SettingBase sb = (SettingBase) pkg.mExtras;
4284            if (sb == null) {
4285                throw new IllegalArgumentException("Unknown package: " + packageName);
4286            }
4287
4288            PermissionsState permissionsState = sb.getPermissionsState();
4289            return permissionsState.getPermissionFlags(name, userId);
4290        }
4291    }
4292
4293    @Override
4294    public void updatePermissionFlags(String name, String packageName, int flagMask,
4295            int flagValues, int userId) {
4296        if (!sUserManager.exists(userId)) {
4297            return;
4298        }
4299
4300        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4301
4302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4303                true /* requireFullPermission */, true /* checkShell */,
4304                "updatePermissionFlags");
4305
4306        // Only the system can change these flags and nothing else.
4307        if (getCallingUid() != Process.SYSTEM_UID) {
4308            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4309            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4310            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4311            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4312            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4313        }
4314
4315        synchronized (mPackages) {
4316            final PackageParser.Package pkg = mPackages.get(packageName);
4317            if (pkg == null) {
4318                throw new IllegalArgumentException("Unknown package: " + packageName);
4319            }
4320
4321            final BasePermission bp = mSettings.mPermissions.get(name);
4322            if (bp == null) {
4323                throw new IllegalArgumentException("Unknown permission: " + name);
4324            }
4325
4326            SettingBase sb = (SettingBase) pkg.mExtras;
4327            if (sb == null) {
4328                throw new IllegalArgumentException("Unknown package: " + packageName);
4329            }
4330
4331            PermissionsState permissionsState = sb.getPermissionsState();
4332
4333            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4334
4335            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4336                // Install and runtime permissions are stored in different places,
4337                // so figure out what permission changed and persist the change.
4338                if (permissionsState.getInstallPermissionState(name) != null) {
4339                    scheduleWriteSettingsLocked();
4340                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4341                        || hadState) {
4342                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4343                }
4344            }
4345        }
4346    }
4347
4348    /**
4349     * Update the permission flags for all packages and runtime permissions of a user in order
4350     * to allow device or profile owner to remove POLICY_FIXED.
4351     */
4352    @Override
4353    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4354        if (!sUserManager.exists(userId)) {
4355            return;
4356        }
4357
4358        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4359
4360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4361                true /* requireFullPermission */, true /* checkShell */,
4362                "updatePermissionFlagsForAllApps");
4363
4364        // Only the system can change system fixed flags.
4365        if (getCallingUid() != Process.SYSTEM_UID) {
4366            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4367            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4368        }
4369
4370        synchronized (mPackages) {
4371            boolean changed = false;
4372            final int packageCount = mPackages.size();
4373            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4374                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4375                SettingBase sb = (SettingBase) pkg.mExtras;
4376                if (sb == null) {
4377                    continue;
4378                }
4379                PermissionsState permissionsState = sb.getPermissionsState();
4380                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4381                        userId, flagMask, flagValues);
4382            }
4383            if (changed) {
4384                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4385            }
4386        }
4387    }
4388
4389    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4390        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4391                != PackageManager.PERMISSION_GRANTED
4392            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4393                != PackageManager.PERMISSION_GRANTED) {
4394            throw new SecurityException(message + " requires "
4395                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4396                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4397        }
4398    }
4399
4400    @Override
4401    public boolean shouldShowRequestPermissionRationale(String permissionName,
4402            String packageName, int userId) {
4403        if (UserHandle.getCallingUserId() != userId) {
4404            mContext.enforceCallingPermission(
4405                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4406                    "canShowRequestPermissionRationale for user " + userId);
4407        }
4408
4409        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4410        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4411            return false;
4412        }
4413
4414        if (checkPermission(permissionName, packageName, userId)
4415                == PackageManager.PERMISSION_GRANTED) {
4416            return false;
4417        }
4418
4419        final int flags;
4420
4421        final long identity = Binder.clearCallingIdentity();
4422        try {
4423            flags = getPermissionFlags(permissionName,
4424                    packageName, userId);
4425        } finally {
4426            Binder.restoreCallingIdentity(identity);
4427        }
4428
4429        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4430                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4431                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4432
4433        if ((flags & fixedFlags) != 0) {
4434            return false;
4435        }
4436
4437        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4438    }
4439
4440    @Override
4441    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4442        mContext.enforceCallingOrSelfPermission(
4443                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4444                "addOnPermissionsChangeListener");
4445
4446        synchronized (mPackages) {
4447            mOnPermissionChangeListeners.addListenerLocked(listener);
4448        }
4449    }
4450
4451    @Override
4452    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4453        synchronized (mPackages) {
4454            mOnPermissionChangeListeners.removeListenerLocked(listener);
4455        }
4456    }
4457
4458    @Override
4459    public boolean isProtectedBroadcast(String actionName) {
4460        synchronized (mPackages) {
4461            if (mProtectedBroadcasts.contains(actionName)) {
4462                return true;
4463            } else if (actionName != null) {
4464                // TODO: remove these terrible hacks
4465                if (actionName.startsWith("android.net.netmon.lingerExpired")
4466                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4467                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4468                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4469                    return true;
4470                }
4471            }
4472        }
4473        return false;
4474    }
4475
4476    @Override
4477    public int checkSignatures(String pkg1, String pkg2) {
4478        synchronized (mPackages) {
4479            final PackageParser.Package p1 = mPackages.get(pkg1);
4480            final PackageParser.Package p2 = mPackages.get(pkg2);
4481            if (p1 == null || p1.mExtras == null
4482                    || p2 == null || p2.mExtras == null) {
4483                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4484            }
4485            return compareSignatures(p1.mSignatures, p2.mSignatures);
4486        }
4487    }
4488
4489    @Override
4490    public int checkUidSignatures(int uid1, int uid2) {
4491        // Map to base uids.
4492        uid1 = UserHandle.getAppId(uid1);
4493        uid2 = UserHandle.getAppId(uid2);
4494        // reader
4495        synchronized (mPackages) {
4496            Signature[] s1;
4497            Signature[] s2;
4498            Object obj = mSettings.getUserIdLPr(uid1);
4499            if (obj != null) {
4500                if (obj instanceof SharedUserSetting) {
4501                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4502                } else if (obj instanceof PackageSetting) {
4503                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4504                } else {
4505                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4506                }
4507            } else {
4508                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4509            }
4510            obj = mSettings.getUserIdLPr(uid2);
4511            if (obj != null) {
4512                if (obj instanceof SharedUserSetting) {
4513                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4514                } else if (obj instanceof PackageSetting) {
4515                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4516                } else {
4517                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4518                }
4519            } else {
4520                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4521            }
4522            return compareSignatures(s1, s2);
4523        }
4524    }
4525
4526    /**
4527     * This method should typically only be used when granting or revoking
4528     * permissions, since the app may immediately restart after this call.
4529     * <p>
4530     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4531     * guard your work against the app being relaunched.
4532     */
4533    private void killUid(int appId, int userId, String reason) {
4534        final long identity = Binder.clearCallingIdentity();
4535        try {
4536            IActivityManager am = ActivityManagerNative.getDefault();
4537            if (am != null) {
4538                try {
4539                    am.killUid(appId, userId, reason);
4540                } catch (RemoteException e) {
4541                    /* ignore - same process */
4542                }
4543            }
4544        } finally {
4545            Binder.restoreCallingIdentity(identity);
4546        }
4547    }
4548
4549    /**
4550     * Compares two sets of signatures. Returns:
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4555     * <br />
4556     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4557     * <br />
4558     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4559     * <br />
4560     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4561     */
4562    static int compareSignatures(Signature[] s1, Signature[] s2) {
4563        if (s1 == null) {
4564            return s2 == null
4565                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4566                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4567        }
4568
4569        if (s2 == null) {
4570            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4571        }
4572
4573        if (s1.length != s2.length) {
4574            return PackageManager.SIGNATURE_NO_MATCH;
4575        }
4576
4577        // Since both signature sets are of size 1, we can compare without HashSets.
4578        if (s1.length == 1) {
4579            return s1[0].equals(s2[0]) ?
4580                    PackageManager.SIGNATURE_MATCH :
4581                    PackageManager.SIGNATURE_NO_MATCH;
4582        }
4583
4584        ArraySet<Signature> set1 = new ArraySet<Signature>();
4585        for (Signature sig : s1) {
4586            set1.add(sig);
4587        }
4588        ArraySet<Signature> set2 = new ArraySet<Signature>();
4589        for (Signature sig : s2) {
4590            set2.add(sig);
4591        }
4592        // Make sure s2 contains all signatures in s1.
4593        if (set1.equals(set2)) {
4594            return PackageManager.SIGNATURE_MATCH;
4595        }
4596        return PackageManager.SIGNATURE_NO_MATCH;
4597    }
4598
4599    /**
4600     * If the database version for this type of package (internal storage or
4601     * external storage) is less than the version where package signatures
4602     * were updated, return true.
4603     */
4604    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4605        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4606        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4607    }
4608
4609    /**
4610     * Used for backward compatibility to make sure any packages with
4611     * certificate chains get upgraded to the new style. {@code existingSigs}
4612     * will be in the old format (since they were stored on disk from before the
4613     * system upgrade) and {@code scannedSigs} will be in the newer format.
4614     */
4615    private int compareSignaturesCompat(PackageSignatures existingSigs,
4616            PackageParser.Package scannedPkg) {
4617        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4618            return PackageManager.SIGNATURE_NO_MATCH;
4619        }
4620
4621        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4622        for (Signature sig : existingSigs.mSignatures) {
4623            existingSet.add(sig);
4624        }
4625        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4626        for (Signature sig : scannedPkg.mSignatures) {
4627            try {
4628                Signature[] chainSignatures = sig.getChainSignatures();
4629                for (Signature chainSig : chainSignatures) {
4630                    scannedCompatSet.add(chainSig);
4631                }
4632            } catch (CertificateEncodingException e) {
4633                scannedCompatSet.add(sig);
4634            }
4635        }
4636        /*
4637         * Make sure the expanded scanned set contains all signatures in the
4638         * existing one.
4639         */
4640        if (scannedCompatSet.equals(existingSet)) {
4641            // Migrate the old signatures to the new scheme.
4642            existingSigs.assignSignatures(scannedPkg.mSignatures);
4643            // The new KeySets will be re-added later in the scanning process.
4644            synchronized (mPackages) {
4645                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4646            }
4647            return PackageManager.SIGNATURE_MATCH;
4648        }
4649        return PackageManager.SIGNATURE_NO_MATCH;
4650    }
4651
4652    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4653        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4654        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4655    }
4656
4657    private int compareSignaturesRecover(PackageSignatures existingSigs,
4658            PackageParser.Package scannedPkg) {
4659        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4660            return PackageManager.SIGNATURE_NO_MATCH;
4661        }
4662
4663        String msg = null;
4664        try {
4665            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4666                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4667                        + scannedPkg.packageName);
4668                return PackageManager.SIGNATURE_MATCH;
4669            }
4670        } catch (CertificateException e) {
4671            msg = e.getMessage();
4672        }
4673
4674        logCriticalInfo(Log.INFO,
4675                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4676        return PackageManager.SIGNATURE_NO_MATCH;
4677    }
4678
4679    @Override
4680    public List<String> getAllPackages() {
4681        synchronized (mPackages) {
4682            return new ArrayList<String>(mPackages.keySet());
4683        }
4684    }
4685
4686    @Override
4687    public String[] getPackagesForUid(int uid) {
4688        uid = UserHandle.getAppId(uid);
4689        // reader
4690        synchronized (mPackages) {
4691            Object obj = mSettings.getUserIdLPr(uid);
4692            if (obj instanceof SharedUserSetting) {
4693                final SharedUserSetting sus = (SharedUserSetting) obj;
4694                final int N = sus.packages.size();
4695                final String[] res = new String[N];
4696                final Iterator<PackageSetting> it = sus.packages.iterator();
4697                int i = 0;
4698                while (it.hasNext()) {
4699                    res[i++] = it.next().name;
4700                }
4701                return res;
4702            } else if (obj instanceof PackageSetting) {
4703                final PackageSetting ps = (PackageSetting) obj;
4704                return new String[] { ps.name };
4705            }
4706        }
4707        return null;
4708    }
4709
4710    @Override
4711    public String getNameForUid(int uid) {
4712        // reader
4713        synchronized (mPackages) {
4714            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4715            if (obj instanceof SharedUserSetting) {
4716                final SharedUserSetting sus = (SharedUserSetting) obj;
4717                return sus.name + ":" + sus.userId;
4718            } else if (obj instanceof PackageSetting) {
4719                final PackageSetting ps = (PackageSetting) obj;
4720                return ps.name;
4721            }
4722        }
4723        return null;
4724    }
4725
4726    @Override
4727    public int getUidForSharedUser(String sharedUserName) {
4728        if(sharedUserName == null) {
4729            return -1;
4730        }
4731        // reader
4732        synchronized (mPackages) {
4733            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4734            if (suid == null) {
4735                return -1;
4736            }
4737            return suid.userId;
4738        }
4739    }
4740
4741    @Override
4742    public int getFlagsForUid(int uid) {
4743        synchronized (mPackages) {
4744            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4745            if (obj instanceof SharedUserSetting) {
4746                final SharedUserSetting sus = (SharedUserSetting) obj;
4747                return sus.pkgFlags;
4748            } else if (obj instanceof PackageSetting) {
4749                final PackageSetting ps = (PackageSetting) obj;
4750                return ps.pkgFlags;
4751            }
4752        }
4753        return 0;
4754    }
4755
4756    @Override
4757    public int getPrivateFlagsForUid(int uid) {
4758        synchronized (mPackages) {
4759            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4760            if (obj instanceof SharedUserSetting) {
4761                final SharedUserSetting sus = (SharedUserSetting) obj;
4762                return sus.pkgPrivateFlags;
4763            } else if (obj instanceof PackageSetting) {
4764                final PackageSetting ps = (PackageSetting) obj;
4765                return ps.pkgPrivateFlags;
4766            }
4767        }
4768        return 0;
4769    }
4770
4771    @Override
4772    public boolean isUidPrivileged(int uid) {
4773        uid = UserHandle.getAppId(uid);
4774        // reader
4775        synchronized (mPackages) {
4776            Object obj = mSettings.getUserIdLPr(uid);
4777            if (obj instanceof SharedUserSetting) {
4778                final SharedUserSetting sus = (SharedUserSetting) obj;
4779                final Iterator<PackageSetting> it = sus.packages.iterator();
4780                while (it.hasNext()) {
4781                    if (it.next().isPrivileged()) {
4782                        return true;
4783                    }
4784                }
4785            } else if (obj instanceof PackageSetting) {
4786                final PackageSetting ps = (PackageSetting) obj;
4787                return ps.isPrivileged();
4788            }
4789        }
4790        return false;
4791    }
4792
4793    @Override
4794    public String[] getAppOpPermissionPackages(String permissionName) {
4795        synchronized (mPackages) {
4796            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4797            if (pkgs == null) {
4798                return null;
4799            }
4800            return pkgs.toArray(new String[pkgs.size()]);
4801        }
4802    }
4803
4804    @Override
4805    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4806            int flags, int userId) {
4807        try {
4808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4809
4810            if (!sUserManager.exists(userId)) return null;
4811            flags = updateFlagsForResolve(flags, userId, intent);
4812            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4813                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4814
4815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4816            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4817                    flags, userId);
4818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4819
4820            final ResolveInfo bestChoice =
4821                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4822
4823            if (isEphemeralAllowed(intent, query, userId)) {
4824                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4825                final EphemeralResolveInfo ai =
4826                        getEphemeralResolveInfo(intent, resolvedType, userId);
4827                if (ai != null) {
4828                    if (DEBUG_EPHEMERAL) {
4829                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4830                    }
4831                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4832                    bestChoice.ephemeralResolveInfo = ai;
4833                }
4834                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4835            }
4836            return bestChoice;
4837        } finally {
4838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4839        }
4840    }
4841
4842    @Override
4843    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4844            IntentFilter filter, int match, ComponentName activity) {
4845        final int userId = UserHandle.getCallingUserId();
4846        if (DEBUG_PREFERRED) {
4847            Log.v(TAG, "setLastChosenActivity intent=" + intent
4848                + " resolvedType=" + resolvedType
4849                + " flags=" + flags
4850                + " filter=" + filter
4851                + " match=" + match
4852                + " activity=" + activity);
4853            filter.dump(new PrintStreamPrinter(System.out), "    ");
4854        }
4855        intent.setComponent(null);
4856        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4857                userId);
4858        // Find any earlier preferred or last chosen entries and nuke them
4859        findPreferredActivity(intent, resolvedType,
4860                flags, query, 0, false, true, false, userId);
4861        // Add the new activity as the last chosen for this filter
4862        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4863                "Setting last chosen");
4864    }
4865
4866    @Override
4867    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4868        final int userId = UserHandle.getCallingUserId();
4869        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4870        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4871                userId);
4872        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4873                false, false, false, userId);
4874    }
4875
4876
4877    private boolean isEphemeralAllowed(
4878            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4879        // Short circuit and return early if possible.
4880        if (DISABLE_EPHEMERAL_APPS) {
4881            return false;
4882        }
4883        final int callingUser = UserHandle.getCallingUserId();
4884        if (callingUser != UserHandle.USER_SYSTEM) {
4885            return false;
4886        }
4887        if (mEphemeralResolverConnection == null) {
4888            return false;
4889        }
4890        if (intent.getComponent() != null) {
4891            return false;
4892        }
4893        if (intent.getPackage() != null) {
4894            return false;
4895        }
4896        final boolean isWebUri = hasWebURI(intent);
4897        if (!isWebUri) {
4898            return false;
4899        }
4900        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4901        synchronized (mPackages) {
4902            final int count = resolvedActivites.size();
4903            for (int n = 0; n < count; n++) {
4904                ResolveInfo info = resolvedActivites.get(n);
4905                String packageName = info.activityInfo.packageName;
4906                PackageSetting ps = mSettings.mPackages.get(packageName);
4907                if (ps != null) {
4908                    // Try to get the status from User settings first
4909                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4910                    int status = (int) (packedStatus >> 32);
4911                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4912                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4913                        if (DEBUG_EPHEMERAL) {
4914                            Slog.v(TAG, "DENY ephemeral apps;"
4915                                + " pkg: " + packageName + ", status: " + status);
4916                        }
4917                        return false;
4918                    }
4919                }
4920            }
4921        }
4922        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4923        return true;
4924    }
4925
4926    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4927            int userId) {
4928        MessageDigest digest = null;
4929        try {
4930            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4931        } catch (NoSuchAlgorithmException e) {
4932            // If we can't create a digest, ignore ephemeral apps.
4933            return null;
4934        }
4935
4936        final byte[] hostBytes = intent.getData().getHost().getBytes();
4937        final byte[] digestBytes = digest.digest(hostBytes);
4938        int shaPrefix =
4939                digestBytes[0] << 24
4940                | digestBytes[1] << 16
4941                | digestBytes[2] << 8
4942                | digestBytes[3] << 0;
4943        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4944                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4945        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4946            // No hash prefix match; there are no ephemeral apps for this domain.
4947            return null;
4948        }
4949        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4950            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4951            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4952                continue;
4953            }
4954            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4955            // No filters; this should never happen.
4956            if (filters.isEmpty()) {
4957                continue;
4958            }
4959            // We have a domain match; resolve the filters to see if anything matches.
4960            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4961            for (int j = filters.size() - 1; j >= 0; --j) {
4962                final EphemeralResolveIntentInfo intentInfo =
4963                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4964                ephemeralResolver.addFilter(intentInfo);
4965            }
4966            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4967                    intent, resolvedType, false /*defaultOnly*/, userId);
4968            if (!matchedResolveInfoList.isEmpty()) {
4969                return matchedResolveInfoList.get(0);
4970            }
4971        }
4972        // Hash or filter mis-match; no ephemeral apps for this domain.
4973        return null;
4974    }
4975
4976    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4977            int flags, List<ResolveInfo> query, int userId) {
4978        if (query != null) {
4979            final int N = query.size();
4980            if (N == 1) {
4981                return query.get(0);
4982            } else if (N > 1) {
4983                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4984                // If there is more than one activity with the same priority,
4985                // then let the user decide between them.
4986                ResolveInfo r0 = query.get(0);
4987                ResolveInfo r1 = query.get(1);
4988                if (DEBUG_INTENT_MATCHING || debug) {
4989                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4990                            + r1.activityInfo.name + "=" + r1.priority);
4991                }
4992                // If the first activity has a higher priority, or a different
4993                // default, then it is always desirable to pick it.
4994                if (r0.priority != r1.priority
4995                        || r0.preferredOrder != r1.preferredOrder
4996                        || r0.isDefault != r1.isDefault) {
4997                    return query.get(0);
4998                }
4999                // If we have saved a preference for a preferred activity for
5000                // this Intent, use that.
5001                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5002                        flags, query, r0.priority, true, false, debug, userId);
5003                if (ri != null) {
5004                    return ri;
5005                }
5006                ri = new ResolveInfo(mResolveInfo);
5007                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5008                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5009                ri.activityInfo.applicationInfo = new ApplicationInfo(
5010                        ri.activityInfo.applicationInfo);
5011                if (userId != 0) {
5012                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5013                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5014                }
5015                // Make sure that the resolver is displayable in car mode
5016                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5017                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5018                return ri;
5019            }
5020        }
5021        return null;
5022    }
5023
5024    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5025            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5026        final int N = query.size();
5027        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5028                .get(userId);
5029        // Get the list of persistent preferred activities that handle the intent
5030        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5031        List<PersistentPreferredActivity> pprefs = ppir != null
5032                ? ppir.queryIntent(intent, resolvedType,
5033                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5034                : null;
5035        if (pprefs != null && pprefs.size() > 0) {
5036            final int M = pprefs.size();
5037            for (int i=0; i<M; i++) {
5038                final PersistentPreferredActivity ppa = pprefs.get(i);
5039                if (DEBUG_PREFERRED || debug) {
5040                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5041                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5042                            + "\n  component=" + ppa.mComponent);
5043                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5044                }
5045                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5046                        flags | MATCH_DISABLED_COMPONENTS, userId);
5047                if (DEBUG_PREFERRED || debug) {
5048                    Slog.v(TAG, "Found persistent preferred activity:");
5049                    if (ai != null) {
5050                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5051                    } else {
5052                        Slog.v(TAG, "  null");
5053                    }
5054                }
5055                if (ai == null) {
5056                    // This previously registered persistent preferred activity
5057                    // component is no longer known. Ignore it and do NOT remove it.
5058                    continue;
5059                }
5060                for (int j=0; j<N; j++) {
5061                    final ResolveInfo ri = query.get(j);
5062                    if (!ri.activityInfo.applicationInfo.packageName
5063                            .equals(ai.applicationInfo.packageName)) {
5064                        continue;
5065                    }
5066                    if (!ri.activityInfo.name.equals(ai.name)) {
5067                        continue;
5068                    }
5069                    //  Found a persistent preference that can handle the intent.
5070                    if (DEBUG_PREFERRED || debug) {
5071                        Slog.v(TAG, "Returning persistent preferred activity: " +
5072                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5073                    }
5074                    return ri;
5075                }
5076            }
5077        }
5078        return null;
5079    }
5080
5081    // TODO: handle preferred activities missing while user has amnesia
5082    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5083            List<ResolveInfo> query, int priority, boolean always,
5084            boolean removeMatches, boolean debug, int userId) {
5085        if (!sUserManager.exists(userId)) return null;
5086        flags = updateFlagsForResolve(flags, userId, intent);
5087        // writer
5088        synchronized (mPackages) {
5089            if (intent.getSelector() != null) {
5090                intent = intent.getSelector();
5091            }
5092            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5093
5094            // Try to find a matching persistent preferred activity.
5095            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5096                    debug, userId);
5097
5098            // If a persistent preferred activity matched, use it.
5099            if (pri != null) {
5100                return pri;
5101            }
5102
5103            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5104            // Get the list of preferred activities that handle the intent
5105            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5106            List<PreferredActivity> prefs = pir != null
5107                    ? pir.queryIntent(intent, resolvedType,
5108                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5109                    : null;
5110            if (prefs != null && prefs.size() > 0) {
5111                boolean changed = false;
5112                try {
5113                    // First figure out how good the original match set is.
5114                    // We will only allow preferred activities that came
5115                    // from the same match quality.
5116                    int match = 0;
5117
5118                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5119
5120                    final int N = query.size();
5121                    for (int j=0; j<N; j++) {
5122                        final ResolveInfo ri = query.get(j);
5123                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5124                                + ": 0x" + Integer.toHexString(match));
5125                        if (ri.match > match) {
5126                            match = ri.match;
5127                        }
5128                    }
5129
5130                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5131                            + Integer.toHexString(match));
5132
5133                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5134                    final int M = prefs.size();
5135                    for (int i=0; i<M; i++) {
5136                        final PreferredActivity pa = prefs.get(i);
5137                        if (DEBUG_PREFERRED || debug) {
5138                            Slog.v(TAG, "Checking PreferredActivity ds="
5139                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5140                                    + "\n  component=" + pa.mPref.mComponent);
5141                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5142                        }
5143                        if (pa.mPref.mMatch != match) {
5144                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5145                                    + Integer.toHexString(pa.mPref.mMatch));
5146                            continue;
5147                        }
5148                        // If it's not an "always" type preferred activity and that's what we're
5149                        // looking for, skip it.
5150                        if (always && !pa.mPref.mAlways) {
5151                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5152                            continue;
5153                        }
5154                        final ActivityInfo ai = getActivityInfo(
5155                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5156                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5157                                userId);
5158                        if (DEBUG_PREFERRED || debug) {
5159                            Slog.v(TAG, "Found preferred activity:");
5160                            if (ai != null) {
5161                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5162                            } else {
5163                                Slog.v(TAG, "  null");
5164                            }
5165                        }
5166                        if (ai == null) {
5167                            // This previously registered preferred activity
5168                            // component is no longer known.  Most likely an update
5169                            // to the app was installed and in the new version this
5170                            // component no longer exists.  Clean it up by removing
5171                            // it from the preferred activities list, and skip it.
5172                            Slog.w(TAG, "Removing dangling preferred activity: "
5173                                    + pa.mPref.mComponent);
5174                            pir.removeFilter(pa);
5175                            changed = true;
5176                            continue;
5177                        }
5178                        for (int j=0; j<N; j++) {
5179                            final ResolveInfo ri = query.get(j);
5180                            if (!ri.activityInfo.applicationInfo.packageName
5181                                    .equals(ai.applicationInfo.packageName)) {
5182                                continue;
5183                            }
5184                            if (!ri.activityInfo.name.equals(ai.name)) {
5185                                continue;
5186                            }
5187
5188                            if (removeMatches) {
5189                                pir.removeFilter(pa);
5190                                changed = true;
5191                                if (DEBUG_PREFERRED) {
5192                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5193                                }
5194                                break;
5195                            }
5196
5197                            // Okay we found a previously set preferred or last chosen app.
5198                            // If the result set is different from when this
5199                            // was created, we need to clear it and re-ask the
5200                            // user their preference, if we're looking for an "always" type entry.
5201                            if (always && !pa.mPref.sameSet(query)) {
5202                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5203                                        + intent + " type " + resolvedType);
5204                                if (DEBUG_PREFERRED) {
5205                                    Slog.v(TAG, "Removing preferred activity since set changed "
5206                                            + pa.mPref.mComponent);
5207                                }
5208                                pir.removeFilter(pa);
5209                                // Re-add the filter as a "last chosen" entry (!always)
5210                                PreferredActivity lastChosen = new PreferredActivity(
5211                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5212                                pir.addFilter(lastChosen);
5213                                changed = true;
5214                                return null;
5215                            }
5216
5217                            // Yay! Either the set matched or we're looking for the last chosen
5218                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5219                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5220                            return ri;
5221                        }
5222                    }
5223                } finally {
5224                    if (changed) {
5225                        if (DEBUG_PREFERRED) {
5226                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5227                        }
5228                        scheduleWritePackageRestrictionsLocked(userId);
5229                    }
5230                }
5231            }
5232        }
5233        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5234        return null;
5235    }
5236
5237    /*
5238     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5239     */
5240    @Override
5241    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5242            int targetUserId) {
5243        mContext.enforceCallingOrSelfPermission(
5244                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5245        List<CrossProfileIntentFilter> matches =
5246                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5247        if (matches != null) {
5248            int size = matches.size();
5249            for (int i = 0; i < size; i++) {
5250                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5251            }
5252        }
5253        if (hasWebURI(intent)) {
5254            // cross-profile app linking works only towards the parent.
5255            final UserInfo parent = getProfileParent(sourceUserId);
5256            synchronized(mPackages) {
5257                int flags = updateFlagsForResolve(0, parent.id, intent);
5258                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5259                        intent, resolvedType, flags, sourceUserId, parent.id);
5260                return xpDomainInfo != null;
5261            }
5262        }
5263        return false;
5264    }
5265
5266    private UserInfo getProfileParent(int userId) {
5267        final long identity = Binder.clearCallingIdentity();
5268        try {
5269            return sUserManager.getProfileParent(userId);
5270        } finally {
5271            Binder.restoreCallingIdentity(identity);
5272        }
5273    }
5274
5275    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5276            String resolvedType, int userId) {
5277        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5278        if (resolver != null) {
5279            return resolver.queryIntent(intent, resolvedType, false, userId);
5280        }
5281        return null;
5282    }
5283
5284    @Override
5285    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5286            String resolvedType, int flags, int userId) {
5287        try {
5288            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5289
5290            return new ParceledListSlice<>(
5291                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5292        } finally {
5293            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5294        }
5295    }
5296
5297    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5298            String resolvedType, int flags, int userId) {
5299        if (!sUserManager.exists(userId)) return Collections.emptyList();
5300        flags = updateFlagsForResolve(flags, userId, intent);
5301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5302                false /* requireFullPermission */, false /* checkShell */,
5303                "query intent activities");
5304        ComponentName comp = intent.getComponent();
5305        if (comp == null) {
5306            if (intent.getSelector() != null) {
5307                intent = intent.getSelector();
5308                comp = intent.getComponent();
5309            }
5310        }
5311
5312        if (comp != null) {
5313            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5314            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5315            if (ai != null) {
5316                final ResolveInfo ri = new ResolveInfo();
5317                ri.activityInfo = ai;
5318                list.add(ri);
5319            }
5320            return list;
5321        }
5322
5323        // reader
5324        synchronized (mPackages) {
5325            final String pkgName = intent.getPackage();
5326            if (pkgName == null) {
5327                List<CrossProfileIntentFilter> matchingFilters =
5328                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5329                // Check for results that need to skip the current profile.
5330                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5331                        resolvedType, flags, userId);
5332                if (xpResolveInfo != null) {
5333                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5334                    result.add(xpResolveInfo);
5335                    return filterIfNotSystemUser(result, userId);
5336                }
5337
5338                // Check for results in the current profile.
5339                List<ResolveInfo> result = mActivities.queryIntent(
5340                        intent, resolvedType, flags, userId);
5341                result = filterIfNotSystemUser(result, userId);
5342
5343                // Check for cross profile results.
5344                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5345                xpResolveInfo = queryCrossProfileIntents(
5346                        matchingFilters, intent, resolvedType, flags, userId,
5347                        hasNonNegativePriorityResult);
5348                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5349                    boolean isVisibleToUser = filterIfNotSystemUser(
5350                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5351                    if (isVisibleToUser) {
5352                        result.add(xpResolveInfo);
5353                        Collections.sort(result, mResolvePrioritySorter);
5354                    }
5355                }
5356                if (hasWebURI(intent)) {
5357                    CrossProfileDomainInfo xpDomainInfo = null;
5358                    final UserInfo parent = getProfileParent(userId);
5359                    if (parent != null) {
5360                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5361                                flags, userId, parent.id);
5362                    }
5363                    if (xpDomainInfo != null) {
5364                        if (xpResolveInfo != null) {
5365                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5366                            // in the result.
5367                            result.remove(xpResolveInfo);
5368                        }
5369                        if (result.size() == 0) {
5370                            result.add(xpDomainInfo.resolveInfo);
5371                            return result;
5372                        }
5373                    } else if (result.size() <= 1) {
5374                        return result;
5375                    }
5376                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5377                            xpDomainInfo, userId);
5378                    Collections.sort(result, mResolvePrioritySorter);
5379                }
5380                return result;
5381            }
5382            final PackageParser.Package pkg = mPackages.get(pkgName);
5383            if (pkg != null) {
5384                return filterIfNotSystemUser(
5385                        mActivities.queryIntentForPackage(
5386                                intent, resolvedType, flags, pkg.activities, userId),
5387                        userId);
5388            }
5389            return new ArrayList<ResolveInfo>();
5390        }
5391    }
5392
5393    private static class CrossProfileDomainInfo {
5394        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5395        ResolveInfo resolveInfo;
5396        /* Best domain verification status of the activities found in the other profile */
5397        int bestDomainVerificationStatus;
5398    }
5399
5400    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5401            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5402        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5403                sourceUserId)) {
5404            return null;
5405        }
5406        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5407                resolvedType, flags, parentUserId);
5408
5409        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5410            return null;
5411        }
5412        CrossProfileDomainInfo result = null;
5413        int size = resultTargetUser.size();
5414        for (int i = 0; i < size; i++) {
5415            ResolveInfo riTargetUser = resultTargetUser.get(i);
5416            // Intent filter verification is only for filters that specify a host. So don't return
5417            // those that handle all web uris.
5418            if (riTargetUser.handleAllWebDataURI) {
5419                continue;
5420            }
5421            String packageName = riTargetUser.activityInfo.packageName;
5422            PackageSetting ps = mSettings.mPackages.get(packageName);
5423            if (ps == null) {
5424                continue;
5425            }
5426            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5427            int status = (int)(verificationState >> 32);
5428            if (result == null) {
5429                result = new CrossProfileDomainInfo();
5430                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5431                        sourceUserId, parentUserId);
5432                result.bestDomainVerificationStatus = status;
5433            } else {
5434                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5435                        result.bestDomainVerificationStatus);
5436            }
5437        }
5438        // Don't consider matches with status NEVER across profiles.
5439        if (result != null && result.bestDomainVerificationStatus
5440                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5441            return null;
5442        }
5443        return result;
5444    }
5445
5446    /**
5447     * Verification statuses are ordered from the worse to the best, except for
5448     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5449     */
5450    private int bestDomainVerificationStatus(int status1, int status2) {
5451        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5452            return status2;
5453        }
5454        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5455            return status1;
5456        }
5457        return (int) MathUtils.max(status1, status2);
5458    }
5459
5460    private boolean isUserEnabled(int userId) {
5461        long callingId = Binder.clearCallingIdentity();
5462        try {
5463            UserInfo userInfo = sUserManager.getUserInfo(userId);
5464            return userInfo != null && userInfo.isEnabled();
5465        } finally {
5466            Binder.restoreCallingIdentity(callingId);
5467        }
5468    }
5469
5470    /**
5471     * Filter out activities with systemUserOnly flag set, when current user is not System.
5472     *
5473     * @return filtered list
5474     */
5475    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5476        if (userId == UserHandle.USER_SYSTEM) {
5477            return resolveInfos;
5478        }
5479        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5480            ResolveInfo info = resolveInfos.get(i);
5481            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5482                resolveInfos.remove(i);
5483            }
5484        }
5485        return resolveInfos;
5486    }
5487
5488    /**
5489     * @param resolveInfos list of resolve infos in descending priority order
5490     * @return if the list contains a resolve info with non-negative priority
5491     */
5492    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5493        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5494    }
5495
5496    private static boolean hasWebURI(Intent intent) {
5497        if (intent.getData() == null) {
5498            return false;
5499        }
5500        final String scheme = intent.getScheme();
5501        if (TextUtils.isEmpty(scheme)) {
5502            return false;
5503        }
5504        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5505    }
5506
5507    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5508            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5509            int userId) {
5510        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5511
5512        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5513            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5514                    candidates.size());
5515        }
5516
5517        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5518        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5519        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5520        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5521        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5522        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5523
5524        synchronized (mPackages) {
5525            final int count = candidates.size();
5526            // First, try to use linked apps. Partition the candidates into four lists:
5527            // one for the final results, one for the "do not use ever", one for "undefined status"
5528            // and finally one for "browser app type".
5529            for (int n=0; n<count; n++) {
5530                ResolveInfo info = candidates.get(n);
5531                String packageName = info.activityInfo.packageName;
5532                PackageSetting ps = mSettings.mPackages.get(packageName);
5533                if (ps != null) {
5534                    // Add to the special match all list (Browser use case)
5535                    if (info.handleAllWebDataURI) {
5536                        matchAllList.add(info);
5537                        continue;
5538                    }
5539                    // Try to get the status from User settings first
5540                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5541                    int status = (int)(packedStatus >> 32);
5542                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5543                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5544                        if (DEBUG_DOMAIN_VERIFICATION) {
5545                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5546                                    + " : linkgen=" + linkGeneration);
5547                        }
5548                        // Use link-enabled generation as preferredOrder, i.e.
5549                        // prefer newly-enabled over earlier-enabled.
5550                        info.preferredOrder = linkGeneration;
5551                        alwaysList.add(info);
5552                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5553                        if (DEBUG_DOMAIN_VERIFICATION) {
5554                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5555                        }
5556                        neverList.add(info);
5557                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5558                        if (DEBUG_DOMAIN_VERIFICATION) {
5559                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5560                        }
5561                        alwaysAskList.add(info);
5562                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5563                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5564                        if (DEBUG_DOMAIN_VERIFICATION) {
5565                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5566                        }
5567                        undefinedList.add(info);
5568                    }
5569                }
5570            }
5571
5572            // We'll want to include browser possibilities in a few cases
5573            boolean includeBrowser = false;
5574
5575            // First try to add the "always" resolution(s) for the current user, if any
5576            if (alwaysList.size() > 0) {
5577                result.addAll(alwaysList);
5578            } else {
5579                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5580                result.addAll(undefinedList);
5581                // Maybe add one for the other profile.
5582                if (xpDomainInfo != null && (
5583                        xpDomainInfo.bestDomainVerificationStatus
5584                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5585                    result.add(xpDomainInfo.resolveInfo);
5586                }
5587                includeBrowser = true;
5588            }
5589
5590            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5591            // If there were 'always' entries their preferred order has been set, so we also
5592            // back that off to make the alternatives equivalent
5593            if (alwaysAskList.size() > 0) {
5594                for (ResolveInfo i : result) {
5595                    i.preferredOrder = 0;
5596                }
5597                result.addAll(alwaysAskList);
5598                includeBrowser = true;
5599            }
5600
5601            if (includeBrowser) {
5602                // Also add browsers (all of them or only the default one)
5603                if (DEBUG_DOMAIN_VERIFICATION) {
5604                    Slog.v(TAG, "   ...including browsers in candidate set");
5605                }
5606                if ((matchFlags & MATCH_ALL) != 0) {
5607                    result.addAll(matchAllList);
5608                } else {
5609                    // Browser/generic handling case.  If there's a default browser, go straight
5610                    // to that (but only if there is no other higher-priority match).
5611                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5612                    int maxMatchPrio = 0;
5613                    ResolveInfo defaultBrowserMatch = null;
5614                    final int numCandidates = matchAllList.size();
5615                    for (int n = 0; n < numCandidates; n++) {
5616                        ResolveInfo info = matchAllList.get(n);
5617                        // track the highest overall match priority...
5618                        if (info.priority > maxMatchPrio) {
5619                            maxMatchPrio = info.priority;
5620                        }
5621                        // ...and the highest-priority default browser match
5622                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5623                            if (defaultBrowserMatch == null
5624                                    || (defaultBrowserMatch.priority < info.priority)) {
5625                                if (debug) {
5626                                    Slog.v(TAG, "Considering default browser match " + info);
5627                                }
5628                                defaultBrowserMatch = info;
5629                            }
5630                        }
5631                    }
5632                    if (defaultBrowserMatch != null
5633                            && defaultBrowserMatch.priority >= maxMatchPrio
5634                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5635                    {
5636                        if (debug) {
5637                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5638                        }
5639                        result.add(defaultBrowserMatch);
5640                    } else {
5641                        result.addAll(matchAllList);
5642                    }
5643                }
5644
5645                // If there is nothing selected, add all candidates and remove the ones that the user
5646                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5647                if (result.size() == 0) {
5648                    result.addAll(candidates);
5649                    result.removeAll(neverList);
5650                }
5651            }
5652        }
5653        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5654            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5655                    result.size());
5656            for (ResolveInfo info : result) {
5657                Slog.v(TAG, "  + " + info.activityInfo);
5658            }
5659        }
5660        return result;
5661    }
5662
5663    // Returns a packed value as a long:
5664    //
5665    // high 'int'-sized word: link status: undefined/ask/never/always.
5666    // low 'int'-sized word: relative priority among 'always' results.
5667    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5668        long result = ps.getDomainVerificationStatusForUser(userId);
5669        // if none available, get the master status
5670        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5671            if (ps.getIntentFilterVerificationInfo() != null) {
5672                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5673            }
5674        }
5675        return result;
5676    }
5677
5678    private ResolveInfo querySkipCurrentProfileIntents(
5679            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5680            int flags, int sourceUserId) {
5681        if (matchingFilters != null) {
5682            int size = matchingFilters.size();
5683            for (int i = 0; i < size; i ++) {
5684                CrossProfileIntentFilter filter = matchingFilters.get(i);
5685                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5686                    // Checking if there are activities in the target user that can handle the
5687                    // intent.
5688                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5689                            resolvedType, flags, sourceUserId);
5690                    if (resolveInfo != null) {
5691                        return resolveInfo;
5692                    }
5693                }
5694            }
5695        }
5696        return null;
5697    }
5698
5699    // Return matching ResolveInfo in target user if any.
5700    private ResolveInfo queryCrossProfileIntents(
5701            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5702            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5703        if (matchingFilters != null) {
5704            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5705            // match the same intent. For performance reasons, it is better not to
5706            // run queryIntent twice for the same userId
5707            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5708            int size = matchingFilters.size();
5709            for (int i = 0; i < size; i++) {
5710                CrossProfileIntentFilter filter = matchingFilters.get(i);
5711                int targetUserId = filter.getTargetUserId();
5712                boolean skipCurrentProfile =
5713                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5714                boolean skipCurrentProfileIfNoMatchFound =
5715                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5716                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5717                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5718                    // Checking if there are activities in the target user that can handle the
5719                    // intent.
5720                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5721                            resolvedType, flags, sourceUserId);
5722                    if (resolveInfo != null) return resolveInfo;
5723                    alreadyTriedUserIds.put(targetUserId, true);
5724                }
5725            }
5726        }
5727        return null;
5728    }
5729
5730    /**
5731     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5732     * will forward the intent to the filter's target user.
5733     * Otherwise, returns null.
5734     */
5735    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5736            String resolvedType, int flags, int sourceUserId) {
5737        int targetUserId = filter.getTargetUserId();
5738        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5739                resolvedType, flags, targetUserId);
5740        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5741            // If all the matches in the target profile are suspended, return null.
5742            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5743                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5744                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5745                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5746                            targetUserId);
5747                }
5748            }
5749        }
5750        return null;
5751    }
5752
5753    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5754            int sourceUserId, int targetUserId) {
5755        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5756        long ident = Binder.clearCallingIdentity();
5757        boolean targetIsProfile;
5758        try {
5759            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5760        } finally {
5761            Binder.restoreCallingIdentity(ident);
5762        }
5763        String className;
5764        if (targetIsProfile) {
5765            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5766        } else {
5767            className = FORWARD_INTENT_TO_PARENT;
5768        }
5769        ComponentName forwardingActivityComponentName = new ComponentName(
5770                mAndroidApplication.packageName, className);
5771        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5772                sourceUserId);
5773        if (!targetIsProfile) {
5774            forwardingActivityInfo.showUserIcon = targetUserId;
5775            forwardingResolveInfo.noResourceId = true;
5776        }
5777        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5778        forwardingResolveInfo.priority = 0;
5779        forwardingResolveInfo.preferredOrder = 0;
5780        forwardingResolveInfo.match = 0;
5781        forwardingResolveInfo.isDefault = true;
5782        forwardingResolveInfo.filter = filter;
5783        forwardingResolveInfo.targetUserId = targetUserId;
5784        return forwardingResolveInfo;
5785    }
5786
5787    @Override
5788    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5789            Intent[] specifics, String[] specificTypes, Intent intent,
5790            String resolvedType, int flags, int userId) {
5791        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5792                specificTypes, intent, resolvedType, flags, userId));
5793    }
5794
5795    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5796            Intent[] specifics, String[] specificTypes, Intent intent,
5797            String resolvedType, int flags, int userId) {
5798        if (!sUserManager.exists(userId)) return Collections.emptyList();
5799        flags = updateFlagsForResolve(flags, userId, intent);
5800        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5801                false /* requireFullPermission */, false /* checkShell */,
5802                "query intent activity options");
5803        final String resultsAction = intent.getAction();
5804
5805        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5806                | PackageManager.GET_RESOLVED_FILTER, userId);
5807
5808        if (DEBUG_INTENT_MATCHING) {
5809            Log.v(TAG, "Query " + intent + ": " + results);
5810        }
5811
5812        int specificsPos = 0;
5813        int N;
5814
5815        // todo: note that the algorithm used here is O(N^2).  This
5816        // isn't a problem in our current environment, but if we start running
5817        // into situations where we have more than 5 or 10 matches then this
5818        // should probably be changed to something smarter...
5819
5820        // First we go through and resolve each of the specific items
5821        // that were supplied, taking care of removing any corresponding
5822        // duplicate items in the generic resolve list.
5823        if (specifics != null) {
5824            for (int i=0; i<specifics.length; i++) {
5825                final Intent sintent = specifics[i];
5826                if (sintent == null) {
5827                    continue;
5828                }
5829
5830                if (DEBUG_INTENT_MATCHING) {
5831                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5832                }
5833
5834                String action = sintent.getAction();
5835                if (resultsAction != null && resultsAction.equals(action)) {
5836                    // If this action was explicitly requested, then don't
5837                    // remove things that have it.
5838                    action = null;
5839                }
5840
5841                ResolveInfo ri = null;
5842                ActivityInfo ai = null;
5843
5844                ComponentName comp = sintent.getComponent();
5845                if (comp == null) {
5846                    ri = resolveIntent(
5847                        sintent,
5848                        specificTypes != null ? specificTypes[i] : null,
5849                            flags, userId);
5850                    if (ri == null) {
5851                        continue;
5852                    }
5853                    if (ri == mResolveInfo) {
5854                        // ACK!  Must do something better with this.
5855                    }
5856                    ai = ri.activityInfo;
5857                    comp = new ComponentName(ai.applicationInfo.packageName,
5858                            ai.name);
5859                } else {
5860                    ai = getActivityInfo(comp, flags, userId);
5861                    if (ai == null) {
5862                        continue;
5863                    }
5864                }
5865
5866                // Look for any generic query activities that are duplicates
5867                // of this specific one, and remove them from the results.
5868                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5869                N = results.size();
5870                int j;
5871                for (j=specificsPos; j<N; j++) {
5872                    ResolveInfo sri = results.get(j);
5873                    if ((sri.activityInfo.name.equals(comp.getClassName())
5874                            && sri.activityInfo.applicationInfo.packageName.equals(
5875                                    comp.getPackageName()))
5876                        || (action != null && sri.filter.matchAction(action))) {
5877                        results.remove(j);
5878                        if (DEBUG_INTENT_MATCHING) Log.v(
5879                            TAG, "Removing duplicate item from " + j
5880                            + " due to specific " + specificsPos);
5881                        if (ri == null) {
5882                            ri = sri;
5883                        }
5884                        j--;
5885                        N--;
5886                    }
5887                }
5888
5889                // Add this specific item to its proper place.
5890                if (ri == null) {
5891                    ri = new ResolveInfo();
5892                    ri.activityInfo = ai;
5893                }
5894                results.add(specificsPos, ri);
5895                ri.specificIndex = i;
5896                specificsPos++;
5897            }
5898        }
5899
5900        // Now we go through the remaining generic results and remove any
5901        // duplicate actions that are found here.
5902        N = results.size();
5903        for (int i=specificsPos; i<N-1; i++) {
5904            final ResolveInfo rii = results.get(i);
5905            if (rii.filter == null) {
5906                continue;
5907            }
5908
5909            // Iterate over all of the actions of this result's intent
5910            // filter...  typically this should be just one.
5911            final Iterator<String> it = rii.filter.actionsIterator();
5912            if (it == null) {
5913                continue;
5914            }
5915            while (it.hasNext()) {
5916                final String action = it.next();
5917                if (resultsAction != null && resultsAction.equals(action)) {
5918                    // If this action was explicitly requested, then don't
5919                    // remove things that have it.
5920                    continue;
5921                }
5922                for (int j=i+1; j<N; j++) {
5923                    final ResolveInfo rij = results.get(j);
5924                    if (rij.filter != null && rij.filter.hasAction(action)) {
5925                        results.remove(j);
5926                        if (DEBUG_INTENT_MATCHING) Log.v(
5927                            TAG, "Removing duplicate item from " + j
5928                            + " due to action " + action + " at " + i);
5929                        j--;
5930                        N--;
5931                    }
5932                }
5933            }
5934
5935            // If the caller didn't request filter information, drop it now
5936            // so we don't have to marshall/unmarshall it.
5937            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5938                rii.filter = null;
5939            }
5940        }
5941
5942        // Filter out the caller activity if so requested.
5943        if (caller != null) {
5944            N = results.size();
5945            for (int i=0; i<N; i++) {
5946                ActivityInfo ainfo = results.get(i).activityInfo;
5947                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5948                        && caller.getClassName().equals(ainfo.name)) {
5949                    results.remove(i);
5950                    break;
5951                }
5952            }
5953        }
5954
5955        // If the caller didn't request filter information,
5956        // drop them now so we don't have to
5957        // marshall/unmarshall it.
5958        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5959            N = results.size();
5960            for (int i=0; i<N; i++) {
5961                results.get(i).filter = null;
5962            }
5963        }
5964
5965        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5966        return results;
5967    }
5968
5969    @Override
5970    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5971            String resolvedType, int flags, int userId) {
5972        return new ParceledListSlice<>(
5973                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5974    }
5975
5976    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5977            String resolvedType, int flags, int userId) {
5978        if (!sUserManager.exists(userId)) return Collections.emptyList();
5979        flags = updateFlagsForResolve(flags, userId, intent);
5980        ComponentName comp = intent.getComponent();
5981        if (comp == null) {
5982            if (intent.getSelector() != null) {
5983                intent = intent.getSelector();
5984                comp = intent.getComponent();
5985            }
5986        }
5987        if (comp != null) {
5988            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5989            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5990            if (ai != null) {
5991                ResolveInfo ri = new ResolveInfo();
5992                ri.activityInfo = ai;
5993                list.add(ri);
5994            }
5995            return list;
5996        }
5997
5998        // reader
5999        synchronized (mPackages) {
6000            String pkgName = intent.getPackage();
6001            if (pkgName == null) {
6002                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6003            }
6004            final PackageParser.Package pkg = mPackages.get(pkgName);
6005            if (pkg != null) {
6006                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6007                        userId);
6008            }
6009            return Collections.emptyList();
6010        }
6011    }
6012
6013    @Override
6014    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6015        if (!sUserManager.exists(userId)) return null;
6016        flags = updateFlagsForResolve(flags, userId, intent);
6017        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6018        if (query != null) {
6019            if (query.size() >= 1) {
6020                // If there is more than one service with the same priority,
6021                // just arbitrarily pick the first one.
6022                return query.get(0);
6023            }
6024        }
6025        return null;
6026    }
6027
6028    @Override
6029    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6030            String resolvedType, int flags, int userId) {
6031        return new ParceledListSlice<>(
6032                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6033    }
6034
6035    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6036            String resolvedType, int flags, int userId) {
6037        if (!sUserManager.exists(userId)) return Collections.emptyList();
6038        flags = updateFlagsForResolve(flags, userId, intent);
6039        ComponentName comp = intent.getComponent();
6040        if (comp == null) {
6041            if (intent.getSelector() != null) {
6042                intent = intent.getSelector();
6043                comp = intent.getComponent();
6044            }
6045        }
6046        if (comp != null) {
6047            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6048            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6049            if (si != null) {
6050                final ResolveInfo ri = new ResolveInfo();
6051                ri.serviceInfo = si;
6052                list.add(ri);
6053            }
6054            return list;
6055        }
6056
6057        // reader
6058        synchronized (mPackages) {
6059            String pkgName = intent.getPackage();
6060            if (pkgName == null) {
6061                return mServices.queryIntent(intent, resolvedType, flags, userId);
6062            }
6063            final PackageParser.Package pkg = mPackages.get(pkgName);
6064            if (pkg != null) {
6065                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6066                        userId);
6067            }
6068            return Collections.emptyList();
6069        }
6070    }
6071
6072    @Override
6073    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6074            String resolvedType, int flags, int userId) {
6075        return new ParceledListSlice<>(
6076                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6077    }
6078
6079    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6080            Intent intent, String resolvedType, int flags, int userId) {
6081        if (!sUserManager.exists(userId)) return Collections.emptyList();
6082        flags = updateFlagsForResolve(flags, userId, intent);
6083        ComponentName comp = intent.getComponent();
6084        if (comp == null) {
6085            if (intent.getSelector() != null) {
6086                intent = intent.getSelector();
6087                comp = intent.getComponent();
6088            }
6089        }
6090        if (comp != null) {
6091            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6092            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6093            if (pi != null) {
6094                final ResolveInfo ri = new ResolveInfo();
6095                ri.providerInfo = pi;
6096                list.add(ri);
6097            }
6098            return list;
6099        }
6100
6101        // reader
6102        synchronized (mPackages) {
6103            String pkgName = intent.getPackage();
6104            if (pkgName == null) {
6105                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6106            }
6107            final PackageParser.Package pkg = mPackages.get(pkgName);
6108            if (pkg != null) {
6109                return mProviders.queryIntentForPackage(
6110                        intent, resolvedType, flags, pkg.providers, userId);
6111            }
6112            return Collections.emptyList();
6113        }
6114    }
6115
6116    @Override
6117    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6118        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6119        flags = updateFlagsForPackage(flags, userId, null);
6120        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6121        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6122                true /* requireFullPermission */, false /* checkShell */,
6123                "get installed packages");
6124
6125        // writer
6126        synchronized (mPackages) {
6127            ArrayList<PackageInfo> list;
6128            if (listUninstalled) {
6129                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6130                for (PackageSetting ps : mSettings.mPackages.values()) {
6131                    final PackageInfo pi;
6132                    if (ps.pkg != null) {
6133                        pi = generatePackageInfo(ps, flags, userId);
6134                    } else {
6135                        pi = generatePackageInfo(ps, flags, userId);
6136                    }
6137                    if (pi != null) {
6138                        list.add(pi);
6139                    }
6140                }
6141            } else {
6142                list = new ArrayList<PackageInfo>(mPackages.size());
6143                for (PackageParser.Package p : mPackages.values()) {
6144                    final PackageInfo pi =
6145                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6146                    if (pi != null) {
6147                        list.add(pi);
6148                    }
6149                }
6150            }
6151
6152            return new ParceledListSlice<PackageInfo>(list);
6153        }
6154    }
6155
6156    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6157            String[] permissions, boolean[] tmp, int flags, int userId) {
6158        int numMatch = 0;
6159        final PermissionsState permissionsState = ps.getPermissionsState();
6160        for (int i=0; i<permissions.length; i++) {
6161            final String permission = permissions[i];
6162            if (permissionsState.hasPermission(permission, userId)) {
6163                tmp[i] = true;
6164                numMatch++;
6165            } else {
6166                tmp[i] = false;
6167            }
6168        }
6169        if (numMatch == 0) {
6170            return;
6171        }
6172        final PackageInfo pi;
6173        if (ps.pkg != null) {
6174            pi = generatePackageInfo(ps, flags, userId);
6175        } else {
6176            pi = generatePackageInfo(ps, flags, userId);
6177        }
6178        // The above might return null in cases of uninstalled apps or install-state
6179        // skew across users/profiles.
6180        if (pi != null) {
6181            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6182                if (numMatch == permissions.length) {
6183                    pi.requestedPermissions = permissions;
6184                } else {
6185                    pi.requestedPermissions = new String[numMatch];
6186                    numMatch = 0;
6187                    for (int i=0; i<permissions.length; i++) {
6188                        if (tmp[i]) {
6189                            pi.requestedPermissions[numMatch] = permissions[i];
6190                            numMatch++;
6191                        }
6192                    }
6193                }
6194            }
6195            list.add(pi);
6196        }
6197    }
6198
6199    @Override
6200    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6201            String[] permissions, int flags, int userId) {
6202        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6203        flags = updateFlagsForPackage(flags, userId, permissions);
6204        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6205
6206        // writer
6207        synchronized (mPackages) {
6208            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6209            boolean[] tmpBools = new boolean[permissions.length];
6210            if (listUninstalled) {
6211                for (PackageSetting ps : mSettings.mPackages.values()) {
6212                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6213                }
6214            } else {
6215                for (PackageParser.Package pkg : mPackages.values()) {
6216                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6217                    if (ps != null) {
6218                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6219                                userId);
6220                    }
6221                }
6222            }
6223
6224            return new ParceledListSlice<PackageInfo>(list);
6225        }
6226    }
6227
6228    @Override
6229    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6230        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6231        flags = updateFlagsForApplication(flags, userId, null);
6232        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6233
6234        // writer
6235        synchronized (mPackages) {
6236            ArrayList<ApplicationInfo> list;
6237            if (listUninstalled) {
6238                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6239                for (PackageSetting ps : mSettings.mPackages.values()) {
6240                    ApplicationInfo ai;
6241                    if (ps.pkg != null) {
6242                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6243                                ps.readUserState(userId), userId);
6244                    } else {
6245                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6246                    }
6247                    if (ai != null) {
6248                        list.add(ai);
6249                    }
6250                }
6251            } else {
6252                list = new ArrayList<ApplicationInfo>(mPackages.size());
6253                for (PackageParser.Package p : mPackages.values()) {
6254                    if (p.mExtras != null) {
6255                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6256                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6257                        if (ai != null) {
6258                            list.add(ai);
6259                        }
6260                    }
6261                }
6262            }
6263
6264            return new ParceledListSlice<ApplicationInfo>(list);
6265        }
6266    }
6267
6268    @Override
6269    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6270        if (DISABLE_EPHEMERAL_APPS) {
6271            return null;
6272        }
6273
6274        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6275                "getEphemeralApplications");
6276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6277                true /* requireFullPermission */, false /* checkShell */,
6278                "getEphemeralApplications");
6279        synchronized (mPackages) {
6280            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6281                    .getEphemeralApplicationsLPw(userId);
6282            if (ephemeralApps != null) {
6283                return new ParceledListSlice<>(ephemeralApps);
6284            }
6285        }
6286        return null;
6287    }
6288
6289    @Override
6290    public boolean isEphemeralApplication(String packageName, int userId) {
6291        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6292                true /* requireFullPermission */, false /* checkShell */,
6293                "isEphemeral");
6294        if (DISABLE_EPHEMERAL_APPS) {
6295            return false;
6296        }
6297
6298        if (!isCallerSameApp(packageName)) {
6299            return false;
6300        }
6301        synchronized (mPackages) {
6302            PackageParser.Package pkg = mPackages.get(packageName);
6303            if (pkg != null) {
6304                return pkg.applicationInfo.isEphemeralApp();
6305            }
6306        }
6307        return false;
6308    }
6309
6310    @Override
6311    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6312        if (DISABLE_EPHEMERAL_APPS) {
6313            return null;
6314        }
6315
6316        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6317                true /* requireFullPermission */, false /* checkShell */,
6318                "getCookie");
6319        if (!isCallerSameApp(packageName)) {
6320            return null;
6321        }
6322        synchronized (mPackages) {
6323            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6324                    packageName, userId);
6325        }
6326    }
6327
6328    @Override
6329    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6330        if (DISABLE_EPHEMERAL_APPS) {
6331            return true;
6332        }
6333
6334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6335                true /* requireFullPermission */, true /* checkShell */,
6336                "setCookie");
6337        if (!isCallerSameApp(packageName)) {
6338            return false;
6339        }
6340        synchronized (mPackages) {
6341            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6342                    packageName, cookie, userId);
6343        }
6344    }
6345
6346    @Override
6347    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6348        if (DISABLE_EPHEMERAL_APPS) {
6349            return null;
6350        }
6351
6352        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6353                "getEphemeralApplicationIcon");
6354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6355                true /* requireFullPermission */, false /* checkShell */,
6356                "getEphemeralApplicationIcon");
6357        synchronized (mPackages) {
6358            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6359                    packageName, userId);
6360        }
6361    }
6362
6363    private boolean isCallerSameApp(String packageName) {
6364        PackageParser.Package pkg = mPackages.get(packageName);
6365        return pkg != null
6366                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6367    }
6368
6369    @Override
6370    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6371        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6372    }
6373
6374    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6375        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6376
6377        // reader
6378        synchronized (mPackages) {
6379            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6380            final int userId = UserHandle.getCallingUserId();
6381            while (i.hasNext()) {
6382                final PackageParser.Package p = i.next();
6383                if (p.applicationInfo == null) continue;
6384
6385                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6386                        && !p.applicationInfo.isDirectBootAware();
6387                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6388                        && p.applicationInfo.isDirectBootAware();
6389
6390                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6391                        && (!mSafeMode || isSystemApp(p))
6392                        && (matchesUnaware || matchesAware)) {
6393                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6394                    if (ps != null) {
6395                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6396                                ps.readUserState(userId), userId);
6397                        if (ai != null) {
6398                            finalList.add(ai);
6399                        }
6400                    }
6401                }
6402            }
6403        }
6404
6405        return finalList;
6406    }
6407
6408    @Override
6409    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6410        if (!sUserManager.exists(userId)) return null;
6411        flags = updateFlagsForComponent(flags, userId, name);
6412        // reader
6413        synchronized (mPackages) {
6414            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6415            PackageSetting ps = provider != null
6416                    ? mSettings.mPackages.get(provider.owner.packageName)
6417                    : null;
6418            return ps != null
6419                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6420                    ? PackageParser.generateProviderInfo(provider, flags,
6421                            ps.readUserState(userId), userId)
6422                    : null;
6423        }
6424    }
6425
6426    /**
6427     * @deprecated
6428     */
6429    @Deprecated
6430    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6431        // reader
6432        synchronized (mPackages) {
6433            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6434                    .entrySet().iterator();
6435            final int userId = UserHandle.getCallingUserId();
6436            while (i.hasNext()) {
6437                Map.Entry<String, PackageParser.Provider> entry = i.next();
6438                PackageParser.Provider p = entry.getValue();
6439                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6440
6441                if (ps != null && p.syncable
6442                        && (!mSafeMode || (p.info.applicationInfo.flags
6443                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6444                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6445                            ps.readUserState(userId), userId);
6446                    if (info != null) {
6447                        outNames.add(entry.getKey());
6448                        outInfo.add(info);
6449                    }
6450                }
6451            }
6452        }
6453    }
6454
6455    @Override
6456    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6457            int uid, int flags) {
6458        final int userId = processName != null ? UserHandle.getUserId(uid)
6459                : UserHandle.getCallingUserId();
6460        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6461        flags = updateFlagsForComponent(flags, userId, processName);
6462
6463        ArrayList<ProviderInfo> finalList = null;
6464        // reader
6465        synchronized (mPackages) {
6466            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6467            while (i.hasNext()) {
6468                final PackageParser.Provider p = i.next();
6469                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6470                if (ps != null && p.info.authority != null
6471                        && (processName == null
6472                                || (p.info.processName.equals(processName)
6473                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6474                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6475                    if (finalList == null) {
6476                        finalList = new ArrayList<ProviderInfo>(3);
6477                    }
6478                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6479                            ps.readUserState(userId), userId);
6480                    if (info != null) {
6481                        finalList.add(info);
6482                    }
6483                }
6484            }
6485        }
6486
6487        if (finalList != null) {
6488            Collections.sort(finalList, mProviderInitOrderSorter);
6489            return new ParceledListSlice<ProviderInfo>(finalList);
6490        }
6491
6492        return ParceledListSlice.emptyList();
6493    }
6494
6495    @Override
6496    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6497        // reader
6498        synchronized (mPackages) {
6499            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6500            return PackageParser.generateInstrumentationInfo(i, flags);
6501        }
6502    }
6503
6504    @Override
6505    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6506            String targetPackage, int flags) {
6507        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6508    }
6509
6510    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6511            int flags) {
6512        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6513
6514        // reader
6515        synchronized (mPackages) {
6516            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6517            while (i.hasNext()) {
6518                final PackageParser.Instrumentation p = i.next();
6519                if (targetPackage == null
6520                        || targetPackage.equals(p.info.targetPackage)) {
6521                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6522                            flags);
6523                    if (ii != null) {
6524                        finalList.add(ii);
6525                    }
6526                }
6527            }
6528        }
6529
6530        return finalList;
6531    }
6532
6533    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6534        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6535        if (overlays == null) {
6536            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6537            return;
6538        }
6539        for (PackageParser.Package opkg : overlays.values()) {
6540            // Not much to do if idmap fails: we already logged the error
6541            // and we certainly don't want to abort installation of pkg simply
6542            // because an overlay didn't fit properly. For these reasons,
6543            // ignore the return value of createIdmapForPackagePairLI.
6544            createIdmapForPackagePairLI(pkg, opkg);
6545        }
6546    }
6547
6548    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6549            PackageParser.Package opkg) {
6550        if (!opkg.mTrustedOverlay) {
6551            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6552                    opkg.baseCodePath + ": overlay not trusted");
6553            return false;
6554        }
6555        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6556        if (overlaySet == null) {
6557            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6558                    opkg.baseCodePath + " but target package has no known overlays");
6559            return false;
6560        }
6561        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6562        // TODO: generate idmap for split APKs
6563        try {
6564            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6565        } catch (InstallerException e) {
6566            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6567                    + opkg.baseCodePath);
6568            return false;
6569        }
6570        PackageParser.Package[] overlayArray =
6571            overlaySet.values().toArray(new PackageParser.Package[0]);
6572        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6573            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6574                return p1.mOverlayPriority - p2.mOverlayPriority;
6575            }
6576        };
6577        Arrays.sort(overlayArray, cmp);
6578
6579        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6580        int i = 0;
6581        for (PackageParser.Package p : overlayArray) {
6582            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6583        }
6584        return true;
6585    }
6586
6587    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6588        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6589        try {
6590            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6591        } finally {
6592            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6593        }
6594    }
6595
6596    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6597        final File[] files = dir.listFiles();
6598        if (ArrayUtils.isEmpty(files)) {
6599            Log.d(TAG, "No files in app dir " + dir);
6600            return;
6601        }
6602
6603        if (DEBUG_PACKAGE_SCANNING) {
6604            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6605                    + " flags=0x" + Integer.toHexString(parseFlags));
6606        }
6607
6608        for (File file : files) {
6609            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6610                    && !PackageInstallerService.isStageName(file.getName());
6611            if (!isPackage) {
6612                // Ignore entries which are not packages
6613                continue;
6614            }
6615            try {
6616                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6617                        scanFlags, currentTime, null);
6618            } catch (PackageManagerException e) {
6619                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6620
6621                // Delete invalid userdata apps
6622                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6623                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6624                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6625                    removeCodePathLI(file);
6626                }
6627            }
6628        }
6629    }
6630
6631    private static File getSettingsProblemFile() {
6632        File dataDir = Environment.getDataDirectory();
6633        File systemDir = new File(dataDir, "system");
6634        File fname = new File(systemDir, "uiderrors.txt");
6635        return fname;
6636    }
6637
6638    static void reportSettingsProblem(int priority, String msg) {
6639        logCriticalInfo(priority, msg);
6640    }
6641
6642    static void logCriticalInfo(int priority, String msg) {
6643        Slog.println(priority, TAG, msg);
6644        EventLogTags.writePmCriticalInfo(msg);
6645        try {
6646            File fname = getSettingsProblemFile();
6647            FileOutputStream out = new FileOutputStream(fname, true);
6648            PrintWriter pw = new FastPrintWriter(out);
6649            SimpleDateFormat formatter = new SimpleDateFormat();
6650            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6651            pw.println(dateString + ": " + msg);
6652            pw.close();
6653            FileUtils.setPermissions(
6654                    fname.toString(),
6655                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6656                    -1, -1);
6657        } catch (java.io.IOException e) {
6658        }
6659    }
6660
6661    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6662            final int policyFlags) throws PackageManagerException {
6663        if (ps != null
6664                && ps.codePath.equals(srcFile)
6665                && ps.timeStamp == srcFile.lastModified()
6666                && !isCompatSignatureUpdateNeeded(pkg)
6667                && !isRecoverSignatureUpdateNeeded(pkg)) {
6668            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6669            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6670            ArraySet<PublicKey> signingKs;
6671            synchronized (mPackages) {
6672                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6673            }
6674            if (ps.signatures.mSignatures != null
6675                    && ps.signatures.mSignatures.length != 0
6676                    && signingKs != null) {
6677                // Optimization: reuse the existing cached certificates
6678                // if the package appears to be unchanged.
6679                pkg.mSignatures = ps.signatures.mSignatures;
6680                pkg.mSigningKeys = signingKs;
6681                return;
6682            }
6683
6684            Slog.w(TAG, "PackageSetting for " + ps.name
6685                    + " is missing signatures.  Collecting certs again to recover them.");
6686        } else {
6687            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6688        }
6689
6690        try {
6691            PackageParser.collectCertificates(pkg, policyFlags);
6692        } catch (PackageParserException e) {
6693            throw PackageManagerException.from(e);
6694        }
6695    }
6696
6697    /**
6698     *  Traces a package scan.
6699     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6700     */
6701    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6702            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6703        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6704        try {
6705            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6706        } finally {
6707            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6708        }
6709    }
6710
6711    /**
6712     *  Scans a package and returns the newly parsed package.
6713     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6714     */
6715    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6716            long currentTime, UserHandle user) throws PackageManagerException {
6717        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6718        PackageParser pp = new PackageParser();
6719        pp.setSeparateProcesses(mSeparateProcesses);
6720        pp.setOnlyCoreApps(mOnlyCore);
6721        pp.setDisplayMetrics(mMetrics);
6722
6723        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6724            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6725        }
6726
6727        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6728        final PackageParser.Package pkg;
6729        try {
6730            pkg = pp.parsePackage(scanFile, parseFlags);
6731        } catch (PackageParserException e) {
6732            throw PackageManagerException.from(e);
6733        } finally {
6734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6735        }
6736
6737        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6738    }
6739
6740    /**
6741     *  Scans a package and returns the newly parsed package.
6742     *  @throws PackageManagerException on a parse error.
6743     */
6744    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6745            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6746            throws PackageManagerException {
6747        // If the package has children and this is the first dive in the function
6748        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6749        // packages (parent and children) would be successfully scanned before the
6750        // actual scan since scanning mutates internal state and we want to atomically
6751        // install the package and its children.
6752        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6753            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6754                scanFlags |= SCAN_CHECK_ONLY;
6755            }
6756        } else {
6757            scanFlags &= ~SCAN_CHECK_ONLY;
6758        }
6759
6760        // Scan the parent
6761        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6762                scanFlags, currentTime, user);
6763
6764        // Scan the children
6765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6766        for (int i = 0; i < childCount; i++) {
6767            PackageParser.Package childPackage = pkg.childPackages.get(i);
6768            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6769                    currentTime, user);
6770        }
6771
6772
6773        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6774            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6775        }
6776
6777        return scannedPkg;
6778    }
6779
6780    /**
6781     *  Scans a package and returns the newly parsed package.
6782     *  @throws PackageManagerException on a parse error.
6783     */
6784    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6785            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6786            throws PackageManagerException {
6787        PackageSetting ps = null;
6788        PackageSetting updatedPkg;
6789        // reader
6790        synchronized (mPackages) {
6791            // Look to see if we already know about this package.
6792            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6793            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6794                // This package has been renamed to its original name.  Let's
6795                // use that.
6796                ps = mSettings.peekPackageLPr(oldName);
6797            }
6798            // If there was no original package, see one for the real package name.
6799            if (ps == null) {
6800                ps = mSettings.peekPackageLPr(pkg.packageName);
6801            }
6802            // Check to see if this package could be hiding/updating a system
6803            // package.  Must look for it either under the original or real
6804            // package name depending on our state.
6805            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6806            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6807
6808            // If this is a package we don't know about on the system partition, we
6809            // may need to remove disabled child packages on the system partition
6810            // or may need to not add child packages if the parent apk is updated
6811            // on the data partition and no longer defines this child package.
6812            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6813                // If this is a parent package for an updated system app and this system
6814                // app got an OTA update which no longer defines some of the child packages
6815                // we have to prune them from the disabled system packages.
6816                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6817                if (disabledPs != null) {
6818                    final int scannedChildCount = (pkg.childPackages != null)
6819                            ? pkg.childPackages.size() : 0;
6820                    final int disabledChildCount = disabledPs.childPackageNames != null
6821                            ? disabledPs.childPackageNames.size() : 0;
6822                    for (int i = 0; i < disabledChildCount; i++) {
6823                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6824                        boolean disabledPackageAvailable = false;
6825                        for (int j = 0; j < scannedChildCount; j++) {
6826                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6827                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6828                                disabledPackageAvailable = true;
6829                                break;
6830                            }
6831                         }
6832                         if (!disabledPackageAvailable) {
6833                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6834                         }
6835                    }
6836                }
6837            }
6838        }
6839
6840        boolean updatedPkgBetter = false;
6841        // First check if this is a system package that may involve an update
6842        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6843            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6844            // it needs to drop FLAG_PRIVILEGED.
6845            if (locationIsPrivileged(scanFile)) {
6846                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6847            } else {
6848                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6849            }
6850
6851            if (ps != null && !ps.codePath.equals(scanFile)) {
6852                // The path has changed from what was last scanned...  check the
6853                // version of the new path against what we have stored to determine
6854                // what to do.
6855                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6856                if (pkg.mVersionCode <= ps.versionCode) {
6857                    // The system package has been updated and the code path does not match
6858                    // Ignore entry. Skip it.
6859                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6860                            + " ignored: updated version " + ps.versionCode
6861                            + " better than this " + pkg.mVersionCode);
6862                    if (!updatedPkg.codePath.equals(scanFile)) {
6863                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6864                                + ps.name + " changing from " + updatedPkg.codePathString
6865                                + " to " + scanFile);
6866                        updatedPkg.codePath = scanFile;
6867                        updatedPkg.codePathString = scanFile.toString();
6868                        updatedPkg.resourcePath = scanFile;
6869                        updatedPkg.resourcePathString = scanFile.toString();
6870                    }
6871                    updatedPkg.pkg = pkg;
6872                    updatedPkg.versionCode = pkg.mVersionCode;
6873
6874                    // Update the disabled system child packages to point to the package too.
6875                    final int childCount = updatedPkg.childPackageNames != null
6876                            ? updatedPkg.childPackageNames.size() : 0;
6877                    for (int i = 0; i < childCount; i++) {
6878                        String childPackageName = updatedPkg.childPackageNames.get(i);
6879                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6880                                childPackageName);
6881                        if (updatedChildPkg != null) {
6882                            updatedChildPkg.pkg = pkg;
6883                            updatedChildPkg.versionCode = pkg.mVersionCode;
6884                        }
6885                    }
6886
6887                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6888                            + scanFile + " ignored: updated version " + ps.versionCode
6889                            + " better than this " + pkg.mVersionCode);
6890                } else {
6891                    // The current app on the system partition is better than
6892                    // what we have updated to on the data partition; switch
6893                    // back to the system partition version.
6894                    // At this point, its safely assumed that package installation for
6895                    // apps in system partition will go through. If not there won't be a working
6896                    // version of the app
6897                    // writer
6898                    synchronized (mPackages) {
6899                        // Just remove the loaded entries from package lists.
6900                        mPackages.remove(ps.name);
6901                    }
6902
6903                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6904                            + " reverting from " + ps.codePathString
6905                            + ": new version " + pkg.mVersionCode
6906                            + " better than installed " + ps.versionCode);
6907
6908                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6909                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6910                    synchronized (mInstallLock) {
6911                        args.cleanUpResourcesLI();
6912                    }
6913                    synchronized (mPackages) {
6914                        mSettings.enableSystemPackageLPw(ps.name);
6915                    }
6916                    updatedPkgBetter = true;
6917                }
6918            }
6919        }
6920
6921        if (updatedPkg != null) {
6922            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6923            // initially
6924            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6925
6926            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6927            // flag set initially
6928            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6929                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6930            }
6931        }
6932
6933        // Verify certificates against what was last scanned
6934        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6935
6936        /*
6937         * A new system app appeared, but we already had a non-system one of the
6938         * same name installed earlier.
6939         */
6940        boolean shouldHideSystemApp = false;
6941        if (updatedPkg == null && ps != null
6942                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6943            /*
6944             * Check to make sure the signatures match first. If they don't,
6945             * wipe the installed application and its data.
6946             */
6947            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6948                    != PackageManager.SIGNATURE_MATCH) {
6949                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6950                        + " signatures don't match existing userdata copy; removing");
6951                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6952                        "scanPackageInternalLI")) {
6953                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6954                }
6955                ps = null;
6956            } else {
6957                /*
6958                 * If the newly-added system app is an older version than the
6959                 * already installed version, hide it. It will be scanned later
6960                 * and re-added like an update.
6961                 */
6962                if (pkg.mVersionCode <= ps.versionCode) {
6963                    shouldHideSystemApp = true;
6964                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6965                            + " but new version " + pkg.mVersionCode + " better than installed "
6966                            + ps.versionCode + "; hiding system");
6967                } else {
6968                    /*
6969                     * The newly found system app is a newer version that the
6970                     * one previously installed. Simply remove the
6971                     * already-installed application and replace it with our own
6972                     * while keeping the application data.
6973                     */
6974                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6975                            + " reverting from " + ps.codePathString + ": new version "
6976                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6977                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6978                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6979                    synchronized (mInstallLock) {
6980                        args.cleanUpResourcesLI();
6981                    }
6982                }
6983            }
6984        }
6985
6986        // The apk is forward locked (not public) if its code and resources
6987        // are kept in different files. (except for app in either system or
6988        // vendor path).
6989        // TODO grab this value from PackageSettings
6990        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6991            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6992                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6993            }
6994        }
6995
6996        // TODO: extend to support forward-locked splits
6997        String resourcePath = null;
6998        String baseResourcePath = null;
6999        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7000            if (ps != null && ps.resourcePathString != null) {
7001                resourcePath = ps.resourcePathString;
7002                baseResourcePath = ps.resourcePathString;
7003            } else {
7004                // Should not happen at all. Just log an error.
7005                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7006            }
7007        } else {
7008            resourcePath = pkg.codePath;
7009            baseResourcePath = pkg.baseCodePath;
7010        }
7011
7012        // Set application objects path explicitly.
7013        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7014        pkg.setApplicationInfoCodePath(pkg.codePath);
7015        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7016        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7017        pkg.setApplicationInfoResourcePath(resourcePath);
7018        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7019        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7020
7021        // Note that we invoke the following method only if we are about to unpack an application
7022        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7023                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7024
7025        /*
7026         * If the system app should be overridden by a previously installed
7027         * data, hide the system app now and let the /data/app scan pick it up
7028         * again.
7029         */
7030        if (shouldHideSystemApp) {
7031            synchronized (mPackages) {
7032                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7033            }
7034        }
7035
7036        return scannedPkg;
7037    }
7038
7039    private static String fixProcessName(String defProcessName,
7040            String processName, int uid) {
7041        if (processName == null) {
7042            return defProcessName;
7043        }
7044        return processName;
7045    }
7046
7047    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7048            throws PackageManagerException {
7049        if (pkgSetting.signatures.mSignatures != null) {
7050            // Already existing package. Make sure signatures match
7051            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7052                    == PackageManager.SIGNATURE_MATCH;
7053            if (!match) {
7054                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7055                        == PackageManager.SIGNATURE_MATCH;
7056            }
7057            if (!match) {
7058                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7059                        == PackageManager.SIGNATURE_MATCH;
7060            }
7061            if (!match) {
7062                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7063                        + pkg.packageName + " signatures do not match the "
7064                        + "previously installed version; ignoring!");
7065            }
7066        }
7067
7068        // Check for shared user signatures
7069        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7070            // Already existing package. Make sure signatures match
7071            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7072                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7073            if (!match) {
7074                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7075                        == PackageManager.SIGNATURE_MATCH;
7076            }
7077            if (!match) {
7078                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7079                        == PackageManager.SIGNATURE_MATCH;
7080            }
7081            if (!match) {
7082                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7083                        "Package " + pkg.packageName
7084                        + " has no signatures that match those in shared user "
7085                        + pkgSetting.sharedUser.name + "; ignoring!");
7086            }
7087        }
7088    }
7089
7090    /**
7091     * Enforces that only the system UID or root's UID can call a method exposed
7092     * via Binder.
7093     *
7094     * @param message used as message if SecurityException is thrown
7095     * @throws SecurityException if the caller is not system or root
7096     */
7097    private static final void enforceSystemOrRoot(String message) {
7098        final int uid = Binder.getCallingUid();
7099        if (uid != Process.SYSTEM_UID && uid != 0) {
7100            throw new SecurityException(message);
7101        }
7102    }
7103
7104    @Override
7105    public void performFstrimIfNeeded() {
7106        enforceSystemOrRoot("Only the system can request fstrim");
7107
7108        // Before everything else, see whether we need to fstrim.
7109        try {
7110            IMountService ms = PackageHelper.getMountService();
7111            if (ms != null) {
7112                final boolean isUpgrade = isUpgrade();
7113                boolean doTrim = isUpgrade;
7114                if (doTrim) {
7115                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7116                } else {
7117                    final long interval = android.provider.Settings.Global.getLong(
7118                            mContext.getContentResolver(),
7119                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7120                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7121                    if (interval > 0) {
7122                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7123                        if (timeSinceLast > interval) {
7124                            doTrim = true;
7125                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7126                                    + "; running immediately");
7127                        }
7128                    }
7129                }
7130                if (doTrim) {
7131                    if (!isFirstBoot()) {
7132                        try {
7133                            ActivityManagerNative.getDefault().showBootMessage(
7134                                    mContext.getResources().getString(
7135                                            R.string.android_upgrading_fstrim), true);
7136                        } catch (RemoteException e) {
7137                        }
7138                    }
7139                    ms.runMaintenance();
7140                }
7141            } else {
7142                Slog.e(TAG, "Mount service unavailable!");
7143            }
7144        } catch (RemoteException e) {
7145            // Can't happen; MountService is local
7146        }
7147    }
7148
7149    @Override
7150    public void updatePackagesIfNeeded() {
7151        enforceSystemOrRoot("Only the system can request package update");
7152
7153        // We need to re-extract after an OTA.
7154        boolean causeUpgrade = isUpgrade();
7155
7156        // First boot or factory reset.
7157        // Note: we also handle devices that are upgrading to N right now as if it is their
7158        //       first boot, as they do not have profile data.
7159        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7160
7161        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7162        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7163
7164        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7165            return;
7166        }
7167
7168        List<PackageParser.Package> pkgs;
7169        synchronized (mPackages) {
7170            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7171        }
7172
7173        int curr = 0;
7174        int total = pkgs.size();
7175        for (PackageParser.Package pkg : pkgs) {
7176            curr++;
7177
7178            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7179                if (DEBUG_DEXOPT) {
7180                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7181                }
7182                continue;
7183            }
7184
7185            if (DEBUG_DEXOPT) {
7186                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7187            }
7188
7189            if (!isFirstBoot()) {
7190                try {
7191                    ActivityManagerNative.getDefault().showBootMessage(
7192                            mContext.getResources().getString(R.string.android_upgrading_apk,
7193                                    curr, total), true);
7194                } catch (RemoteException e) {
7195                }
7196            }
7197
7198            performDexOpt(pkg.packageName,
7199                    null /* instructionSet */,
7200                    false /* checkProfiles */,
7201                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7202                    false /* force */);
7203        }
7204    }
7205
7206    @Override
7207    public void notifyPackageUse(String packageName, int reason) {
7208        synchronized (mPackages) {
7209            PackageParser.Package p = mPackages.get(packageName);
7210            if (p == null) {
7211                return;
7212            }
7213            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7214        }
7215    }
7216
7217    // TODO: this is not used nor needed. Delete it.
7218    @Override
7219    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7220        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7221                getFullCompilerFilter(), false /* force */);
7222    }
7223
7224    @Override
7225    public boolean performDexOpt(String packageName, String instructionSet,
7226            boolean checkProfiles, int compileReason, boolean force) {
7227        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7228                getCompilerFilterForReason(compileReason), force);
7229    }
7230
7231    @Override
7232    public boolean performDexOptMode(String packageName, String instructionSet,
7233            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7234        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7235                targetCompilerFilter, force);
7236    }
7237
7238    private boolean performDexOptTraced(String packageName, String instructionSet,
7239                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7240        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7241        try {
7242            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7243                    targetCompilerFilter, force);
7244        } finally {
7245            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7246        }
7247    }
7248
7249    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7250    // if the package can now be considered up to date for the given filter.
7251    private boolean performDexOptInternal(String packageName, String instructionSet,
7252                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7253        PackageParser.Package p;
7254        final String targetInstructionSet;
7255        synchronized (mPackages) {
7256            p = mPackages.get(packageName);
7257            if (p == null) {
7258                return false;
7259            }
7260            mPackageUsage.write(false);
7261
7262            targetInstructionSet = instructionSet != null ? instructionSet :
7263                    getPrimaryInstructionSet(p.applicationInfo);
7264        }
7265        long callingId = Binder.clearCallingIdentity();
7266        try {
7267            synchronized (mInstallLock) {
7268                final String[] instructionSets = new String[] { targetInstructionSet };
7269                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7270                        checkProfiles, targetCompilerFilter, force);
7271                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7272            }
7273        } finally {
7274            Binder.restoreCallingIdentity(callingId);
7275        }
7276    }
7277
7278    public ArraySet<String> getOptimizablePackages() {
7279        ArraySet<String> pkgs = new ArraySet<String>();
7280        synchronized (mPackages) {
7281            for (PackageParser.Package p : mPackages.values()) {
7282                if (PackageDexOptimizer.canOptimizePackage(p)) {
7283                    pkgs.add(p.packageName);
7284                }
7285            }
7286        }
7287        return pkgs;
7288    }
7289
7290    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7291            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7292            boolean force) {
7293        // Select the dex optimizer based on the force parameter.
7294        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7295        //       allocate an object here.
7296        PackageDexOptimizer pdo = force
7297                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7298                : mPackageDexOptimizer;
7299
7300        // Optimize all dependencies first. Note: we ignore the return value and march on
7301        // on errors.
7302        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7303        if (!deps.isEmpty()) {
7304            for (PackageParser.Package depPackage : deps) {
7305                // TODO: Analyze and investigate if we (should) profile libraries.
7306                // Currently this will do a full compilation of the library by default.
7307                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7308                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7309            }
7310        }
7311
7312        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7313    }
7314
7315    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7316        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7317            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7318            Set<String> collectedNames = new HashSet<>();
7319            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7320
7321            retValue.remove(p);
7322
7323            return retValue;
7324        } else {
7325            return Collections.emptyList();
7326        }
7327    }
7328
7329    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7330            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7331        if (!collectedNames.contains(p.packageName)) {
7332            collectedNames.add(p.packageName);
7333            collected.add(p);
7334
7335            if (p.usesLibraries != null) {
7336                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7337            }
7338            if (p.usesOptionalLibraries != null) {
7339                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7340                        collectedNames);
7341            }
7342        }
7343    }
7344
7345    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7346            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7347        for (String libName : libs) {
7348            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7349            if (libPkg != null) {
7350                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7351            }
7352        }
7353    }
7354
7355    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7356        synchronized (mPackages) {
7357            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7358            if (lib != null && lib.apk != null) {
7359                return mPackages.get(lib.apk);
7360            }
7361        }
7362        return null;
7363    }
7364
7365    public void shutdown() {
7366        mPackageUsage.write(true);
7367    }
7368
7369    @Override
7370    public void forceDexOpt(String packageName) {
7371        enforceSystemOrRoot("forceDexOpt");
7372
7373        PackageParser.Package pkg;
7374        synchronized (mPackages) {
7375            pkg = mPackages.get(packageName);
7376            if (pkg == null) {
7377                throw new IllegalArgumentException("Unknown package: " + packageName);
7378            }
7379        }
7380
7381        synchronized (mInstallLock) {
7382            final String[] instructionSets = new String[] {
7383                    getPrimaryInstructionSet(pkg.applicationInfo) };
7384
7385            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7386
7387            // Whoever is calling forceDexOpt wants a fully compiled package.
7388            // Don't use profiles since that may cause compilation to be skipped.
7389            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7390                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7391                    true /* force */);
7392
7393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7395                throw new IllegalStateException("Failed to dexopt: " + res);
7396            }
7397        }
7398    }
7399
7400    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7401        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7402            Slog.w(TAG, "Unable to update from " + oldPkg.name
7403                    + " to " + newPkg.packageName
7404                    + ": old package not in system partition");
7405            return false;
7406        } else if (mPackages.get(oldPkg.name) != null) {
7407            Slog.w(TAG, "Unable to update from " + oldPkg.name
7408                    + " to " + newPkg.packageName
7409                    + ": old package still exists");
7410            return false;
7411        }
7412        return true;
7413    }
7414
7415    void removeCodePathLI(File codePath) {
7416        if (codePath.isDirectory()) {
7417            try {
7418                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7419            } catch (InstallerException e) {
7420                Slog.w(TAG, "Failed to remove code path", e);
7421            }
7422        } else {
7423            codePath.delete();
7424        }
7425    }
7426
7427    private int[] resolveUserIds(int userId) {
7428        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7429    }
7430
7431    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7432        if (pkg == null) {
7433            Slog.wtf(TAG, "Package was null!", new Throwable());
7434            return;
7435        }
7436        clearAppDataLeafLIF(pkg, userId, flags);
7437        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7438        for (int i = 0; i < childCount; i++) {
7439            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7440        }
7441    }
7442
7443    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7444        final PackageSetting ps;
7445        synchronized (mPackages) {
7446            ps = mSettings.mPackages.get(pkg.packageName);
7447        }
7448        for (int realUserId : resolveUserIds(userId)) {
7449            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7450            try {
7451                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7452                        ceDataInode);
7453            } catch (InstallerException e) {
7454                Slog.w(TAG, String.valueOf(e));
7455            }
7456        }
7457    }
7458
7459    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7460        if (pkg == null) {
7461            Slog.wtf(TAG, "Package was null!", new Throwable());
7462            return;
7463        }
7464        destroyAppDataLeafLIF(pkg, userId, flags);
7465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7466        for (int i = 0; i < childCount; i++) {
7467            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7468        }
7469    }
7470
7471    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7472        final PackageSetting ps;
7473        synchronized (mPackages) {
7474            ps = mSettings.mPackages.get(pkg.packageName);
7475        }
7476        for (int realUserId : resolveUserIds(userId)) {
7477            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7478            try {
7479                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7480                        ceDataInode);
7481            } catch (InstallerException e) {
7482                Slog.w(TAG, String.valueOf(e));
7483            }
7484        }
7485    }
7486
7487    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7488        if (pkg == null) {
7489            Slog.wtf(TAG, "Package was null!", new Throwable());
7490            return;
7491        }
7492        destroyAppProfilesLeafLIF(pkg);
7493        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7494        for (int i = 0; i < childCount; i++) {
7495            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7496        }
7497    }
7498
7499    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7500        try {
7501            mInstaller.destroyAppProfiles(pkg.packageName);
7502        } catch (InstallerException e) {
7503            Slog.w(TAG, String.valueOf(e));
7504        }
7505    }
7506
7507    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7508        if (pkg == null) {
7509            Slog.wtf(TAG, "Package was null!", new Throwable());
7510            return;
7511        }
7512        clearAppProfilesLeafLIF(pkg);
7513        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7514        for (int i = 0; i < childCount; i++) {
7515            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7516        }
7517    }
7518
7519    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7520        try {
7521            mInstaller.clearAppProfiles(pkg.packageName);
7522        } catch (InstallerException e) {
7523            Slog.w(TAG, String.valueOf(e));
7524        }
7525    }
7526
7527    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7528            long lastUpdateTime) {
7529        // Set parent install/update time
7530        PackageSetting ps = (PackageSetting) pkg.mExtras;
7531        if (ps != null) {
7532            ps.firstInstallTime = firstInstallTime;
7533            ps.lastUpdateTime = lastUpdateTime;
7534        }
7535        // Set children install/update time
7536        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7537        for (int i = 0; i < childCount; i++) {
7538            PackageParser.Package childPkg = pkg.childPackages.get(i);
7539            ps = (PackageSetting) childPkg.mExtras;
7540            if (ps != null) {
7541                ps.firstInstallTime = firstInstallTime;
7542                ps.lastUpdateTime = lastUpdateTime;
7543            }
7544        }
7545    }
7546
7547    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7548            PackageParser.Package changingLib) {
7549        if (file.path != null) {
7550            usesLibraryFiles.add(file.path);
7551            return;
7552        }
7553        PackageParser.Package p = mPackages.get(file.apk);
7554        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7555            // If we are doing this while in the middle of updating a library apk,
7556            // then we need to make sure to use that new apk for determining the
7557            // dependencies here.  (We haven't yet finished committing the new apk
7558            // to the package manager state.)
7559            if (p == null || p.packageName.equals(changingLib.packageName)) {
7560                p = changingLib;
7561            }
7562        }
7563        if (p != null) {
7564            usesLibraryFiles.addAll(p.getAllCodePaths());
7565        }
7566    }
7567
7568    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7569            PackageParser.Package changingLib) throws PackageManagerException {
7570        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7571            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7572            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7573            for (int i=0; i<N; i++) {
7574                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7575                if (file == null) {
7576                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7577                            "Package " + pkg.packageName + " requires unavailable shared library "
7578                            + pkg.usesLibraries.get(i) + "; failing!");
7579                }
7580                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7581            }
7582            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7583            for (int i=0; i<N; i++) {
7584                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7585                if (file == null) {
7586                    Slog.w(TAG, "Package " + pkg.packageName
7587                            + " desires unavailable shared library "
7588                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7589                } else {
7590                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7591                }
7592            }
7593            N = usesLibraryFiles.size();
7594            if (N > 0) {
7595                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7596            } else {
7597                pkg.usesLibraryFiles = null;
7598            }
7599        }
7600    }
7601
7602    private static boolean hasString(List<String> list, List<String> which) {
7603        if (list == null) {
7604            return false;
7605        }
7606        for (int i=list.size()-1; i>=0; i--) {
7607            for (int j=which.size()-1; j>=0; j--) {
7608                if (which.get(j).equals(list.get(i))) {
7609                    return true;
7610                }
7611            }
7612        }
7613        return false;
7614    }
7615
7616    private void updateAllSharedLibrariesLPw() {
7617        for (PackageParser.Package pkg : mPackages.values()) {
7618            try {
7619                updateSharedLibrariesLPw(pkg, null);
7620            } catch (PackageManagerException e) {
7621                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7622            }
7623        }
7624    }
7625
7626    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7627            PackageParser.Package changingPkg) {
7628        ArrayList<PackageParser.Package> res = null;
7629        for (PackageParser.Package pkg : mPackages.values()) {
7630            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7631                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7632                if (res == null) {
7633                    res = new ArrayList<PackageParser.Package>();
7634                }
7635                res.add(pkg);
7636                try {
7637                    updateSharedLibrariesLPw(pkg, changingPkg);
7638                } catch (PackageManagerException e) {
7639                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7640                }
7641            }
7642        }
7643        return res;
7644    }
7645
7646    /**
7647     * Derive the value of the {@code cpuAbiOverride} based on the provided
7648     * value and an optional stored value from the package settings.
7649     */
7650    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7651        String cpuAbiOverride = null;
7652
7653        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7654            cpuAbiOverride = null;
7655        } else if (abiOverride != null) {
7656            cpuAbiOverride = abiOverride;
7657        } else if (settings != null) {
7658            cpuAbiOverride = settings.cpuAbiOverrideString;
7659        }
7660
7661        return cpuAbiOverride;
7662    }
7663
7664    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7665            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7666                    throws PackageManagerException {
7667        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7668        // If the package has children and this is the first dive in the function
7669        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7670        // whether all packages (parent and children) would be successfully scanned
7671        // before the actual scan since scanning mutates internal state and we want
7672        // to atomically install the package and its children.
7673        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7674            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7675                scanFlags |= SCAN_CHECK_ONLY;
7676            }
7677        } else {
7678            scanFlags &= ~SCAN_CHECK_ONLY;
7679        }
7680
7681        final PackageParser.Package scannedPkg;
7682        try {
7683            // Scan the parent
7684            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7685            // Scan the children
7686            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7687            for (int i = 0; i < childCount; i++) {
7688                PackageParser.Package childPkg = pkg.childPackages.get(i);
7689                scanPackageLI(childPkg, policyFlags,
7690                        scanFlags, currentTime, user);
7691            }
7692        } finally {
7693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7694        }
7695
7696        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7697            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7698        }
7699
7700        return scannedPkg;
7701    }
7702
7703    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7704            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7705        boolean success = false;
7706        try {
7707            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7708                    currentTime, user);
7709            success = true;
7710            return res;
7711        } finally {
7712            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7713                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7714                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7715                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7716                destroyAppProfilesLIF(pkg);
7717            }
7718        }
7719    }
7720
7721    /**
7722     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7723     */
7724    private static boolean apkHasCode(String fileName) {
7725        StrictJarFile jarFile = null;
7726        try {
7727            jarFile = new StrictJarFile(fileName,
7728                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7729            return jarFile.findEntry("classes.dex") != null;
7730        } catch (IOException ignore) {
7731        } finally {
7732            try {
7733                jarFile.close();
7734            } catch (IOException ignore) {}
7735        }
7736        return false;
7737    }
7738
7739    /**
7740     * Enforces code policy for the package. This ensures that if an APK has
7741     * declared hasCode="true" in its manifest that the APK actually contains
7742     * code.
7743     *
7744     * @throws PackageManagerException If bytecode could not be found when it should exist
7745     */
7746    private static void enforceCodePolicy(PackageParser.Package pkg)
7747            throws PackageManagerException {
7748        final boolean shouldHaveCode =
7749                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7750        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7751            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7752                    "Package " + pkg.baseCodePath + " code is missing");
7753        }
7754
7755        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7756            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7757                final boolean splitShouldHaveCode =
7758                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7759                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7760                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7761                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7762                }
7763            }
7764        }
7765    }
7766
7767    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7768            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7769            throws PackageManagerException {
7770        final File scanFile = new File(pkg.codePath);
7771        if (pkg.applicationInfo.getCodePath() == null ||
7772                pkg.applicationInfo.getResourcePath() == null) {
7773            // Bail out. The resource and code paths haven't been set.
7774            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7775                    "Code and resource paths haven't been set correctly");
7776        }
7777
7778        // Apply policy
7779        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7780            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7781            if (pkg.applicationInfo.isDirectBootAware()) {
7782                // we're direct boot aware; set for all components
7783                for (PackageParser.Service s : pkg.services) {
7784                    s.info.encryptionAware = s.info.directBootAware = true;
7785                }
7786                for (PackageParser.Provider p : pkg.providers) {
7787                    p.info.encryptionAware = p.info.directBootAware = true;
7788                }
7789                for (PackageParser.Activity a : pkg.activities) {
7790                    a.info.encryptionAware = a.info.directBootAware = true;
7791                }
7792                for (PackageParser.Activity r : pkg.receivers) {
7793                    r.info.encryptionAware = r.info.directBootAware = true;
7794                }
7795            }
7796        } else {
7797            // Only allow system apps to be flagged as core apps.
7798            pkg.coreApp = false;
7799            // clear flags not applicable to regular apps
7800            pkg.applicationInfo.privateFlags &=
7801                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7802            pkg.applicationInfo.privateFlags &=
7803                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7804        }
7805        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7806
7807        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7808            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7809        }
7810
7811        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7812            enforceCodePolicy(pkg);
7813        }
7814
7815        if (mCustomResolverComponentName != null &&
7816                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7817            setUpCustomResolverActivity(pkg);
7818        }
7819
7820        if (pkg.packageName.equals("android")) {
7821            synchronized (mPackages) {
7822                if (mAndroidApplication != null) {
7823                    Slog.w(TAG, "*************************************************");
7824                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7825                    Slog.w(TAG, " file=" + scanFile);
7826                    Slog.w(TAG, "*************************************************");
7827                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7828                            "Core android package being redefined.  Skipping.");
7829                }
7830
7831                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7832                    // Set up information for our fall-back user intent resolution activity.
7833                    mPlatformPackage = pkg;
7834                    pkg.mVersionCode = mSdkVersion;
7835                    mAndroidApplication = pkg.applicationInfo;
7836
7837                    if (!mResolverReplaced) {
7838                        mResolveActivity.applicationInfo = mAndroidApplication;
7839                        mResolveActivity.name = ResolverActivity.class.getName();
7840                        mResolveActivity.packageName = mAndroidApplication.packageName;
7841                        mResolveActivity.processName = "system:ui";
7842                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7843                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7844                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7845                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7846                        mResolveActivity.exported = true;
7847                        mResolveActivity.enabled = true;
7848                        mResolveInfo.activityInfo = mResolveActivity;
7849                        mResolveInfo.priority = 0;
7850                        mResolveInfo.preferredOrder = 0;
7851                        mResolveInfo.match = 0;
7852                        mResolveComponentName = new ComponentName(
7853                                mAndroidApplication.packageName, mResolveActivity.name);
7854                    }
7855                }
7856            }
7857        }
7858
7859        if (DEBUG_PACKAGE_SCANNING) {
7860            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7861                Log.d(TAG, "Scanning package " + pkg.packageName);
7862        }
7863
7864        synchronized (mPackages) {
7865            if (mPackages.containsKey(pkg.packageName)
7866                    || mSharedLibraries.containsKey(pkg.packageName)) {
7867                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7868                        "Application package " + pkg.packageName
7869                                + " already installed.  Skipping duplicate.");
7870            }
7871
7872            // If we're only installing presumed-existing packages, require that the
7873            // scanned APK is both already known and at the path previously established
7874            // for it.  Previously unknown packages we pick up normally, but if we have an
7875            // a priori expectation about this package's install presence, enforce it.
7876            // With a singular exception for new system packages. When an OTA contains
7877            // a new system package, we allow the codepath to change from a system location
7878            // to the user-installed location. If we don't allow this change, any newer,
7879            // user-installed version of the application will be ignored.
7880            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7881                if (mExpectingBetter.containsKey(pkg.packageName)) {
7882                    logCriticalInfo(Log.WARN,
7883                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7884                } else {
7885                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7886                    if (known != null) {
7887                        if (DEBUG_PACKAGE_SCANNING) {
7888                            Log.d(TAG, "Examining " + pkg.codePath
7889                                    + " and requiring known paths " + known.codePathString
7890                                    + " & " + known.resourcePathString);
7891                        }
7892                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7893                                || !pkg.applicationInfo.getResourcePath().equals(
7894                                known.resourcePathString)) {
7895                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7896                                    "Application package " + pkg.packageName
7897                                            + " found at " + pkg.applicationInfo.getCodePath()
7898                                            + " but expected at " + known.codePathString
7899                                            + "; ignoring.");
7900                        }
7901                    }
7902                }
7903            }
7904        }
7905
7906        // Initialize package source and resource directories
7907        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7908        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7909
7910        SharedUserSetting suid = null;
7911        PackageSetting pkgSetting = null;
7912
7913        if (!isSystemApp(pkg)) {
7914            // Only system apps can use these features.
7915            pkg.mOriginalPackages = null;
7916            pkg.mRealPackage = null;
7917            pkg.mAdoptPermissions = null;
7918        }
7919
7920        // Getting the package setting may have a side-effect, so if we
7921        // are only checking if scan would succeed, stash a copy of the
7922        // old setting to restore at the end.
7923        PackageSetting nonMutatedPs = null;
7924
7925        // writer
7926        synchronized (mPackages) {
7927            if (pkg.mSharedUserId != null) {
7928                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7929                if (suid == null) {
7930                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7931                            "Creating application package " + pkg.packageName
7932                            + " for shared user failed");
7933                }
7934                if (DEBUG_PACKAGE_SCANNING) {
7935                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7936                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7937                                + "): packages=" + suid.packages);
7938                }
7939            }
7940
7941            // Check if we are renaming from an original package name.
7942            PackageSetting origPackage = null;
7943            String realName = null;
7944            if (pkg.mOriginalPackages != null) {
7945                // This package may need to be renamed to a previously
7946                // installed name.  Let's check on that...
7947                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7948                if (pkg.mOriginalPackages.contains(renamed)) {
7949                    // This package had originally been installed as the
7950                    // original name, and we have already taken care of
7951                    // transitioning to the new one.  Just update the new
7952                    // one to continue using the old name.
7953                    realName = pkg.mRealPackage;
7954                    if (!pkg.packageName.equals(renamed)) {
7955                        // Callers into this function may have already taken
7956                        // care of renaming the package; only do it here if
7957                        // it is not already done.
7958                        pkg.setPackageName(renamed);
7959                    }
7960
7961                } else {
7962                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7963                        if ((origPackage = mSettings.peekPackageLPr(
7964                                pkg.mOriginalPackages.get(i))) != null) {
7965                            // We do have the package already installed under its
7966                            // original name...  should we use it?
7967                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7968                                // New package is not compatible with original.
7969                                origPackage = null;
7970                                continue;
7971                            } else if (origPackage.sharedUser != null) {
7972                                // Make sure uid is compatible between packages.
7973                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7974                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7975                                            + " to " + pkg.packageName + ": old uid "
7976                                            + origPackage.sharedUser.name
7977                                            + " differs from " + pkg.mSharedUserId);
7978                                    origPackage = null;
7979                                    continue;
7980                                }
7981                                // TODO: Add case when shared user id is added [b/28144775]
7982                            } else {
7983                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7984                                        + pkg.packageName + " to old name " + origPackage.name);
7985                            }
7986                            break;
7987                        }
7988                    }
7989                }
7990            }
7991
7992            if (mTransferedPackages.contains(pkg.packageName)) {
7993                Slog.w(TAG, "Package " + pkg.packageName
7994                        + " was transferred to another, but its .apk remains");
7995            }
7996
7997            // See comments in nonMutatedPs declaration
7998            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7999                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8000                if (foundPs != null) {
8001                    nonMutatedPs = new PackageSetting(foundPs);
8002                }
8003            }
8004
8005            // Just create the setting, don't add it yet. For already existing packages
8006            // the PkgSetting exists already and doesn't have to be created.
8007            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8008                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8009                    pkg.applicationInfo.primaryCpuAbi,
8010                    pkg.applicationInfo.secondaryCpuAbi,
8011                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8012                    user, false);
8013            if (pkgSetting == null) {
8014                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8015                        "Creating application package " + pkg.packageName + " failed");
8016            }
8017
8018            if (pkgSetting.origPackage != null) {
8019                // If we are first transitioning from an original package,
8020                // fix up the new package's name now.  We need to do this after
8021                // looking up the package under its new name, so getPackageLP
8022                // can take care of fiddling things correctly.
8023                pkg.setPackageName(origPackage.name);
8024
8025                // File a report about this.
8026                String msg = "New package " + pkgSetting.realName
8027                        + " renamed to replace old package " + pkgSetting.name;
8028                reportSettingsProblem(Log.WARN, msg);
8029
8030                // Make a note of it.
8031                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8032                    mTransferedPackages.add(origPackage.name);
8033                }
8034
8035                // No longer need to retain this.
8036                pkgSetting.origPackage = null;
8037            }
8038
8039            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8040                // Make a note of it.
8041                mTransferedPackages.add(pkg.packageName);
8042            }
8043
8044            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8045                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8046            }
8047
8048            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8049                // Check all shared libraries and map to their actual file path.
8050                // We only do this here for apps not on a system dir, because those
8051                // are the only ones that can fail an install due to this.  We
8052                // will take care of the system apps by updating all of their
8053                // library paths after the scan is done.
8054                updateSharedLibrariesLPw(pkg, null);
8055            }
8056
8057            if (mFoundPolicyFile) {
8058                SELinuxMMAC.assignSeinfoValue(pkg);
8059            }
8060
8061            pkg.applicationInfo.uid = pkgSetting.appId;
8062            pkg.mExtras = pkgSetting;
8063            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8064                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8065                    // We just determined the app is signed correctly, so bring
8066                    // over the latest parsed certs.
8067                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8068                } else {
8069                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8070                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8071                                "Package " + pkg.packageName + " upgrade keys do not match the "
8072                                + "previously installed version");
8073                    } else {
8074                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8075                        String msg = "System package " + pkg.packageName
8076                            + " signature changed; retaining data.";
8077                        reportSettingsProblem(Log.WARN, msg);
8078                    }
8079                }
8080            } else {
8081                try {
8082                    verifySignaturesLP(pkgSetting, pkg);
8083                    // We just determined the app is signed correctly, so bring
8084                    // over the latest parsed certs.
8085                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8086                } catch (PackageManagerException e) {
8087                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8088                        throw e;
8089                    }
8090                    // The signature has changed, but this package is in the system
8091                    // image...  let's recover!
8092                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8093                    // However...  if this package is part of a shared user, but it
8094                    // doesn't match the signature of the shared user, let's fail.
8095                    // What this means is that you can't change the signatures
8096                    // associated with an overall shared user, which doesn't seem all
8097                    // that unreasonable.
8098                    if (pkgSetting.sharedUser != null) {
8099                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8100                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8101                            throw new PackageManagerException(
8102                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8103                                            "Signature mismatch for shared user: "
8104                                            + pkgSetting.sharedUser);
8105                        }
8106                    }
8107                    // File a report about this.
8108                    String msg = "System package " + pkg.packageName
8109                        + " signature changed; retaining data.";
8110                    reportSettingsProblem(Log.WARN, msg);
8111                }
8112            }
8113            // Verify that this new package doesn't have any content providers
8114            // that conflict with existing packages.  Only do this if the
8115            // package isn't already installed, since we don't want to break
8116            // things that are installed.
8117            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8118                final int N = pkg.providers.size();
8119                int i;
8120                for (i=0; i<N; i++) {
8121                    PackageParser.Provider p = pkg.providers.get(i);
8122                    if (p.info.authority != null) {
8123                        String names[] = p.info.authority.split(";");
8124                        for (int j = 0; j < names.length; j++) {
8125                            if (mProvidersByAuthority.containsKey(names[j])) {
8126                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8127                                final String otherPackageName =
8128                                        ((other != null && other.getComponentName() != null) ?
8129                                                other.getComponentName().getPackageName() : "?");
8130                                throw new PackageManagerException(
8131                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8132                                                "Can't install because provider name " + names[j]
8133                                                + " (in package " + pkg.applicationInfo.packageName
8134                                                + ") is already used by " + otherPackageName);
8135                            }
8136                        }
8137                    }
8138                }
8139            }
8140
8141            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8142                // This package wants to adopt ownership of permissions from
8143                // another package.
8144                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8145                    final String origName = pkg.mAdoptPermissions.get(i);
8146                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8147                    if (orig != null) {
8148                        if (verifyPackageUpdateLPr(orig, pkg)) {
8149                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8150                                    + pkg.packageName);
8151                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8152                        }
8153                    }
8154                }
8155            }
8156        }
8157
8158        final String pkgName = pkg.packageName;
8159
8160        final long scanFileTime = scanFile.lastModified();
8161        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8162        pkg.applicationInfo.processName = fixProcessName(
8163                pkg.applicationInfo.packageName,
8164                pkg.applicationInfo.processName,
8165                pkg.applicationInfo.uid);
8166
8167        if (pkg != mPlatformPackage) {
8168            // Get all of our default paths setup
8169            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8170        }
8171
8172        final String path = scanFile.getPath();
8173        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8174
8175        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8176            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8177
8178            // Some system apps still use directory structure for native libraries
8179            // in which case we might end up not detecting abi solely based on apk
8180            // structure. Try to detect abi based on directory structure.
8181            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8182                    pkg.applicationInfo.primaryCpuAbi == null) {
8183                setBundledAppAbisAndRoots(pkg, pkgSetting);
8184                setNativeLibraryPaths(pkg);
8185            }
8186
8187        } else {
8188            if ((scanFlags & SCAN_MOVE) != 0) {
8189                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8190                // but we already have this packages package info in the PackageSetting. We just
8191                // use that and derive the native library path based on the new codepath.
8192                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8193                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8194            }
8195
8196            // Set native library paths again. For moves, the path will be updated based on the
8197            // ABIs we've determined above. For non-moves, the path will be updated based on the
8198            // ABIs we determined during compilation, but the path will depend on the final
8199            // package path (after the rename away from the stage path).
8200            setNativeLibraryPaths(pkg);
8201        }
8202
8203        // This is a special case for the "system" package, where the ABI is
8204        // dictated by the zygote configuration (and init.rc). We should keep track
8205        // of this ABI so that we can deal with "normal" applications that run under
8206        // the same UID correctly.
8207        if (mPlatformPackage == pkg) {
8208            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8209                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8210        }
8211
8212        // If there's a mismatch between the abi-override in the package setting
8213        // and the abiOverride specified for the install. Warn about this because we
8214        // would've already compiled the app without taking the package setting into
8215        // account.
8216        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8217            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8218                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8219                        " for package " + pkg.packageName);
8220            }
8221        }
8222
8223        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8224        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8225        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8226
8227        // Copy the derived override back to the parsed package, so that we can
8228        // update the package settings accordingly.
8229        pkg.cpuAbiOverride = cpuAbiOverride;
8230
8231        if (DEBUG_ABI_SELECTION) {
8232            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8233                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8234                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8235        }
8236
8237        // Push the derived path down into PackageSettings so we know what to
8238        // clean up at uninstall time.
8239        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8240
8241        if (DEBUG_ABI_SELECTION) {
8242            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8243                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8244                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8245        }
8246
8247        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8248            // We don't do this here during boot because we can do it all
8249            // at once after scanning all existing packages.
8250            //
8251            // We also do this *before* we perform dexopt on this package, so that
8252            // we can avoid redundant dexopts, and also to make sure we've got the
8253            // code and package path correct.
8254            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8255                    pkg, true /* boot complete */);
8256        }
8257
8258        if (mFactoryTest && pkg.requestedPermissions.contains(
8259                android.Manifest.permission.FACTORY_TEST)) {
8260            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8261        }
8262
8263        ArrayList<PackageParser.Package> clientLibPkgs = null;
8264
8265        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8266            if (nonMutatedPs != null) {
8267                synchronized (mPackages) {
8268                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8269                }
8270            }
8271            return pkg;
8272        }
8273
8274        // Only privileged apps and updated privileged apps can add child packages.
8275        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8276            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8277                throw new PackageManagerException("Only privileged apps and updated "
8278                        + "privileged apps can add child packages. Ignoring package "
8279                        + pkg.packageName);
8280            }
8281            final int childCount = pkg.childPackages.size();
8282            for (int i = 0; i < childCount; i++) {
8283                PackageParser.Package childPkg = pkg.childPackages.get(i);
8284                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8285                        childPkg.packageName)) {
8286                    throw new PackageManagerException("Cannot override a child package of "
8287                            + "another disabled system app. Ignoring package " + pkg.packageName);
8288                }
8289            }
8290        }
8291
8292        // writer
8293        synchronized (mPackages) {
8294            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8295                // Only system apps can add new shared libraries.
8296                if (pkg.libraryNames != null) {
8297                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8298                        String name = pkg.libraryNames.get(i);
8299                        boolean allowed = false;
8300                        if (pkg.isUpdatedSystemApp()) {
8301                            // New library entries can only be added through the
8302                            // system image.  This is important to get rid of a lot
8303                            // of nasty edge cases: for example if we allowed a non-
8304                            // system update of the app to add a library, then uninstalling
8305                            // the update would make the library go away, and assumptions
8306                            // we made such as through app install filtering would now
8307                            // have allowed apps on the device which aren't compatible
8308                            // with it.  Better to just have the restriction here, be
8309                            // conservative, and create many fewer cases that can negatively
8310                            // impact the user experience.
8311                            final PackageSetting sysPs = mSettings
8312                                    .getDisabledSystemPkgLPr(pkg.packageName);
8313                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8314                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8315                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8316                                        allowed = true;
8317                                        break;
8318                                    }
8319                                }
8320                            }
8321                        } else {
8322                            allowed = true;
8323                        }
8324                        if (allowed) {
8325                            if (!mSharedLibraries.containsKey(name)) {
8326                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8327                            } else if (!name.equals(pkg.packageName)) {
8328                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8329                                        + name + " already exists; skipping");
8330                            }
8331                        } else {
8332                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8333                                    + name + " that is not declared on system image; skipping");
8334                        }
8335                    }
8336                    if ((scanFlags & SCAN_BOOTING) == 0) {
8337                        // If we are not booting, we need to update any applications
8338                        // that are clients of our shared library.  If we are booting,
8339                        // this will all be done once the scan is complete.
8340                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8341                    }
8342                }
8343            }
8344        }
8345
8346        if ((scanFlags & SCAN_BOOTING) != 0) {
8347            // No apps can run during boot scan, so they don't need to be frozen
8348        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8349            // Caller asked to not kill app, so it's probably not frozen
8350        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8351            // Caller asked us to ignore frozen check for some reason; they
8352            // probably didn't know the package name
8353        } else {
8354            // We're doing major surgery on this package, so it better be frozen
8355            // right now to keep it from launching
8356            checkPackageFrozen(pkgName);
8357        }
8358
8359        // Also need to kill any apps that are dependent on the library.
8360        if (clientLibPkgs != null) {
8361            for (int i=0; i<clientLibPkgs.size(); i++) {
8362                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8363                killApplication(clientPkg.applicationInfo.packageName,
8364                        clientPkg.applicationInfo.uid, "update lib");
8365            }
8366        }
8367
8368        // Make sure we're not adding any bogus keyset info
8369        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8370        ksms.assertScannedPackageValid(pkg);
8371
8372        // writer
8373        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8374
8375        boolean createIdmapFailed = false;
8376        synchronized (mPackages) {
8377            // We don't expect installation to fail beyond this point
8378
8379            // Add the new setting to mSettings
8380            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8381            // Add the new setting to mPackages
8382            mPackages.put(pkg.applicationInfo.packageName, pkg);
8383            // Make sure we don't accidentally delete its data.
8384            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8385            while (iter.hasNext()) {
8386                PackageCleanItem item = iter.next();
8387                if (pkgName.equals(item.packageName)) {
8388                    iter.remove();
8389                }
8390            }
8391
8392            // Take care of first install / last update times.
8393            if (currentTime != 0) {
8394                if (pkgSetting.firstInstallTime == 0) {
8395                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8396                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8397                    pkgSetting.lastUpdateTime = currentTime;
8398                }
8399            } else if (pkgSetting.firstInstallTime == 0) {
8400                // We need *something*.  Take time time stamp of the file.
8401                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8402            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8403                if (scanFileTime != pkgSetting.timeStamp) {
8404                    // A package on the system image has changed; consider this
8405                    // to be an update.
8406                    pkgSetting.lastUpdateTime = scanFileTime;
8407                }
8408            }
8409
8410            // Add the package's KeySets to the global KeySetManagerService
8411            ksms.addScannedPackageLPw(pkg);
8412
8413            int N = pkg.providers.size();
8414            StringBuilder r = null;
8415            int i;
8416            for (i=0; i<N; i++) {
8417                PackageParser.Provider p = pkg.providers.get(i);
8418                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8419                        p.info.processName, pkg.applicationInfo.uid);
8420                mProviders.addProvider(p);
8421                p.syncable = p.info.isSyncable;
8422                if (p.info.authority != null) {
8423                    String names[] = p.info.authority.split(";");
8424                    p.info.authority = null;
8425                    for (int j = 0; j < names.length; j++) {
8426                        if (j == 1 && p.syncable) {
8427                            // We only want the first authority for a provider to possibly be
8428                            // syncable, so if we already added this provider using a different
8429                            // authority clear the syncable flag. We copy the provider before
8430                            // changing it because the mProviders object contains a reference
8431                            // to a provider that we don't want to change.
8432                            // Only do this for the second authority since the resulting provider
8433                            // object can be the same for all future authorities for this provider.
8434                            p = new PackageParser.Provider(p);
8435                            p.syncable = false;
8436                        }
8437                        if (!mProvidersByAuthority.containsKey(names[j])) {
8438                            mProvidersByAuthority.put(names[j], p);
8439                            if (p.info.authority == null) {
8440                                p.info.authority = names[j];
8441                            } else {
8442                                p.info.authority = p.info.authority + ";" + names[j];
8443                            }
8444                            if (DEBUG_PACKAGE_SCANNING) {
8445                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8446                                    Log.d(TAG, "Registered content provider: " + names[j]
8447                                            + ", className = " + p.info.name + ", isSyncable = "
8448                                            + p.info.isSyncable);
8449                            }
8450                        } else {
8451                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8452                            Slog.w(TAG, "Skipping provider name " + names[j] +
8453                                    " (in package " + pkg.applicationInfo.packageName +
8454                                    "): name already used by "
8455                                    + ((other != null && other.getComponentName() != null)
8456                                            ? other.getComponentName().getPackageName() : "?"));
8457                        }
8458                    }
8459                }
8460                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8461                    if (r == null) {
8462                        r = new StringBuilder(256);
8463                    } else {
8464                        r.append(' ');
8465                    }
8466                    r.append(p.info.name);
8467                }
8468            }
8469            if (r != null) {
8470                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8471            }
8472
8473            N = pkg.services.size();
8474            r = null;
8475            for (i=0; i<N; i++) {
8476                PackageParser.Service s = pkg.services.get(i);
8477                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8478                        s.info.processName, pkg.applicationInfo.uid);
8479                mServices.addService(s);
8480                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8481                    if (r == null) {
8482                        r = new StringBuilder(256);
8483                    } else {
8484                        r.append(' ');
8485                    }
8486                    r.append(s.info.name);
8487                }
8488            }
8489            if (r != null) {
8490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8491            }
8492
8493            N = pkg.receivers.size();
8494            r = null;
8495            for (i=0; i<N; i++) {
8496                PackageParser.Activity a = pkg.receivers.get(i);
8497                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8498                        a.info.processName, pkg.applicationInfo.uid);
8499                mReceivers.addActivity(a, "receiver");
8500                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8501                    if (r == null) {
8502                        r = new StringBuilder(256);
8503                    } else {
8504                        r.append(' ');
8505                    }
8506                    r.append(a.info.name);
8507                }
8508            }
8509            if (r != null) {
8510                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8511            }
8512
8513            N = pkg.activities.size();
8514            r = null;
8515            for (i=0; i<N; i++) {
8516                PackageParser.Activity a = pkg.activities.get(i);
8517                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8518                        a.info.processName, pkg.applicationInfo.uid);
8519                mActivities.addActivity(a, "activity");
8520                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8521                    if (r == null) {
8522                        r = new StringBuilder(256);
8523                    } else {
8524                        r.append(' ');
8525                    }
8526                    r.append(a.info.name);
8527                }
8528            }
8529            if (r != null) {
8530                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8531            }
8532
8533            N = pkg.permissionGroups.size();
8534            r = null;
8535            for (i=0; i<N; i++) {
8536                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8537                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8538                if (cur == null) {
8539                    mPermissionGroups.put(pg.info.name, pg);
8540                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8541                        if (r == null) {
8542                            r = new StringBuilder(256);
8543                        } else {
8544                            r.append(' ');
8545                        }
8546                        r.append(pg.info.name);
8547                    }
8548                } else {
8549                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8550                            + pg.info.packageName + " ignored: original from "
8551                            + cur.info.packageName);
8552                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8553                        if (r == null) {
8554                            r = new StringBuilder(256);
8555                        } else {
8556                            r.append(' ');
8557                        }
8558                        r.append("DUP:");
8559                        r.append(pg.info.name);
8560                    }
8561                }
8562            }
8563            if (r != null) {
8564                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8565            }
8566
8567            N = pkg.permissions.size();
8568            r = null;
8569            for (i=0; i<N; i++) {
8570                PackageParser.Permission p = pkg.permissions.get(i);
8571
8572                // Assume by default that we did not install this permission into the system.
8573                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8574
8575                // Now that permission groups have a special meaning, we ignore permission
8576                // groups for legacy apps to prevent unexpected behavior. In particular,
8577                // permissions for one app being granted to someone just becase they happen
8578                // to be in a group defined by another app (before this had no implications).
8579                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8580                    p.group = mPermissionGroups.get(p.info.group);
8581                    // Warn for a permission in an unknown group.
8582                    if (p.info.group != null && p.group == null) {
8583                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8584                                + p.info.packageName + " in an unknown group " + p.info.group);
8585                    }
8586                }
8587
8588                ArrayMap<String, BasePermission> permissionMap =
8589                        p.tree ? mSettings.mPermissionTrees
8590                                : mSettings.mPermissions;
8591                BasePermission bp = permissionMap.get(p.info.name);
8592
8593                // Allow system apps to redefine non-system permissions
8594                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8595                    final boolean currentOwnerIsSystem = (bp.perm != null
8596                            && isSystemApp(bp.perm.owner));
8597                    if (isSystemApp(p.owner)) {
8598                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8599                            // It's a built-in permission and no owner, take ownership now
8600                            bp.packageSetting = pkgSetting;
8601                            bp.perm = p;
8602                            bp.uid = pkg.applicationInfo.uid;
8603                            bp.sourcePackage = p.info.packageName;
8604                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8605                        } else if (!currentOwnerIsSystem) {
8606                            String msg = "New decl " + p.owner + " of permission  "
8607                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8608                            reportSettingsProblem(Log.WARN, msg);
8609                            bp = null;
8610                        }
8611                    }
8612                }
8613
8614                if (bp == null) {
8615                    bp = new BasePermission(p.info.name, p.info.packageName,
8616                            BasePermission.TYPE_NORMAL);
8617                    permissionMap.put(p.info.name, bp);
8618                }
8619
8620                if (bp.perm == null) {
8621                    if (bp.sourcePackage == null
8622                            || bp.sourcePackage.equals(p.info.packageName)) {
8623                        BasePermission tree = findPermissionTreeLP(p.info.name);
8624                        if (tree == null
8625                                || tree.sourcePackage.equals(p.info.packageName)) {
8626                            bp.packageSetting = pkgSetting;
8627                            bp.perm = p;
8628                            bp.uid = pkg.applicationInfo.uid;
8629                            bp.sourcePackage = p.info.packageName;
8630                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8631                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8632                                if (r == null) {
8633                                    r = new StringBuilder(256);
8634                                } else {
8635                                    r.append(' ');
8636                                }
8637                                r.append(p.info.name);
8638                            }
8639                        } else {
8640                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8641                                    + p.info.packageName + " ignored: base tree "
8642                                    + tree.name + " is from package "
8643                                    + tree.sourcePackage);
8644                        }
8645                    } else {
8646                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8647                                + p.info.packageName + " ignored: original from "
8648                                + bp.sourcePackage);
8649                    }
8650                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8651                    if (r == null) {
8652                        r = new StringBuilder(256);
8653                    } else {
8654                        r.append(' ');
8655                    }
8656                    r.append("DUP:");
8657                    r.append(p.info.name);
8658                }
8659                if (bp.perm == p) {
8660                    bp.protectionLevel = p.info.protectionLevel;
8661                }
8662            }
8663
8664            if (r != null) {
8665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8666            }
8667
8668            N = pkg.instrumentation.size();
8669            r = null;
8670            for (i=0; i<N; i++) {
8671                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8672                a.info.packageName = pkg.applicationInfo.packageName;
8673                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8674                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8675                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8676                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8677                a.info.dataDir = pkg.applicationInfo.dataDir;
8678                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8679                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8680
8681                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8682                // need other information about the application, like the ABI and what not ?
8683                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8684                mInstrumentation.put(a.getComponentName(), a);
8685                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8686                    if (r == null) {
8687                        r = new StringBuilder(256);
8688                    } else {
8689                        r.append(' ');
8690                    }
8691                    r.append(a.info.name);
8692                }
8693            }
8694            if (r != null) {
8695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8696            }
8697
8698            if (pkg.protectedBroadcasts != null) {
8699                N = pkg.protectedBroadcasts.size();
8700                for (i=0; i<N; i++) {
8701                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8702                }
8703            }
8704
8705            pkgSetting.setTimeStamp(scanFileTime);
8706
8707            // Create idmap files for pairs of (packages, overlay packages).
8708            // Note: "android", ie framework-res.apk, is handled by native layers.
8709            if (pkg.mOverlayTarget != null) {
8710                // This is an overlay package.
8711                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8712                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8713                        mOverlays.put(pkg.mOverlayTarget,
8714                                new ArrayMap<String, PackageParser.Package>());
8715                    }
8716                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8717                    map.put(pkg.packageName, pkg);
8718                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8719                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8720                        createIdmapFailed = true;
8721                    }
8722                }
8723            } else if (mOverlays.containsKey(pkg.packageName) &&
8724                    !pkg.packageName.equals("android")) {
8725                // This is a regular package, with one or more known overlay packages.
8726                createIdmapsForPackageLI(pkg);
8727            }
8728        }
8729
8730        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8731
8732        if (createIdmapFailed) {
8733            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8734                    "scanPackageLI failed to createIdmap");
8735        }
8736        return pkg;
8737    }
8738
8739    /**
8740     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8741     * is derived purely on the basis of the contents of {@code scanFile} and
8742     * {@code cpuAbiOverride}.
8743     *
8744     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8745     */
8746    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8747                                 String cpuAbiOverride, boolean extractLibs)
8748            throws PackageManagerException {
8749        // TODO: We can probably be smarter about this stuff. For installed apps,
8750        // we can calculate this information at install time once and for all. For
8751        // system apps, we can probably assume that this information doesn't change
8752        // after the first boot scan. As things stand, we do lots of unnecessary work.
8753
8754        // Give ourselves some initial paths; we'll come back for another
8755        // pass once we've determined ABI below.
8756        setNativeLibraryPaths(pkg);
8757
8758        // We would never need to extract libs for forward-locked and external packages,
8759        // since the container service will do it for us. We shouldn't attempt to
8760        // extract libs from system app when it was not updated.
8761        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8762                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8763            extractLibs = false;
8764        }
8765
8766        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8767        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8768
8769        NativeLibraryHelper.Handle handle = null;
8770        try {
8771            handle = NativeLibraryHelper.Handle.create(pkg);
8772            // TODO(multiArch): This can be null for apps that didn't go through the
8773            // usual installation process. We can calculate it again, like we
8774            // do during install time.
8775            //
8776            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8777            // unnecessary.
8778            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8779
8780            // Null out the abis so that they can be recalculated.
8781            pkg.applicationInfo.primaryCpuAbi = null;
8782            pkg.applicationInfo.secondaryCpuAbi = null;
8783            if (isMultiArch(pkg.applicationInfo)) {
8784                // Warn if we've set an abiOverride for multi-lib packages..
8785                // By definition, we need to copy both 32 and 64 bit libraries for
8786                // such packages.
8787                if (pkg.cpuAbiOverride != null
8788                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8789                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8790                }
8791
8792                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8793                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8794                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8795                    if (extractLibs) {
8796                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8797                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8798                                useIsaSpecificSubdirs);
8799                    } else {
8800                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8801                    }
8802                }
8803
8804                maybeThrowExceptionForMultiArchCopy(
8805                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8806
8807                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8808                    if (extractLibs) {
8809                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8810                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8811                                useIsaSpecificSubdirs);
8812                    } else {
8813                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8814                    }
8815                }
8816
8817                maybeThrowExceptionForMultiArchCopy(
8818                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8819
8820                if (abi64 >= 0) {
8821                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8822                }
8823
8824                if (abi32 >= 0) {
8825                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8826                    if (abi64 >= 0) {
8827                        if (pkg.use32bitAbi) {
8828                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8829                            pkg.applicationInfo.primaryCpuAbi = abi;
8830                        } else {
8831                            pkg.applicationInfo.secondaryCpuAbi = abi;
8832                        }
8833                    } else {
8834                        pkg.applicationInfo.primaryCpuAbi = abi;
8835                    }
8836                }
8837
8838            } else {
8839                String[] abiList = (cpuAbiOverride != null) ?
8840                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8841
8842                // Enable gross and lame hacks for apps that are built with old
8843                // SDK tools. We must scan their APKs for renderscript bitcode and
8844                // not launch them if it's present. Don't bother checking on devices
8845                // that don't have 64 bit support.
8846                boolean needsRenderScriptOverride = false;
8847                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8848                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8849                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8850                    needsRenderScriptOverride = true;
8851                }
8852
8853                final int copyRet;
8854                if (extractLibs) {
8855                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8856                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8857                } else {
8858                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8859                }
8860
8861                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8862                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8863                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8864                }
8865
8866                if (copyRet >= 0) {
8867                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8868                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8869                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8870                } else if (needsRenderScriptOverride) {
8871                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8872                }
8873            }
8874        } catch (IOException ioe) {
8875            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8876        } finally {
8877            IoUtils.closeQuietly(handle);
8878        }
8879
8880        // Now that we've calculated the ABIs and determined if it's an internal app,
8881        // we will go ahead and populate the nativeLibraryPath.
8882        setNativeLibraryPaths(pkg);
8883    }
8884
8885    /**
8886     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8887     * i.e, so that all packages can be run inside a single process if required.
8888     *
8889     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8890     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8891     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8892     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8893     * updating a package that belongs to a shared user.
8894     *
8895     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8896     * adds unnecessary complexity.
8897     */
8898    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8899            PackageParser.Package scannedPackage, boolean bootComplete) {
8900        String requiredInstructionSet = null;
8901        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8902            requiredInstructionSet = VMRuntime.getInstructionSet(
8903                     scannedPackage.applicationInfo.primaryCpuAbi);
8904        }
8905
8906        PackageSetting requirer = null;
8907        for (PackageSetting ps : packagesForUser) {
8908            // If packagesForUser contains scannedPackage, we skip it. This will happen
8909            // when scannedPackage is an update of an existing package. Without this check,
8910            // we will never be able to change the ABI of any package belonging to a shared
8911            // user, even if it's compatible with other packages.
8912            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8913                if (ps.primaryCpuAbiString == null) {
8914                    continue;
8915                }
8916
8917                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8918                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8919                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8920                    // this but there's not much we can do.
8921                    String errorMessage = "Instruction set mismatch, "
8922                            + ((requirer == null) ? "[caller]" : requirer)
8923                            + " requires " + requiredInstructionSet + " whereas " + ps
8924                            + " requires " + instructionSet;
8925                    Slog.w(TAG, errorMessage);
8926                }
8927
8928                if (requiredInstructionSet == null) {
8929                    requiredInstructionSet = instructionSet;
8930                    requirer = ps;
8931                }
8932            }
8933        }
8934
8935        if (requiredInstructionSet != null) {
8936            String adjustedAbi;
8937            if (requirer != null) {
8938                // requirer != null implies that either scannedPackage was null or that scannedPackage
8939                // did not require an ABI, in which case we have to adjust scannedPackage to match
8940                // the ABI of the set (which is the same as requirer's ABI)
8941                adjustedAbi = requirer.primaryCpuAbiString;
8942                if (scannedPackage != null) {
8943                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8944                }
8945            } else {
8946                // requirer == null implies that we're updating all ABIs in the set to
8947                // match scannedPackage.
8948                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8949            }
8950
8951            for (PackageSetting ps : packagesForUser) {
8952                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8953                    if (ps.primaryCpuAbiString != null) {
8954                        continue;
8955                    }
8956
8957                    ps.primaryCpuAbiString = adjustedAbi;
8958                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8959                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8960                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8961                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8962                                + " (requirer="
8963                                + (requirer == null ? "null" : requirer.pkg.packageName)
8964                                + ", scannedPackage="
8965                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8966                                + ")");
8967                        try {
8968                            mInstaller.rmdex(ps.codePathString,
8969                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8970                        } catch (InstallerException ignored) {
8971                        }
8972                    }
8973                }
8974            }
8975        }
8976    }
8977
8978    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8979        synchronized (mPackages) {
8980            mResolverReplaced = true;
8981            // Set up information for custom user intent resolution activity.
8982            mResolveActivity.applicationInfo = pkg.applicationInfo;
8983            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8984            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8985            mResolveActivity.processName = pkg.applicationInfo.packageName;
8986            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8987            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8988                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8989            mResolveActivity.theme = 0;
8990            mResolveActivity.exported = true;
8991            mResolveActivity.enabled = true;
8992            mResolveInfo.activityInfo = mResolveActivity;
8993            mResolveInfo.priority = 0;
8994            mResolveInfo.preferredOrder = 0;
8995            mResolveInfo.match = 0;
8996            mResolveComponentName = mCustomResolverComponentName;
8997            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8998                    mResolveComponentName);
8999        }
9000    }
9001
9002    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9003        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9004
9005        // Set up information for ephemeral installer activity
9006        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9007        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9008        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9009        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9010        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9011        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9012                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9013        mEphemeralInstallerActivity.theme = 0;
9014        mEphemeralInstallerActivity.exported = true;
9015        mEphemeralInstallerActivity.enabled = true;
9016        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9017        mEphemeralInstallerInfo.priority = 0;
9018        mEphemeralInstallerInfo.preferredOrder = 0;
9019        mEphemeralInstallerInfo.match = 0;
9020
9021        if (DEBUG_EPHEMERAL) {
9022            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9023        }
9024    }
9025
9026    private static String calculateBundledApkRoot(final String codePathString) {
9027        final File codePath = new File(codePathString);
9028        final File codeRoot;
9029        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9030            codeRoot = Environment.getRootDirectory();
9031        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9032            codeRoot = Environment.getOemDirectory();
9033        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9034            codeRoot = Environment.getVendorDirectory();
9035        } else {
9036            // Unrecognized code path; take its top real segment as the apk root:
9037            // e.g. /something/app/blah.apk => /something
9038            try {
9039                File f = codePath.getCanonicalFile();
9040                File parent = f.getParentFile();    // non-null because codePath is a file
9041                File tmp;
9042                while ((tmp = parent.getParentFile()) != null) {
9043                    f = parent;
9044                    parent = tmp;
9045                }
9046                codeRoot = f;
9047                Slog.w(TAG, "Unrecognized code path "
9048                        + codePath + " - using " + codeRoot);
9049            } catch (IOException e) {
9050                // Can't canonicalize the code path -- shenanigans?
9051                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9052                return Environment.getRootDirectory().getPath();
9053            }
9054        }
9055        return codeRoot.getPath();
9056    }
9057
9058    /**
9059     * Derive and set the location of native libraries for the given package,
9060     * which varies depending on where and how the package was installed.
9061     */
9062    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9063        final ApplicationInfo info = pkg.applicationInfo;
9064        final String codePath = pkg.codePath;
9065        final File codeFile = new File(codePath);
9066        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9067        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9068
9069        info.nativeLibraryRootDir = null;
9070        info.nativeLibraryRootRequiresIsa = false;
9071        info.nativeLibraryDir = null;
9072        info.secondaryNativeLibraryDir = null;
9073
9074        if (isApkFile(codeFile)) {
9075            // Monolithic install
9076            if (bundledApp) {
9077                // If "/system/lib64/apkname" exists, assume that is the per-package
9078                // native library directory to use; otherwise use "/system/lib/apkname".
9079                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9080                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9081                        getPrimaryInstructionSet(info));
9082
9083                // This is a bundled system app so choose the path based on the ABI.
9084                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9085                // is just the default path.
9086                final String apkName = deriveCodePathName(codePath);
9087                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9088                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9089                        apkName).getAbsolutePath();
9090
9091                if (info.secondaryCpuAbi != null) {
9092                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9093                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9094                            secondaryLibDir, apkName).getAbsolutePath();
9095                }
9096            } else if (asecApp) {
9097                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9098                        .getAbsolutePath();
9099            } else {
9100                final String apkName = deriveCodePathName(codePath);
9101                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9102                        .getAbsolutePath();
9103            }
9104
9105            info.nativeLibraryRootRequiresIsa = false;
9106            info.nativeLibraryDir = info.nativeLibraryRootDir;
9107        } else {
9108            // Cluster install
9109            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9110            info.nativeLibraryRootRequiresIsa = true;
9111
9112            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9113                    getPrimaryInstructionSet(info)).getAbsolutePath();
9114
9115            if (info.secondaryCpuAbi != null) {
9116                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9117                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9118            }
9119        }
9120    }
9121
9122    /**
9123     * Calculate the abis and roots for a bundled app. These can uniquely
9124     * be determined from the contents of the system partition, i.e whether
9125     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9126     * of this information, and instead assume that the system was built
9127     * sensibly.
9128     */
9129    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9130                                           PackageSetting pkgSetting) {
9131        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9132
9133        // If "/system/lib64/apkname" exists, assume that is the per-package
9134        // native library directory to use; otherwise use "/system/lib/apkname".
9135        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9136        setBundledAppAbi(pkg, apkRoot, apkName);
9137        // pkgSetting might be null during rescan following uninstall of updates
9138        // to a bundled app, so accommodate that possibility.  The settings in
9139        // that case will be established later from the parsed package.
9140        //
9141        // If the settings aren't null, sync them up with what we've just derived.
9142        // note that apkRoot isn't stored in the package settings.
9143        if (pkgSetting != null) {
9144            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9145            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9146        }
9147    }
9148
9149    /**
9150     * Deduces the ABI of a bundled app and sets the relevant fields on the
9151     * parsed pkg object.
9152     *
9153     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9154     *        under which system libraries are installed.
9155     * @param apkName the name of the installed package.
9156     */
9157    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9158        final File codeFile = new File(pkg.codePath);
9159
9160        final boolean has64BitLibs;
9161        final boolean has32BitLibs;
9162        if (isApkFile(codeFile)) {
9163            // Monolithic install
9164            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9165            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9166        } else {
9167            // Cluster install
9168            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9169            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9170                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9171                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9172                has64BitLibs = (new File(rootDir, isa)).exists();
9173            } else {
9174                has64BitLibs = false;
9175            }
9176            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9177                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9178                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9179                has32BitLibs = (new File(rootDir, isa)).exists();
9180            } else {
9181                has32BitLibs = false;
9182            }
9183        }
9184
9185        if (has64BitLibs && !has32BitLibs) {
9186            // The package has 64 bit libs, but not 32 bit libs. Its primary
9187            // ABI should be 64 bit. We can safely assume here that the bundled
9188            // native libraries correspond to the most preferred ABI in the list.
9189
9190            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9191            pkg.applicationInfo.secondaryCpuAbi = null;
9192        } else if (has32BitLibs && !has64BitLibs) {
9193            // The package has 32 bit libs but not 64 bit libs. Its primary
9194            // ABI should be 32 bit.
9195
9196            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9197            pkg.applicationInfo.secondaryCpuAbi = null;
9198        } else if (has32BitLibs && has64BitLibs) {
9199            // The application has both 64 and 32 bit bundled libraries. We check
9200            // here that the app declares multiArch support, and warn if it doesn't.
9201            //
9202            // We will be lenient here and record both ABIs. The primary will be the
9203            // ABI that's higher on the list, i.e, a device that's configured to prefer
9204            // 64 bit apps will see a 64 bit primary ABI,
9205
9206            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9207                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9208            }
9209
9210            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9211                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9212                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9213            } else {
9214                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9215                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9216            }
9217        } else {
9218            pkg.applicationInfo.primaryCpuAbi = null;
9219            pkg.applicationInfo.secondaryCpuAbi = null;
9220        }
9221    }
9222
9223    private void killApplication(String pkgName, int appId, String reason) {
9224        // Request the ActivityManager to kill the process(only for existing packages)
9225        // so that we do not end up in a confused state while the user is still using the older
9226        // version of the application while the new one gets installed.
9227        final long token = Binder.clearCallingIdentity();
9228        try {
9229            IActivityManager am = ActivityManagerNative.getDefault();
9230            if (am != null) {
9231                try {
9232                    am.killApplicationWithAppId(pkgName, appId, reason);
9233                } catch (RemoteException e) {
9234                }
9235            }
9236        } finally {
9237            Binder.restoreCallingIdentity(token);
9238        }
9239    }
9240
9241    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9242        // Remove the parent package setting
9243        PackageSetting ps = (PackageSetting) pkg.mExtras;
9244        if (ps != null) {
9245            removePackageLI(ps, chatty);
9246        }
9247        // Remove the child package setting
9248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9249        for (int i = 0; i < childCount; i++) {
9250            PackageParser.Package childPkg = pkg.childPackages.get(i);
9251            ps = (PackageSetting) childPkg.mExtras;
9252            if (ps != null) {
9253                removePackageLI(ps, chatty);
9254            }
9255        }
9256    }
9257
9258    void removePackageLI(PackageSetting ps, boolean chatty) {
9259        if (DEBUG_INSTALL) {
9260            if (chatty)
9261                Log.d(TAG, "Removing package " + ps.name);
9262        }
9263
9264        // writer
9265        synchronized (mPackages) {
9266            mPackages.remove(ps.name);
9267            final PackageParser.Package pkg = ps.pkg;
9268            if (pkg != null) {
9269                cleanPackageDataStructuresLILPw(pkg, chatty);
9270            }
9271        }
9272    }
9273
9274    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9275        if (DEBUG_INSTALL) {
9276            if (chatty)
9277                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9278        }
9279
9280        // writer
9281        synchronized (mPackages) {
9282            // Remove the parent package
9283            mPackages.remove(pkg.applicationInfo.packageName);
9284            cleanPackageDataStructuresLILPw(pkg, chatty);
9285
9286            // Remove the child packages
9287            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9288            for (int i = 0; i < childCount; i++) {
9289                PackageParser.Package childPkg = pkg.childPackages.get(i);
9290                mPackages.remove(childPkg.applicationInfo.packageName);
9291                cleanPackageDataStructuresLILPw(childPkg, chatty);
9292            }
9293        }
9294    }
9295
9296    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9297        int N = pkg.providers.size();
9298        StringBuilder r = null;
9299        int i;
9300        for (i=0; i<N; i++) {
9301            PackageParser.Provider p = pkg.providers.get(i);
9302            mProviders.removeProvider(p);
9303            if (p.info.authority == null) {
9304
9305                /* There was another ContentProvider with this authority when
9306                 * this app was installed so this authority is null,
9307                 * Ignore it as we don't have to unregister the provider.
9308                 */
9309                continue;
9310            }
9311            String names[] = p.info.authority.split(";");
9312            for (int j = 0; j < names.length; j++) {
9313                if (mProvidersByAuthority.get(names[j]) == p) {
9314                    mProvidersByAuthority.remove(names[j]);
9315                    if (DEBUG_REMOVE) {
9316                        if (chatty)
9317                            Log.d(TAG, "Unregistered content provider: " + names[j]
9318                                    + ", className = " + p.info.name + ", isSyncable = "
9319                                    + p.info.isSyncable);
9320                    }
9321                }
9322            }
9323            if (DEBUG_REMOVE && chatty) {
9324                if (r == null) {
9325                    r = new StringBuilder(256);
9326                } else {
9327                    r.append(' ');
9328                }
9329                r.append(p.info.name);
9330            }
9331        }
9332        if (r != null) {
9333            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9334        }
9335
9336        N = pkg.services.size();
9337        r = null;
9338        for (i=0; i<N; i++) {
9339            PackageParser.Service s = pkg.services.get(i);
9340            mServices.removeService(s);
9341            if (chatty) {
9342                if (r == null) {
9343                    r = new StringBuilder(256);
9344                } else {
9345                    r.append(' ');
9346                }
9347                r.append(s.info.name);
9348            }
9349        }
9350        if (r != null) {
9351            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9352        }
9353
9354        N = pkg.receivers.size();
9355        r = null;
9356        for (i=0; i<N; i++) {
9357            PackageParser.Activity a = pkg.receivers.get(i);
9358            mReceivers.removeActivity(a, "receiver");
9359            if (DEBUG_REMOVE && chatty) {
9360                if (r == null) {
9361                    r = new StringBuilder(256);
9362                } else {
9363                    r.append(' ');
9364                }
9365                r.append(a.info.name);
9366            }
9367        }
9368        if (r != null) {
9369            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9370        }
9371
9372        N = pkg.activities.size();
9373        r = null;
9374        for (i=0; i<N; i++) {
9375            PackageParser.Activity a = pkg.activities.get(i);
9376            mActivities.removeActivity(a, "activity");
9377            if (DEBUG_REMOVE && chatty) {
9378                if (r == null) {
9379                    r = new StringBuilder(256);
9380                } else {
9381                    r.append(' ');
9382                }
9383                r.append(a.info.name);
9384            }
9385        }
9386        if (r != null) {
9387            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9388        }
9389
9390        N = pkg.permissions.size();
9391        r = null;
9392        for (i=0; i<N; i++) {
9393            PackageParser.Permission p = pkg.permissions.get(i);
9394            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9395            if (bp == null) {
9396                bp = mSettings.mPermissionTrees.get(p.info.name);
9397            }
9398            if (bp != null && bp.perm == p) {
9399                bp.perm = null;
9400                if (DEBUG_REMOVE && chatty) {
9401                    if (r == null) {
9402                        r = new StringBuilder(256);
9403                    } else {
9404                        r.append(' ');
9405                    }
9406                    r.append(p.info.name);
9407                }
9408            }
9409            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9410                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9411                if (appOpPkgs != null) {
9412                    appOpPkgs.remove(pkg.packageName);
9413                }
9414            }
9415        }
9416        if (r != null) {
9417            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9418        }
9419
9420        N = pkg.requestedPermissions.size();
9421        r = null;
9422        for (i=0; i<N; i++) {
9423            String perm = pkg.requestedPermissions.get(i);
9424            BasePermission bp = mSettings.mPermissions.get(perm);
9425            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9426                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9427                if (appOpPkgs != null) {
9428                    appOpPkgs.remove(pkg.packageName);
9429                    if (appOpPkgs.isEmpty()) {
9430                        mAppOpPermissionPackages.remove(perm);
9431                    }
9432                }
9433            }
9434        }
9435        if (r != null) {
9436            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9437        }
9438
9439        N = pkg.instrumentation.size();
9440        r = null;
9441        for (i=0; i<N; i++) {
9442            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9443            mInstrumentation.remove(a.getComponentName());
9444            if (DEBUG_REMOVE && chatty) {
9445                if (r == null) {
9446                    r = new StringBuilder(256);
9447                } else {
9448                    r.append(' ');
9449                }
9450                r.append(a.info.name);
9451            }
9452        }
9453        if (r != null) {
9454            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9455        }
9456
9457        r = null;
9458        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9459            // Only system apps can hold shared libraries.
9460            if (pkg.libraryNames != null) {
9461                for (i=0; i<pkg.libraryNames.size(); i++) {
9462                    String name = pkg.libraryNames.get(i);
9463                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9464                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9465                        mSharedLibraries.remove(name);
9466                        if (DEBUG_REMOVE && chatty) {
9467                            if (r == null) {
9468                                r = new StringBuilder(256);
9469                            } else {
9470                                r.append(' ');
9471                            }
9472                            r.append(name);
9473                        }
9474                    }
9475                }
9476            }
9477        }
9478        if (r != null) {
9479            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9480        }
9481    }
9482
9483    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9484        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9485            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9486                return true;
9487            }
9488        }
9489        return false;
9490    }
9491
9492    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9493    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9494    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9495
9496    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9497        // Update the parent permissions
9498        updatePermissionsLPw(pkg.packageName, pkg, flags);
9499        // Update the child permissions
9500        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9501        for (int i = 0; i < childCount; i++) {
9502            PackageParser.Package childPkg = pkg.childPackages.get(i);
9503            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9504        }
9505    }
9506
9507    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9508            int flags) {
9509        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9510        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9511    }
9512
9513    private void updatePermissionsLPw(String changingPkg,
9514            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9515        // Make sure there are no dangling permission trees.
9516        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9517        while (it.hasNext()) {
9518            final BasePermission bp = it.next();
9519            if (bp.packageSetting == null) {
9520                // We may not yet have parsed the package, so just see if
9521                // we still know about its settings.
9522                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9523            }
9524            if (bp.packageSetting == null) {
9525                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9526                        + " from package " + bp.sourcePackage);
9527                it.remove();
9528            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9529                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9530                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9531                            + " from package " + bp.sourcePackage);
9532                    flags |= UPDATE_PERMISSIONS_ALL;
9533                    it.remove();
9534                }
9535            }
9536        }
9537
9538        // Make sure all dynamic permissions have been assigned to a package,
9539        // and make sure there are no dangling permissions.
9540        it = mSettings.mPermissions.values().iterator();
9541        while (it.hasNext()) {
9542            final BasePermission bp = it.next();
9543            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9544                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9545                        + bp.name + " pkg=" + bp.sourcePackage
9546                        + " info=" + bp.pendingInfo);
9547                if (bp.packageSetting == null && bp.pendingInfo != null) {
9548                    final BasePermission tree = findPermissionTreeLP(bp.name);
9549                    if (tree != null && tree.perm != null) {
9550                        bp.packageSetting = tree.packageSetting;
9551                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9552                                new PermissionInfo(bp.pendingInfo));
9553                        bp.perm.info.packageName = tree.perm.info.packageName;
9554                        bp.perm.info.name = bp.name;
9555                        bp.uid = tree.uid;
9556                    }
9557                }
9558            }
9559            if (bp.packageSetting == null) {
9560                // We may not yet have parsed the package, so just see if
9561                // we still know about its settings.
9562                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9563            }
9564            if (bp.packageSetting == null) {
9565                Slog.w(TAG, "Removing dangling permission: " + bp.name
9566                        + " from package " + bp.sourcePackage);
9567                it.remove();
9568            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9569                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9570                    Slog.i(TAG, "Removing old permission: " + bp.name
9571                            + " from package " + bp.sourcePackage);
9572                    flags |= UPDATE_PERMISSIONS_ALL;
9573                    it.remove();
9574                }
9575            }
9576        }
9577
9578        // Now update the permissions for all packages, in particular
9579        // replace the granted permissions of the system packages.
9580        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9581            for (PackageParser.Package pkg : mPackages.values()) {
9582                if (pkg != pkgInfo) {
9583                    // Only replace for packages on requested volume
9584                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9585                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9586                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9587                    grantPermissionsLPw(pkg, replace, changingPkg);
9588                }
9589            }
9590        }
9591
9592        if (pkgInfo != null) {
9593            // Only replace for packages on requested volume
9594            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9595            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9596                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9597            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9598        }
9599    }
9600
9601    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9602            String packageOfInterest) {
9603        // IMPORTANT: There are two types of permissions: install and runtime.
9604        // Install time permissions are granted when the app is installed to
9605        // all device users and users added in the future. Runtime permissions
9606        // are granted at runtime explicitly to specific users. Normal and signature
9607        // protected permissions are install time permissions. Dangerous permissions
9608        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9609        // otherwise they are runtime permissions. This function does not manage
9610        // runtime permissions except for the case an app targeting Lollipop MR1
9611        // being upgraded to target a newer SDK, in which case dangerous permissions
9612        // are transformed from install time to runtime ones.
9613
9614        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9615        if (ps == null) {
9616            return;
9617        }
9618
9619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9620
9621        PermissionsState permissionsState = ps.getPermissionsState();
9622        PermissionsState origPermissions = permissionsState;
9623
9624        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9625
9626        boolean runtimePermissionsRevoked = false;
9627        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9628
9629        boolean changedInstallPermission = false;
9630
9631        if (replace) {
9632            ps.installPermissionsFixed = false;
9633            if (!ps.isSharedUser()) {
9634                origPermissions = new PermissionsState(permissionsState);
9635                permissionsState.reset();
9636            } else {
9637                // We need to know only about runtime permission changes since the
9638                // calling code always writes the install permissions state but
9639                // the runtime ones are written only if changed. The only cases of
9640                // changed runtime permissions here are promotion of an install to
9641                // runtime and revocation of a runtime from a shared user.
9642                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9643                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9644                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9645                    runtimePermissionsRevoked = true;
9646                }
9647            }
9648        }
9649
9650        permissionsState.setGlobalGids(mGlobalGids);
9651
9652        final int N = pkg.requestedPermissions.size();
9653        for (int i=0; i<N; i++) {
9654            final String name = pkg.requestedPermissions.get(i);
9655            final BasePermission bp = mSettings.mPermissions.get(name);
9656
9657            if (DEBUG_INSTALL) {
9658                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9659            }
9660
9661            if (bp == null || bp.packageSetting == null) {
9662                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9663                    Slog.w(TAG, "Unknown permission " + name
9664                            + " in package " + pkg.packageName);
9665                }
9666                continue;
9667            }
9668
9669            final String perm = bp.name;
9670            boolean allowedSig = false;
9671            int grant = GRANT_DENIED;
9672
9673            // Keep track of app op permissions.
9674            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9675                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9676                if (pkgs == null) {
9677                    pkgs = new ArraySet<>();
9678                    mAppOpPermissionPackages.put(bp.name, pkgs);
9679                }
9680                pkgs.add(pkg.packageName);
9681            }
9682
9683            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9684            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9685                    >= Build.VERSION_CODES.M;
9686            switch (level) {
9687                case PermissionInfo.PROTECTION_NORMAL: {
9688                    // For all apps normal permissions are install time ones.
9689                    grant = GRANT_INSTALL;
9690                } break;
9691
9692                case PermissionInfo.PROTECTION_DANGEROUS: {
9693                    // If a permission review is required for legacy apps we represent
9694                    // their permissions as always granted runtime ones since we need
9695                    // to keep the review required permission flag per user while an
9696                    // install permission's state is shared across all users.
9697                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9698                        // For legacy apps dangerous permissions are install time ones.
9699                        grant = GRANT_INSTALL;
9700                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9701                        // For legacy apps that became modern, install becomes runtime.
9702                        grant = GRANT_UPGRADE;
9703                    } else if (mPromoteSystemApps
9704                            && isSystemApp(ps)
9705                            && mExistingSystemPackages.contains(ps.name)) {
9706                        // For legacy system apps, install becomes runtime.
9707                        // We cannot check hasInstallPermission() for system apps since those
9708                        // permissions were granted implicitly and not persisted pre-M.
9709                        grant = GRANT_UPGRADE;
9710                    } else {
9711                        // For modern apps keep runtime permissions unchanged.
9712                        grant = GRANT_RUNTIME;
9713                    }
9714                } break;
9715
9716                case PermissionInfo.PROTECTION_SIGNATURE: {
9717                    // For all apps signature permissions are install time ones.
9718                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9719                    if (allowedSig) {
9720                        grant = GRANT_INSTALL;
9721                    }
9722                } break;
9723            }
9724
9725            if (DEBUG_INSTALL) {
9726                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9727            }
9728
9729            if (grant != GRANT_DENIED) {
9730                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9731                    // If this is an existing, non-system package, then
9732                    // we can't add any new permissions to it.
9733                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9734                        // Except...  if this is a permission that was added
9735                        // to the platform (note: need to only do this when
9736                        // updating the platform).
9737                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9738                            grant = GRANT_DENIED;
9739                        }
9740                    }
9741                }
9742
9743                switch (grant) {
9744                    case GRANT_INSTALL: {
9745                        // Revoke this as runtime permission to handle the case of
9746                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9747                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9748                            if (origPermissions.getRuntimePermissionState(
9749                                    bp.name, userId) != null) {
9750                                // Revoke the runtime permission and clear the flags.
9751                                origPermissions.revokeRuntimePermission(bp, userId);
9752                                origPermissions.updatePermissionFlags(bp, userId,
9753                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9754                                // If we revoked a permission permission, we have to write.
9755                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9756                                        changedRuntimePermissionUserIds, userId);
9757                            }
9758                        }
9759                        // Grant an install permission.
9760                        if (permissionsState.grantInstallPermission(bp) !=
9761                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9762                            changedInstallPermission = true;
9763                        }
9764                    } break;
9765
9766                    case GRANT_RUNTIME: {
9767                        // Grant previously granted runtime permissions.
9768                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9769                            PermissionState permissionState = origPermissions
9770                                    .getRuntimePermissionState(bp.name, userId);
9771                            int flags = permissionState != null
9772                                    ? permissionState.getFlags() : 0;
9773                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9774                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9775                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9776                                    // If we cannot put the permission as it was, we have to write.
9777                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9778                                            changedRuntimePermissionUserIds, userId);
9779                                }
9780                                // If the app supports runtime permissions no need for a review.
9781                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9782                                        && appSupportsRuntimePermissions
9783                                        && (flags & PackageManager
9784                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9785                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9786                                    // Since we changed the flags, we have to write.
9787                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9788                                            changedRuntimePermissionUserIds, userId);
9789                                }
9790                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9791                                    && !appSupportsRuntimePermissions) {
9792                                // For legacy apps that need a permission review, every new
9793                                // runtime permission is granted but it is pending a review.
9794                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9795                                    permissionsState.grantRuntimePermission(bp, userId);
9796                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9797                                    // We changed the permission and flags, hence have to write.
9798                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9799                                            changedRuntimePermissionUserIds, userId);
9800                                }
9801                            }
9802                            // Propagate the permission flags.
9803                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9804                        }
9805                    } break;
9806
9807                    case GRANT_UPGRADE: {
9808                        // Grant runtime permissions for a previously held install permission.
9809                        PermissionState permissionState = origPermissions
9810                                .getInstallPermissionState(bp.name);
9811                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9812
9813                        if (origPermissions.revokeInstallPermission(bp)
9814                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9815                            // We will be transferring the permission flags, so clear them.
9816                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9817                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9818                            changedInstallPermission = true;
9819                        }
9820
9821                        // If the permission is not to be promoted to runtime we ignore it and
9822                        // also its other flags as they are not applicable to install permissions.
9823                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9824                            for (int userId : currentUserIds) {
9825                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9826                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9827                                    // Transfer the permission flags.
9828                                    permissionsState.updatePermissionFlags(bp, userId,
9829                                            flags, flags);
9830                                    // If we granted the permission, we have to write.
9831                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9832                                            changedRuntimePermissionUserIds, userId);
9833                                }
9834                            }
9835                        }
9836                    } break;
9837
9838                    default: {
9839                        if (packageOfInterest == null
9840                                || packageOfInterest.equals(pkg.packageName)) {
9841                            Slog.w(TAG, "Not granting permission " + perm
9842                                    + " to package " + pkg.packageName
9843                                    + " because it was previously installed without");
9844                        }
9845                    } break;
9846                }
9847            } else {
9848                if (permissionsState.revokeInstallPermission(bp) !=
9849                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9850                    // Also drop the permission flags.
9851                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9852                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9853                    changedInstallPermission = true;
9854                    Slog.i(TAG, "Un-granting permission " + perm
9855                            + " from package " + pkg.packageName
9856                            + " (protectionLevel=" + bp.protectionLevel
9857                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9858                            + ")");
9859                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9860                    // Don't print warning for app op permissions, since it is fine for them
9861                    // not to be granted, there is a UI for the user to decide.
9862                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9863                        Slog.w(TAG, "Not granting permission " + perm
9864                                + " to package " + pkg.packageName
9865                                + " (protectionLevel=" + bp.protectionLevel
9866                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9867                                + ")");
9868                    }
9869                }
9870            }
9871        }
9872
9873        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9874                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9875            // This is the first that we have heard about this package, so the
9876            // permissions we have now selected are fixed until explicitly
9877            // changed.
9878            ps.installPermissionsFixed = true;
9879        }
9880
9881        // Persist the runtime permissions state for users with changes. If permissions
9882        // were revoked because no app in the shared user declares them we have to
9883        // write synchronously to avoid losing runtime permissions state.
9884        for (int userId : changedRuntimePermissionUserIds) {
9885            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9886        }
9887
9888        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9889    }
9890
9891    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9892        boolean allowed = false;
9893        final int NP = PackageParser.NEW_PERMISSIONS.length;
9894        for (int ip=0; ip<NP; ip++) {
9895            final PackageParser.NewPermissionInfo npi
9896                    = PackageParser.NEW_PERMISSIONS[ip];
9897            if (npi.name.equals(perm)
9898                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9899                allowed = true;
9900                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9901                        + pkg.packageName);
9902                break;
9903            }
9904        }
9905        return allowed;
9906    }
9907
9908    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9909            BasePermission bp, PermissionsState origPermissions) {
9910        boolean allowed;
9911        allowed = (compareSignatures(
9912                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9913                        == PackageManager.SIGNATURE_MATCH)
9914                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9915                        == PackageManager.SIGNATURE_MATCH);
9916        if (!allowed && (bp.protectionLevel
9917                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9918            if (isSystemApp(pkg)) {
9919                // For updated system applications, a system permission
9920                // is granted only if it had been defined by the original application.
9921                if (pkg.isUpdatedSystemApp()) {
9922                    final PackageSetting sysPs = mSettings
9923                            .getDisabledSystemPkgLPr(pkg.packageName);
9924                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9925                        // If the original was granted this permission, we take
9926                        // that grant decision as read and propagate it to the
9927                        // update.
9928                        if (sysPs.isPrivileged()) {
9929                            allowed = true;
9930                        }
9931                    } else {
9932                        // The system apk may have been updated with an older
9933                        // version of the one on the data partition, but which
9934                        // granted a new system permission that it didn't have
9935                        // before.  In this case we do want to allow the app to
9936                        // now get the new permission if the ancestral apk is
9937                        // privileged to get it.
9938                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9939                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9940                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9941                                    allowed = true;
9942                                    break;
9943                                }
9944                            }
9945                        }
9946                        // Also if a privileged parent package on the system image or any of
9947                        // its children requested a privileged permission, the updated child
9948                        // packages can also get the permission.
9949                        if (pkg.parentPackage != null) {
9950                            final PackageSetting disabledSysParentPs = mSettings
9951                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9952                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9953                                    && disabledSysParentPs.isPrivileged()) {
9954                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9955                                    allowed = true;
9956                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9957                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9958                                    for (int i = 0; i < count; i++) {
9959                                        PackageParser.Package disabledSysChildPkg =
9960                                                disabledSysParentPs.pkg.childPackages.get(i);
9961                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9962                                                perm)) {
9963                                            allowed = true;
9964                                            break;
9965                                        }
9966                                    }
9967                                }
9968                            }
9969                        }
9970                    }
9971                } else {
9972                    allowed = isPrivilegedApp(pkg);
9973                }
9974            }
9975        }
9976        if (!allowed) {
9977            if (!allowed && (bp.protectionLevel
9978                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9979                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9980                // If this was a previously normal/dangerous permission that got moved
9981                // to a system permission as part of the runtime permission redesign, then
9982                // we still want to blindly grant it to old apps.
9983                allowed = true;
9984            }
9985            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9986                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9987                // If this permission is to be granted to the system installer and
9988                // this app is an installer, then it gets the permission.
9989                allowed = true;
9990            }
9991            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9992                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9993                // If this permission is to be granted to the system verifier and
9994                // this app is a verifier, then it gets the permission.
9995                allowed = true;
9996            }
9997            if (!allowed && (bp.protectionLevel
9998                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9999                    && isSystemApp(pkg)) {
10000                // Any pre-installed system app is allowed to get this permission.
10001                allowed = true;
10002            }
10003            if (!allowed && (bp.protectionLevel
10004                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10005                // For development permissions, a development permission
10006                // is granted only if it was already granted.
10007                allowed = origPermissions.hasInstallPermission(perm);
10008            }
10009            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10010                    && pkg.packageName.equals(mSetupWizardPackage)) {
10011                // If this permission is to be granted to the system setup wizard and
10012                // this app is a setup wizard, then it gets the permission.
10013                allowed = true;
10014            }
10015        }
10016        return allowed;
10017    }
10018
10019    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10020        final int permCount = pkg.requestedPermissions.size();
10021        for (int j = 0; j < permCount; j++) {
10022            String requestedPermission = pkg.requestedPermissions.get(j);
10023            if (permission.equals(requestedPermission)) {
10024                return true;
10025            }
10026        }
10027        return false;
10028    }
10029
10030    final class ActivityIntentResolver
10031            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10032        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10033                boolean defaultOnly, int userId) {
10034            if (!sUserManager.exists(userId)) return null;
10035            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10036            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10037        }
10038
10039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10040                int userId) {
10041            if (!sUserManager.exists(userId)) return null;
10042            mFlags = flags;
10043            return super.queryIntent(intent, resolvedType,
10044                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10045        }
10046
10047        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10048                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10049            if (!sUserManager.exists(userId)) return null;
10050            if (packageActivities == null) {
10051                return null;
10052            }
10053            mFlags = flags;
10054            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10055            final int N = packageActivities.size();
10056            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10057                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10058
10059            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10060            for (int i = 0; i < N; ++i) {
10061                intentFilters = packageActivities.get(i).intents;
10062                if (intentFilters != null && intentFilters.size() > 0) {
10063                    PackageParser.ActivityIntentInfo[] array =
10064                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10065                    intentFilters.toArray(array);
10066                    listCut.add(array);
10067                }
10068            }
10069            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10070        }
10071
10072        /**
10073         * Finds a privileged activity that matches the specified activity names.
10074         */
10075        private PackageParser.Activity findMatchingActivity(
10076                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10077            for (PackageParser.Activity sysActivity : activityList) {
10078                if (sysActivity.info.name.equals(activityInfo.name)) {
10079                    return sysActivity;
10080                }
10081                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10082                    return sysActivity;
10083                }
10084                if (sysActivity.info.targetActivity != null) {
10085                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10086                        return sysActivity;
10087                    }
10088                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10089                        return sysActivity;
10090                    }
10091                }
10092            }
10093            return null;
10094        }
10095
10096        public class IterGenerator<E> {
10097            public Iterator<E> generate(ActivityIntentInfo info) {
10098                return null;
10099            }
10100        }
10101
10102        public class ActionIterGenerator extends IterGenerator<String> {
10103            @Override
10104            public Iterator<String> generate(ActivityIntentInfo info) {
10105                return info.actionsIterator();
10106            }
10107        }
10108
10109        public class CategoriesIterGenerator extends IterGenerator<String> {
10110            @Override
10111            public Iterator<String> generate(ActivityIntentInfo info) {
10112                return info.categoriesIterator();
10113            }
10114        }
10115
10116        public class SchemesIterGenerator extends IterGenerator<String> {
10117            @Override
10118            public Iterator<String> generate(ActivityIntentInfo info) {
10119                return info.schemesIterator();
10120            }
10121        }
10122
10123        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10124            @Override
10125            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10126                return info.authoritiesIterator();
10127            }
10128        }
10129
10130        /**
10131         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10132         * MODIFIED. Do not pass in a list that should not be changed.
10133         */
10134        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10135                IterGenerator<T> generator, Iterator<T> searchIterator) {
10136            // loop through the set of actions; every one must be found in the intent filter
10137            while (searchIterator.hasNext()) {
10138                // we must have at least one filter in the list to consider a match
10139                if (intentList.size() == 0) {
10140                    break;
10141                }
10142
10143                final T searchAction = searchIterator.next();
10144
10145                // loop through the set of intent filters
10146                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10147                while (intentIter.hasNext()) {
10148                    final ActivityIntentInfo intentInfo = intentIter.next();
10149                    boolean selectionFound = false;
10150
10151                    // loop through the intent filter's selection criteria; at least one
10152                    // of them must match the searched criteria
10153                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10154                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10155                        final T intentSelection = intentSelectionIter.next();
10156                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10157                            selectionFound = true;
10158                            break;
10159                        }
10160                    }
10161
10162                    // the selection criteria wasn't found in this filter's set; this filter
10163                    // is not a potential match
10164                    if (!selectionFound) {
10165                        intentIter.remove();
10166                    }
10167                }
10168            }
10169        }
10170
10171        private boolean isProtectedAction(ActivityIntentInfo filter) {
10172            final Iterator<String> actionsIter = filter.actionsIterator();
10173            while (actionsIter != null && actionsIter.hasNext()) {
10174                final String filterAction = actionsIter.next();
10175                if (PROTECTED_ACTIONS.contains(filterAction)) {
10176                    return true;
10177                }
10178            }
10179            return false;
10180        }
10181
10182        /**
10183         * Adjusts the priority of the given intent filter according to policy.
10184         * <p>
10185         * <ul>
10186         * <li>The priority for non privileged applications is capped to '0'</li>
10187         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10188         * <li>The priority for unbundled updates to privileged applications is capped to the
10189         *      priority defined on the system partition</li>
10190         * </ul>
10191         * <p>
10192         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10193         * allowed to obtain any priority on any action.
10194         */
10195        private void adjustPriority(
10196                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10197            // nothing to do; priority is fine as-is
10198            if (intent.getPriority() <= 0) {
10199                return;
10200            }
10201
10202            final ActivityInfo activityInfo = intent.activity.info;
10203            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10204
10205            final boolean privilegedApp =
10206                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10207            if (!privilegedApp) {
10208                // non-privileged applications can never define a priority >0
10209                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10210                        + " package: " + applicationInfo.packageName
10211                        + " activity: " + intent.activity.className
10212                        + " origPrio: " + intent.getPriority());
10213                intent.setPriority(0);
10214                return;
10215            }
10216
10217            if (systemActivities == null) {
10218                // the system package is not disabled; we're parsing the system partition
10219                if (isProtectedAction(intent)) {
10220                    if (mDeferProtectedFilters) {
10221                        // We can't deal with these just yet. No component should ever obtain a
10222                        // >0 priority for a protected actions, with ONE exception -- the setup
10223                        // wizard. The setup wizard, however, cannot be known until we're able to
10224                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10225                        // until all intent filters have been processed. Chicken, meet egg.
10226                        // Let the filter temporarily have a high priority and rectify the
10227                        // priorities after all system packages have been scanned.
10228                        mProtectedFilters.add(intent);
10229                        if (DEBUG_FILTERS) {
10230                            Slog.i(TAG, "Protected action; save for later;"
10231                                    + " package: " + applicationInfo.packageName
10232                                    + " activity: " + intent.activity.className
10233                                    + " origPrio: " + intent.getPriority());
10234                        }
10235                        return;
10236                    } else {
10237                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10238                            Slog.i(TAG, "No setup wizard;"
10239                                + " All protected intents capped to priority 0");
10240                        }
10241                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10242                            if (DEBUG_FILTERS) {
10243                                Slog.i(TAG, "Found setup wizard;"
10244                                    + " allow priority " + intent.getPriority() + ";"
10245                                    + " package: " + intent.activity.info.packageName
10246                                    + " activity: " + intent.activity.className
10247                                    + " priority: " + intent.getPriority());
10248                            }
10249                            // setup wizard gets whatever it wants
10250                            return;
10251                        }
10252                        Slog.w(TAG, "Protected action; cap priority to 0;"
10253                                + " package: " + intent.activity.info.packageName
10254                                + " activity: " + intent.activity.className
10255                                + " origPrio: " + intent.getPriority());
10256                        intent.setPriority(0);
10257                        return;
10258                    }
10259                }
10260                // privileged apps on the system image get whatever priority they request
10261                return;
10262            }
10263
10264            // privileged app unbundled update ... try to find the same activity
10265            final PackageParser.Activity foundActivity =
10266                    findMatchingActivity(systemActivities, activityInfo);
10267            if (foundActivity == null) {
10268                // this is a new activity; it cannot obtain >0 priority
10269                if (DEBUG_FILTERS) {
10270                    Slog.i(TAG, "New activity; cap priority to 0;"
10271                            + " package: " + applicationInfo.packageName
10272                            + " activity: " + intent.activity.className
10273                            + " origPrio: " + intent.getPriority());
10274                }
10275                intent.setPriority(0);
10276                return;
10277            }
10278
10279            // found activity, now check for filter equivalence
10280
10281            // a shallow copy is enough; we modify the list, not its contents
10282            final List<ActivityIntentInfo> intentListCopy =
10283                    new ArrayList<>(foundActivity.intents);
10284            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10285
10286            // find matching action subsets
10287            final Iterator<String> actionsIterator = intent.actionsIterator();
10288            if (actionsIterator != null) {
10289                getIntentListSubset(
10290                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10291                if (intentListCopy.size() == 0) {
10292                    // no more intents to match; we're not equivalent
10293                    if (DEBUG_FILTERS) {
10294                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10295                                + " package: " + applicationInfo.packageName
10296                                + " activity: " + intent.activity.className
10297                                + " origPrio: " + intent.getPriority());
10298                    }
10299                    intent.setPriority(0);
10300                    return;
10301                }
10302            }
10303
10304            // find matching category subsets
10305            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10306            if (categoriesIterator != null) {
10307                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10308                        categoriesIterator);
10309                if (intentListCopy.size() == 0) {
10310                    // no more intents to match; we're not equivalent
10311                    if (DEBUG_FILTERS) {
10312                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10313                                + " package: " + applicationInfo.packageName
10314                                + " activity: " + intent.activity.className
10315                                + " origPrio: " + intent.getPriority());
10316                    }
10317                    intent.setPriority(0);
10318                    return;
10319                }
10320            }
10321
10322            // find matching schemes subsets
10323            final Iterator<String> schemesIterator = intent.schemesIterator();
10324            if (schemesIterator != null) {
10325                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10326                        schemesIterator);
10327                if (intentListCopy.size() == 0) {
10328                    // no more intents to match; we're not equivalent
10329                    if (DEBUG_FILTERS) {
10330                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10331                                + " package: " + applicationInfo.packageName
10332                                + " activity: " + intent.activity.className
10333                                + " origPrio: " + intent.getPriority());
10334                    }
10335                    intent.setPriority(0);
10336                    return;
10337                }
10338            }
10339
10340            // find matching authorities subsets
10341            final Iterator<IntentFilter.AuthorityEntry>
10342                    authoritiesIterator = intent.authoritiesIterator();
10343            if (authoritiesIterator != null) {
10344                getIntentListSubset(intentListCopy,
10345                        new AuthoritiesIterGenerator(),
10346                        authoritiesIterator);
10347                if (intentListCopy.size() == 0) {
10348                    // no more intents to match; we're not equivalent
10349                    if (DEBUG_FILTERS) {
10350                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10351                                + " package: " + applicationInfo.packageName
10352                                + " activity: " + intent.activity.className
10353                                + " origPrio: " + intent.getPriority());
10354                    }
10355                    intent.setPriority(0);
10356                    return;
10357                }
10358            }
10359
10360            // we found matching filter(s); app gets the max priority of all intents
10361            int cappedPriority = 0;
10362            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10363                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10364            }
10365            if (intent.getPriority() > cappedPriority) {
10366                if (DEBUG_FILTERS) {
10367                    Slog.i(TAG, "Found matching filter(s);"
10368                            + " cap priority to " + cappedPriority + ";"
10369                            + " package: " + applicationInfo.packageName
10370                            + " activity: " + intent.activity.className
10371                            + " origPrio: " + intent.getPriority());
10372                }
10373                intent.setPriority(cappedPriority);
10374                return;
10375            }
10376            // all this for nothing; the requested priority was <= what was on the system
10377        }
10378
10379        public final void addActivity(PackageParser.Activity a, String type) {
10380            mActivities.put(a.getComponentName(), a);
10381            if (DEBUG_SHOW_INFO)
10382                Log.v(
10383                TAG, "  " + type + " " +
10384                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10385            if (DEBUG_SHOW_INFO)
10386                Log.v(TAG, "    Class=" + a.info.name);
10387            final int NI = a.intents.size();
10388            for (int j=0; j<NI; j++) {
10389                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10390                if ("activity".equals(type)) {
10391                    final PackageSetting ps =
10392                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10393                    final List<PackageParser.Activity> systemActivities =
10394                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10395                    adjustPriority(systemActivities, intent);
10396                }
10397                if (DEBUG_SHOW_INFO) {
10398                    Log.v(TAG, "    IntentFilter:");
10399                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10400                }
10401                if (!intent.debugCheck()) {
10402                    Log.w(TAG, "==> For Activity " + a.info.name);
10403                }
10404                addFilter(intent);
10405            }
10406        }
10407
10408        public final void removeActivity(PackageParser.Activity a, String type) {
10409            mActivities.remove(a.getComponentName());
10410            if (DEBUG_SHOW_INFO) {
10411                Log.v(TAG, "  " + type + " "
10412                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10413                                : a.info.name) + ":");
10414                Log.v(TAG, "    Class=" + a.info.name);
10415            }
10416            final int NI = a.intents.size();
10417            for (int j=0; j<NI; j++) {
10418                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10419                if (DEBUG_SHOW_INFO) {
10420                    Log.v(TAG, "    IntentFilter:");
10421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10422                }
10423                removeFilter(intent);
10424            }
10425        }
10426
10427        @Override
10428        protected boolean allowFilterResult(
10429                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10430            ActivityInfo filterAi = filter.activity.info;
10431            for (int i=dest.size()-1; i>=0; i--) {
10432                ActivityInfo destAi = dest.get(i).activityInfo;
10433                if (destAi.name == filterAi.name
10434                        && destAi.packageName == filterAi.packageName) {
10435                    return false;
10436                }
10437            }
10438            return true;
10439        }
10440
10441        @Override
10442        protected ActivityIntentInfo[] newArray(int size) {
10443            return new ActivityIntentInfo[size];
10444        }
10445
10446        @Override
10447        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10448            if (!sUserManager.exists(userId)) return true;
10449            PackageParser.Package p = filter.activity.owner;
10450            if (p != null) {
10451                PackageSetting ps = (PackageSetting)p.mExtras;
10452                if (ps != null) {
10453                    // System apps are never considered stopped for purposes of
10454                    // filtering, because there may be no way for the user to
10455                    // actually re-launch them.
10456                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10457                            && ps.getStopped(userId);
10458                }
10459            }
10460            return false;
10461        }
10462
10463        @Override
10464        protected boolean isPackageForFilter(String packageName,
10465                PackageParser.ActivityIntentInfo info) {
10466            return packageName.equals(info.activity.owner.packageName);
10467        }
10468
10469        @Override
10470        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10471                int match, int userId) {
10472            if (!sUserManager.exists(userId)) return null;
10473            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10474                return null;
10475            }
10476            final PackageParser.Activity activity = info.activity;
10477            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10478            if (ps == null) {
10479                return null;
10480            }
10481            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10482                    ps.readUserState(userId), userId);
10483            if (ai == null) {
10484                return null;
10485            }
10486            final ResolveInfo res = new ResolveInfo();
10487            res.activityInfo = ai;
10488            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10489                res.filter = info;
10490            }
10491            if (info != null) {
10492                res.handleAllWebDataURI = info.handleAllWebDataURI();
10493            }
10494            res.priority = info.getPriority();
10495            res.preferredOrder = activity.owner.mPreferredOrder;
10496            //System.out.println("Result: " + res.activityInfo.className +
10497            //                   " = " + res.priority);
10498            res.match = match;
10499            res.isDefault = info.hasDefault;
10500            res.labelRes = info.labelRes;
10501            res.nonLocalizedLabel = info.nonLocalizedLabel;
10502            if (userNeedsBadging(userId)) {
10503                res.noResourceId = true;
10504            } else {
10505                res.icon = info.icon;
10506            }
10507            res.iconResourceId = info.icon;
10508            res.system = res.activityInfo.applicationInfo.isSystemApp();
10509            return res;
10510        }
10511
10512        @Override
10513        protected void sortResults(List<ResolveInfo> results) {
10514            Collections.sort(results, mResolvePrioritySorter);
10515        }
10516
10517        @Override
10518        protected void dumpFilter(PrintWriter out, String prefix,
10519                PackageParser.ActivityIntentInfo filter) {
10520            out.print(prefix); out.print(
10521                    Integer.toHexString(System.identityHashCode(filter.activity)));
10522                    out.print(' ');
10523                    filter.activity.printComponentShortName(out);
10524                    out.print(" filter ");
10525                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10526        }
10527
10528        @Override
10529        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10530            return filter.activity;
10531        }
10532
10533        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10534            PackageParser.Activity activity = (PackageParser.Activity)label;
10535            out.print(prefix); out.print(
10536                    Integer.toHexString(System.identityHashCode(activity)));
10537                    out.print(' ');
10538                    activity.printComponentShortName(out);
10539            if (count > 1) {
10540                out.print(" ("); out.print(count); out.print(" filters)");
10541            }
10542            out.println();
10543        }
10544
10545        // Keys are String (activity class name), values are Activity.
10546        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10547                = new ArrayMap<ComponentName, PackageParser.Activity>();
10548        private int mFlags;
10549    }
10550
10551    private final class ServiceIntentResolver
10552            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10553        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10554                boolean defaultOnly, int userId) {
10555            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10556            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10557        }
10558
10559        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10560                int userId) {
10561            if (!sUserManager.exists(userId)) return null;
10562            mFlags = flags;
10563            return super.queryIntent(intent, resolvedType,
10564                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10565        }
10566
10567        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10568                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10569            if (!sUserManager.exists(userId)) return null;
10570            if (packageServices == null) {
10571                return null;
10572            }
10573            mFlags = flags;
10574            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10575            final int N = packageServices.size();
10576            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10577                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10578
10579            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10580            for (int i = 0; i < N; ++i) {
10581                intentFilters = packageServices.get(i).intents;
10582                if (intentFilters != null && intentFilters.size() > 0) {
10583                    PackageParser.ServiceIntentInfo[] array =
10584                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10585                    intentFilters.toArray(array);
10586                    listCut.add(array);
10587                }
10588            }
10589            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10590        }
10591
10592        public final void addService(PackageParser.Service s) {
10593            mServices.put(s.getComponentName(), s);
10594            if (DEBUG_SHOW_INFO) {
10595                Log.v(TAG, "  "
10596                        + (s.info.nonLocalizedLabel != null
10597                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10598                Log.v(TAG, "    Class=" + s.info.name);
10599            }
10600            final int NI = s.intents.size();
10601            int j;
10602            for (j=0; j<NI; j++) {
10603                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10604                if (DEBUG_SHOW_INFO) {
10605                    Log.v(TAG, "    IntentFilter:");
10606                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10607                }
10608                if (!intent.debugCheck()) {
10609                    Log.w(TAG, "==> For Service " + s.info.name);
10610                }
10611                addFilter(intent);
10612            }
10613        }
10614
10615        public final void removeService(PackageParser.Service s) {
10616            mServices.remove(s.getComponentName());
10617            if (DEBUG_SHOW_INFO) {
10618                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10619                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10620                Log.v(TAG, "    Class=" + s.info.name);
10621            }
10622            final int NI = s.intents.size();
10623            int j;
10624            for (j=0; j<NI; j++) {
10625                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10626                if (DEBUG_SHOW_INFO) {
10627                    Log.v(TAG, "    IntentFilter:");
10628                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10629                }
10630                removeFilter(intent);
10631            }
10632        }
10633
10634        @Override
10635        protected boolean allowFilterResult(
10636                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10637            ServiceInfo filterSi = filter.service.info;
10638            for (int i=dest.size()-1; i>=0; i--) {
10639                ServiceInfo destAi = dest.get(i).serviceInfo;
10640                if (destAi.name == filterSi.name
10641                        && destAi.packageName == filterSi.packageName) {
10642                    return false;
10643                }
10644            }
10645            return true;
10646        }
10647
10648        @Override
10649        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10650            return new PackageParser.ServiceIntentInfo[size];
10651        }
10652
10653        @Override
10654        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10655            if (!sUserManager.exists(userId)) return true;
10656            PackageParser.Package p = filter.service.owner;
10657            if (p != null) {
10658                PackageSetting ps = (PackageSetting)p.mExtras;
10659                if (ps != null) {
10660                    // System apps are never considered stopped for purposes of
10661                    // filtering, because there may be no way for the user to
10662                    // actually re-launch them.
10663                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10664                            && ps.getStopped(userId);
10665                }
10666            }
10667            return false;
10668        }
10669
10670        @Override
10671        protected boolean isPackageForFilter(String packageName,
10672                PackageParser.ServiceIntentInfo info) {
10673            return packageName.equals(info.service.owner.packageName);
10674        }
10675
10676        @Override
10677        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10678                int match, int userId) {
10679            if (!sUserManager.exists(userId)) return null;
10680            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10681            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10682                return null;
10683            }
10684            final PackageParser.Service service = info.service;
10685            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10686            if (ps == null) {
10687                return null;
10688            }
10689            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10690                    ps.readUserState(userId), userId);
10691            if (si == null) {
10692                return null;
10693            }
10694            final ResolveInfo res = new ResolveInfo();
10695            res.serviceInfo = si;
10696            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10697                res.filter = filter;
10698            }
10699            res.priority = info.getPriority();
10700            res.preferredOrder = service.owner.mPreferredOrder;
10701            res.match = match;
10702            res.isDefault = info.hasDefault;
10703            res.labelRes = info.labelRes;
10704            res.nonLocalizedLabel = info.nonLocalizedLabel;
10705            res.icon = info.icon;
10706            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10707            return res;
10708        }
10709
10710        @Override
10711        protected void sortResults(List<ResolveInfo> results) {
10712            Collections.sort(results, mResolvePrioritySorter);
10713        }
10714
10715        @Override
10716        protected void dumpFilter(PrintWriter out, String prefix,
10717                PackageParser.ServiceIntentInfo filter) {
10718            out.print(prefix); out.print(
10719                    Integer.toHexString(System.identityHashCode(filter.service)));
10720                    out.print(' ');
10721                    filter.service.printComponentShortName(out);
10722                    out.print(" filter ");
10723                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10724        }
10725
10726        @Override
10727        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10728            return filter.service;
10729        }
10730
10731        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10732            PackageParser.Service service = (PackageParser.Service)label;
10733            out.print(prefix); out.print(
10734                    Integer.toHexString(System.identityHashCode(service)));
10735                    out.print(' ');
10736                    service.printComponentShortName(out);
10737            if (count > 1) {
10738                out.print(" ("); out.print(count); out.print(" filters)");
10739            }
10740            out.println();
10741        }
10742
10743//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10744//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10745//            final List<ResolveInfo> retList = Lists.newArrayList();
10746//            while (i.hasNext()) {
10747//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10748//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10749//                    retList.add(resolveInfo);
10750//                }
10751//            }
10752//            return retList;
10753//        }
10754
10755        // Keys are String (activity class name), values are Activity.
10756        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10757                = new ArrayMap<ComponentName, PackageParser.Service>();
10758        private int mFlags;
10759    };
10760
10761    private final class ProviderIntentResolver
10762            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10764                boolean defaultOnly, int userId) {
10765            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10766            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10767        }
10768
10769        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10770                int userId) {
10771            if (!sUserManager.exists(userId))
10772                return null;
10773            mFlags = flags;
10774            return super.queryIntent(intent, resolvedType,
10775                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10776        }
10777
10778        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10779                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10780            if (!sUserManager.exists(userId))
10781                return null;
10782            if (packageProviders == null) {
10783                return null;
10784            }
10785            mFlags = flags;
10786            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10787            final int N = packageProviders.size();
10788            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10789                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10790
10791            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10792            for (int i = 0; i < N; ++i) {
10793                intentFilters = packageProviders.get(i).intents;
10794                if (intentFilters != null && intentFilters.size() > 0) {
10795                    PackageParser.ProviderIntentInfo[] array =
10796                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10797                    intentFilters.toArray(array);
10798                    listCut.add(array);
10799                }
10800            }
10801            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10802        }
10803
10804        public final void addProvider(PackageParser.Provider p) {
10805            if (mProviders.containsKey(p.getComponentName())) {
10806                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10807                return;
10808            }
10809
10810            mProviders.put(p.getComponentName(), p);
10811            if (DEBUG_SHOW_INFO) {
10812                Log.v(TAG, "  "
10813                        + (p.info.nonLocalizedLabel != null
10814                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10815                Log.v(TAG, "    Class=" + p.info.name);
10816            }
10817            final int NI = p.intents.size();
10818            int j;
10819            for (j = 0; j < NI; j++) {
10820                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10821                if (DEBUG_SHOW_INFO) {
10822                    Log.v(TAG, "    IntentFilter:");
10823                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10824                }
10825                if (!intent.debugCheck()) {
10826                    Log.w(TAG, "==> For Provider " + p.info.name);
10827                }
10828                addFilter(intent);
10829            }
10830        }
10831
10832        public final void removeProvider(PackageParser.Provider p) {
10833            mProviders.remove(p.getComponentName());
10834            if (DEBUG_SHOW_INFO) {
10835                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10836                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10837                Log.v(TAG, "    Class=" + p.info.name);
10838            }
10839            final int NI = p.intents.size();
10840            int j;
10841            for (j = 0; j < NI; j++) {
10842                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10843                if (DEBUG_SHOW_INFO) {
10844                    Log.v(TAG, "    IntentFilter:");
10845                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10846                }
10847                removeFilter(intent);
10848            }
10849        }
10850
10851        @Override
10852        protected boolean allowFilterResult(
10853                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10854            ProviderInfo filterPi = filter.provider.info;
10855            for (int i = dest.size() - 1; i >= 0; i--) {
10856                ProviderInfo destPi = dest.get(i).providerInfo;
10857                if (destPi.name == filterPi.name
10858                        && destPi.packageName == filterPi.packageName) {
10859                    return false;
10860                }
10861            }
10862            return true;
10863        }
10864
10865        @Override
10866        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10867            return new PackageParser.ProviderIntentInfo[size];
10868        }
10869
10870        @Override
10871        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10872            if (!sUserManager.exists(userId))
10873                return true;
10874            PackageParser.Package p = filter.provider.owner;
10875            if (p != null) {
10876                PackageSetting ps = (PackageSetting) p.mExtras;
10877                if (ps != null) {
10878                    // System apps are never considered stopped for purposes of
10879                    // filtering, because there may be no way for the user to
10880                    // actually re-launch them.
10881                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10882                            && ps.getStopped(userId);
10883                }
10884            }
10885            return false;
10886        }
10887
10888        @Override
10889        protected boolean isPackageForFilter(String packageName,
10890                PackageParser.ProviderIntentInfo info) {
10891            return packageName.equals(info.provider.owner.packageName);
10892        }
10893
10894        @Override
10895        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10896                int match, int userId) {
10897            if (!sUserManager.exists(userId))
10898                return null;
10899            final PackageParser.ProviderIntentInfo info = filter;
10900            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10901                return null;
10902            }
10903            final PackageParser.Provider provider = info.provider;
10904            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10905            if (ps == null) {
10906                return null;
10907            }
10908            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10909                    ps.readUserState(userId), userId);
10910            if (pi == null) {
10911                return null;
10912            }
10913            final ResolveInfo res = new ResolveInfo();
10914            res.providerInfo = pi;
10915            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10916                res.filter = filter;
10917            }
10918            res.priority = info.getPriority();
10919            res.preferredOrder = provider.owner.mPreferredOrder;
10920            res.match = match;
10921            res.isDefault = info.hasDefault;
10922            res.labelRes = info.labelRes;
10923            res.nonLocalizedLabel = info.nonLocalizedLabel;
10924            res.icon = info.icon;
10925            res.system = res.providerInfo.applicationInfo.isSystemApp();
10926            return res;
10927        }
10928
10929        @Override
10930        protected void sortResults(List<ResolveInfo> results) {
10931            Collections.sort(results, mResolvePrioritySorter);
10932        }
10933
10934        @Override
10935        protected void dumpFilter(PrintWriter out, String prefix,
10936                PackageParser.ProviderIntentInfo filter) {
10937            out.print(prefix);
10938            out.print(
10939                    Integer.toHexString(System.identityHashCode(filter.provider)));
10940            out.print(' ');
10941            filter.provider.printComponentShortName(out);
10942            out.print(" filter ");
10943            out.println(Integer.toHexString(System.identityHashCode(filter)));
10944        }
10945
10946        @Override
10947        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10948            return filter.provider;
10949        }
10950
10951        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10952            PackageParser.Provider provider = (PackageParser.Provider)label;
10953            out.print(prefix); out.print(
10954                    Integer.toHexString(System.identityHashCode(provider)));
10955                    out.print(' ');
10956                    provider.printComponentShortName(out);
10957            if (count > 1) {
10958                out.print(" ("); out.print(count); out.print(" filters)");
10959            }
10960            out.println();
10961        }
10962
10963        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10964                = new ArrayMap<ComponentName, PackageParser.Provider>();
10965        private int mFlags;
10966    }
10967
10968    private static final class EphemeralIntentResolver
10969            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10970        @Override
10971        protected EphemeralResolveIntentInfo[] newArray(int size) {
10972            return new EphemeralResolveIntentInfo[size];
10973        }
10974
10975        @Override
10976        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10977            return true;
10978        }
10979
10980        @Override
10981        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10982                int userId) {
10983            if (!sUserManager.exists(userId)) {
10984                return null;
10985            }
10986            return info.getEphemeralResolveInfo();
10987        }
10988    }
10989
10990    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10991            new Comparator<ResolveInfo>() {
10992        public int compare(ResolveInfo r1, ResolveInfo r2) {
10993            int v1 = r1.priority;
10994            int v2 = r2.priority;
10995            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10996            if (v1 != v2) {
10997                return (v1 > v2) ? -1 : 1;
10998            }
10999            v1 = r1.preferredOrder;
11000            v2 = r2.preferredOrder;
11001            if (v1 != v2) {
11002                return (v1 > v2) ? -1 : 1;
11003            }
11004            if (r1.isDefault != r2.isDefault) {
11005                return r1.isDefault ? -1 : 1;
11006            }
11007            v1 = r1.match;
11008            v2 = r2.match;
11009            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11010            if (v1 != v2) {
11011                return (v1 > v2) ? -1 : 1;
11012            }
11013            if (r1.system != r2.system) {
11014                return r1.system ? -1 : 1;
11015            }
11016            if (r1.activityInfo != null) {
11017                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11018            }
11019            if (r1.serviceInfo != null) {
11020                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11021            }
11022            if (r1.providerInfo != null) {
11023                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11024            }
11025            return 0;
11026        }
11027    };
11028
11029    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11030            new Comparator<ProviderInfo>() {
11031        public int compare(ProviderInfo p1, ProviderInfo p2) {
11032            final int v1 = p1.initOrder;
11033            final int v2 = p2.initOrder;
11034            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11035        }
11036    };
11037
11038    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11039            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11040            final int[] userIds) {
11041        mHandler.post(new Runnable() {
11042            @Override
11043            public void run() {
11044                try {
11045                    final IActivityManager am = ActivityManagerNative.getDefault();
11046                    if (am == null) return;
11047                    final int[] resolvedUserIds;
11048                    if (userIds == null) {
11049                        resolvedUserIds = am.getRunningUserIds();
11050                    } else {
11051                        resolvedUserIds = userIds;
11052                    }
11053                    for (int id : resolvedUserIds) {
11054                        final Intent intent = new Intent(action,
11055                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11056                        if (extras != null) {
11057                            intent.putExtras(extras);
11058                        }
11059                        if (targetPkg != null) {
11060                            intent.setPackage(targetPkg);
11061                        }
11062                        // Modify the UID when posting to other users
11063                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11064                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11065                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11066                            intent.putExtra(Intent.EXTRA_UID, uid);
11067                        }
11068                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11069                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11070                        if (DEBUG_BROADCASTS) {
11071                            RuntimeException here = new RuntimeException("here");
11072                            here.fillInStackTrace();
11073                            Slog.d(TAG, "Sending to user " + id + ": "
11074                                    + intent.toShortString(false, true, false, false)
11075                                    + " " + intent.getExtras(), here);
11076                        }
11077                        am.broadcastIntent(null, intent, null, finishedReceiver,
11078                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11079                                null, finishedReceiver != null, false, id);
11080                    }
11081                } catch (RemoteException ex) {
11082                }
11083            }
11084        });
11085    }
11086
11087    /**
11088     * Check if the external storage media is available. This is true if there
11089     * is a mounted external storage medium or if the external storage is
11090     * emulated.
11091     */
11092    private boolean isExternalMediaAvailable() {
11093        return mMediaMounted || Environment.isExternalStorageEmulated();
11094    }
11095
11096    @Override
11097    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11098        // writer
11099        synchronized (mPackages) {
11100            if (!isExternalMediaAvailable()) {
11101                // If the external storage is no longer mounted at this point,
11102                // the caller may not have been able to delete all of this
11103                // packages files and can not delete any more.  Bail.
11104                return null;
11105            }
11106            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11107            if (lastPackage != null) {
11108                pkgs.remove(lastPackage);
11109            }
11110            if (pkgs.size() > 0) {
11111                return pkgs.get(0);
11112            }
11113        }
11114        return null;
11115    }
11116
11117    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11118        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11119                userId, andCode ? 1 : 0, packageName);
11120        if (mSystemReady) {
11121            msg.sendToTarget();
11122        } else {
11123            if (mPostSystemReadyMessages == null) {
11124                mPostSystemReadyMessages = new ArrayList<>();
11125            }
11126            mPostSystemReadyMessages.add(msg);
11127        }
11128    }
11129
11130    void startCleaningPackages() {
11131        // reader
11132        if (!isExternalMediaAvailable()) {
11133            return;
11134        }
11135        synchronized (mPackages) {
11136            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11137                return;
11138            }
11139        }
11140        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11141        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11142        IActivityManager am = ActivityManagerNative.getDefault();
11143        if (am != null) {
11144            try {
11145                am.startService(null, intent, null, mContext.getOpPackageName(),
11146                        UserHandle.USER_SYSTEM);
11147            } catch (RemoteException e) {
11148            }
11149        }
11150    }
11151
11152    @Override
11153    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11154            int installFlags, String installerPackageName, int userId) {
11155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11156
11157        final int callingUid = Binder.getCallingUid();
11158        enforceCrossUserPermission(callingUid, userId,
11159                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11160
11161        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11162            try {
11163                if (observer != null) {
11164                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11165                }
11166            } catch (RemoteException re) {
11167            }
11168            return;
11169        }
11170
11171        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11172            installFlags |= PackageManager.INSTALL_FROM_ADB;
11173
11174        } else {
11175            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11176            // about installerPackageName.
11177
11178            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11179            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11180        }
11181
11182        UserHandle user;
11183        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11184            user = UserHandle.ALL;
11185        } else {
11186            user = new UserHandle(userId);
11187        }
11188
11189        // Only system components can circumvent runtime permissions when installing.
11190        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11191                && mContext.checkCallingOrSelfPermission(Manifest.permission
11192                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11193            throw new SecurityException("You need the "
11194                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11195                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11196        }
11197
11198        final File originFile = new File(originPath);
11199        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11200
11201        final Message msg = mHandler.obtainMessage(INIT_COPY);
11202        final VerificationInfo verificationInfo = new VerificationInfo(
11203                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11204        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11205                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11206                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11207                null /*certificates*/);
11208        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11209        msg.obj = params;
11210
11211        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11212                System.identityHashCode(msg.obj));
11213        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11214                System.identityHashCode(msg.obj));
11215
11216        mHandler.sendMessage(msg);
11217    }
11218
11219    void installStage(String packageName, File stagedDir, String stagedCid,
11220            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11221            String installerPackageName, int installerUid, UserHandle user,
11222            Certificate[][] certificates) {
11223        if (DEBUG_EPHEMERAL) {
11224            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11225                Slog.d(TAG, "Ephemeral install of " + packageName);
11226            }
11227        }
11228        final VerificationInfo verificationInfo = new VerificationInfo(
11229                sessionParams.originatingUri, sessionParams.referrerUri,
11230                sessionParams.originatingUid, installerUid);
11231
11232        final OriginInfo origin;
11233        if (stagedDir != null) {
11234            origin = OriginInfo.fromStagedFile(stagedDir);
11235        } else {
11236            origin = OriginInfo.fromStagedContainer(stagedCid);
11237        }
11238
11239        final Message msg = mHandler.obtainMessage(INIT_COPY);
11240        final InstallParams params = new InstallParams(origin, null, observer,
11241                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11242                verificationInfo, user, sessionParams.abiOverride,
11243                sessionParams.grantedRuntimePermissions, certificates);
11244        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11245        msg.obj = params;
11246
11247        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11248                System.identityHashCode(msg.obj));
11249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11250                System.identityHashCode(msg.obj));
11251
11252        mHandler.sendMessage(msg);
11253    }
11254
11255    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11256            int userId) {
11257        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11258        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11259    }
11260
11261    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11262            int appId, int userId) {
11263        Bundle extras = new Bundle(1);
11264        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11265
11266        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11267                packageName, extras, 0, null, null, new int[] {userId});
11268        try {
11269            IActivityManager am = ActivityManagerNative.getDefault();
11270            if (isSystem && am.isUserRunning(userId, 0)) {
11271                // The just-installed/enabled app is bundled on the system, so presumed
11272                // to be able to run automatically without needing an explicit launch.
11273                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11274                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11275                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11276                        .setPackage(packageName);
11277                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11278                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11279            }
11280        } catch (RemoteException e) {
11281            // shouldn't happen
11282            Slog.w(TAG, "Unable to bootstrap installed package", e);
11283        }
11284    }
11285
11286    @Override
11287    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11288            int userId) {
11289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11290        PackageSetting pkgSetting;
11291        final int uid = Binder.getCallingUid();
11292        enforceCrossUserPermission(uid, userId,
11293                true /* requireFullPermission */, true /* checkShell */,
11294                "setApplicationHiddenSetting for user " + userId);
11295
11296        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11297            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11298            return false;
11299        }
11300
11301        long callingId = Binder.clearCallingIdentity();
11302        try {
11303            boolean sendAdded = false;
11304            boolean sendRemoved = false;
11305            // writer
11306            synchronized (mPackages) {
11307                pkgSetting = mSettings.mPackages.get(packageName);
11308                if (pkgSetting == null) {
11309                    return false;
11310                }
11311                if (pkgSetting.getHidden(userId) != hidden) {
11312                    pkgSetting.setHidden(hidden, userId);
11313                    mSettings.writePackageRestrictionsLPr(userId);
11314                    if (hidden) {
11315                        sendRemoved = true;
11316                    } else {
11317                        sendAdded = true;
11318                    }
11319                }
11320            }
11321            if (sendAdded) {
11322                sendPackageAddedForUser(packageName, pkgSetting, userId);
11323                return true;
11324            }
11325            if (sendRemoved) {
11326                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11327                        "hiding pkg");
11328                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11329                return true;
11330            }
11331        } finally {
11332            Binder.restoreCallingIdentity(callingId);
11333        }
11334        return false;
11335    }
11336
11337    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11338            int userId) {
11339        final PackageRemovedInfo info = new PackageRemovedInfo();
11340        info.removedPackage = packageName;
11341        info.removedUsers = new int[] {userId};
11342        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11343        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11344    }
11345
11346    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11347        if (pkgList.length > 0) {
11348            Bundle extras = new Bundle(1);
11349            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11350
11351            sendPackageBroadcast(
11352                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11353                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11354                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11355                    new int[] {userId});
11356        }
11357    }
11358
11359    /**
11360     * Returns true if application is not found or there was an error. Otherwise it returns
11361     * the hidden state of the package for the given user.
11362     */
11363    @Override
11364    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11365        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11366        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11367                true /* requireFullPermission */, false /* checkShell */,
11368                "getApplicationHidden for user " + userId);
11369        PackageSetting pkgSetting;
11370        long callingId = Binder.clearCallingIdentity();
11371        try {
11372            // writer
11373            synchronized (mPackages) {
11374                pkgSetting = mSettings.mPackages.get(packageName);
11375                if (pkgSetting == null) {
11376                    return true;
11377                }
11378                return pkgSetting.getHidden(userId);
11379            }
11380        } finally {
11381            Binder.restoreCallingIdentity(callingId);
11382        }
11383    }
11384
11385    /**
11386     * @hide
11387     */
11388    @Override
11389    public int installExistingPackageAsUser(String packageName, int userId) {
11390        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11391                null);
11392        PackageSetting pkgSetting;
11393        final int uid = Binder.getCallingUid();
11394        enforceCrossUserPermission(uid, userId,
11395                true /* requireFullPermission */, true /* checkShell */,
11396                "installExistingPackage for user " + userId);
11397        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11398            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11399        }
11400
11401        long callingId = Binder.clearCallingIdentity();
11402        try {
11403            boolean installed = false;
11404
11405            // writer
11406            synchronized (mPackages) {
11407                pkgSetting = mSettings.mPackages.get(packageName);
11408                if (pkgSetting == null) {
11409                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11410                }
11411                if (!pkgSetting.getInstalled(userId)) {
11412                    pkgSetting.setInstalled(true, userId);
11413                    pkgSetting.setHidden(false, userId);
11414                    mSettings.writePackageRestrictionsLPr(userId);
11415                    installed = true;
11416                }
11417            }
11418
11419            if (installed) {
11420                if (pkgSetting.pkg != null) {
11421                    synchronized (mInstallLock) {
11422                        // We don't need to freeze for a brand new install
11423                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11424                    }
11425                }
11426                sendPackageAddedForUser(packageName, pkgSetting, userId);
11427            }
11428        } finally {
11429            Binder.restoreCallingIdentity(callingId);
11430        }
11431
11432        return PackageManager.INSTALL_SUCCEEDED;
11433    }
11434
11435    boolean isUserRestricted(int userId, String restrictionKey) {
11436        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11437        if (restrictions.getBoolean(restrictionKey, false)) {
11438            Log.w(TAG, "User is restricted: " + restrictionKey);
11439            return true;
11440        }
11441        return false;
11442    }
11443
11444    @Override
11445    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11446            int userId) {
11447        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11449                true /* requireFullPermission */, true /* checkShell */,
11450                "setPackagesSuspended for user " + userId);
11451
11452        if (ArrayUtils.isEmpty(packageNames)) {
11453            return packageNames;
11454        }
11455
11456        // List of package names for whom the suspended state has changed.
11457        List<String> changedPackages = new ArrayList<>(packageNames.length);
11458        // List of package names for whom the suspended state is not set as requested in this
11459        // method.
11460        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11461        for (int i = 0; i < packageNames.length; i++) {
11462            String packageName = packageNames[i];
11463            long callingId = Binder.clearCallingIdentity();
11464            try {
11465                boolean changed = false;
11466                final int appId;
11467                synchronized (mPackages) {
11468                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11469                    if (pkgSetting == null) {
11470                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11471                                + "\". Skipping suspending/un-suspending.");
11472                        unactionedPackages.add(packageName);
11473                        continue;
11474                    }
11475                    appId = pkgSetting.appId;
11476                    if (pkgSetting.getSuspended(userId) != suspended) {
11477                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11478                            unactionedPackages.add(packageName);
11479                            continue;
11480                        }
11481                        pkgSetting.setSuspended(suspended, userId);
11482                        mSettings.writePackageRestrictionsLPr(userId);
11483                        changed = true;
11484                        changedPackages.add(packageName);
11485                    }
11486                }
11487
11488                if (changed && suspended) {
11489                    killApplication(packageName, UserHandle.getUid(userId, appId),
11490                            "suspending package");
11491                }
11492            } finally {
11493                Binder.restoreCallingIdentity(callingId);
11494            }
11495        }
11496
11497        if (!changedPackages.isEmpty()) {
11498            sendPackagesSuspendedForUser(changedPackages.toArray(
11499                    new String[changedPackages.size()]), userId, suspended);
11500        }
11501
11502        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11503    }
11504
11505    @Override
11506    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11507        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11508                true /* requireFullPermission */, false /* checkShell */,
11509                "isPackageSuspendedForUser for user " + userId);
11510        synchronized (mPackages) {
11511            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11512            if (pkgSetting == null) {
11513                throw new IllegalArgumentException("Unknown target package: " + packageName);
11514            }
11515            return pkgSetting.getSuspended(userId);
11516        }
11517    }
11518
11519    /**
11520     * TODO: cache and disallow blocking the active dialer.
11521     *
11522     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11523     */
11524    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11525        if (isPackageDeviceAdmin(packageName, userId)) {
11526            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11527                    + "\": has an active device admin");
11528            return false;
11529        }
11530
11531        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11532        if (packageName.equals(activeLauncherPackageName)) {
11533            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11534                    + "\": contains the active launcher");
11535            return false;
11536        }
11537
11538        if (packageName.equals(mRequiredInstallerPackage)) {
11539            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11540                    + "\": required for package installation");
11541            return false;
11542        }
11543
11544        if (packageName.equals(mRequiredVerifierPackage)) {
11545            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11546                    + "\": required for package verification");
11547            return false;
11548        }
11549
11550        final PackageParser.Package pkg = mPackages.get(packageName);
11551        if (pkg != null && isPrivilegedApp(pkg)) {
11552            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11553                    + "\": is a privileged app");
11554            return false;
11555        }
11556
11557        return true;
11558    }
11559
11560    private String getActiveLauncherPackageName(int userId) {
11561        Intent intent = new Intent(Intent.ACTION_MAIN);
11562        intent.addCategory(Intent.CATEGORY_HOME);
11563        ResolveInfo resolveInfo = resolveIntent(
11564                intent,
11565                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11566                PackageManager.MATCH_DEFAULT_ONLY,
11567                userId);
11568
11569        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11570    }
11571
11572    @Override
11573    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11574        mContext.enforceCallingOrSelfPermission(
11575                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11576                "Only package verification agents can verify applications");
11577
11578        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11579        final PackageVerificationResponse response = new PackageVerificationResponse(
11580                verificationCode, Binder.getCallingUid());
11581        msg.arg1 = id;
11582        msg.obj = response;
11583        mHandler.sendMessage(msg);
11584    }
11585
11586    @Override
11587    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11588            long millisecondsToDelay) {
11589        mContext.enforceCallingOrSelfPermission(
11590                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11591                "Only package verification agents can extend verification timeouts");
11592
11593        final PackageVerificationState state = mPendingVerification.get(id);
11594        final PackageVerificationResponse response = new PackageVerificationResponse(
11595                verificationCodeAtTimeout, Binder.getCallingUid());
11596
11597        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11598            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11599        }
11600        if (millisecondsToDelay < 0) {
11601            millisecondsToDelay = 0;
11602        }
11603        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11604                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11605            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11606        }
11607
11608        if ((state != null) && !state.timeoutExtended()) {
11609            state.extendTimeout();
11610
11611            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11612            msg.arg1 = id;
11613            msg.obj = response;
11614            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11615        }
11616    }
11617
11618    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11619            int verificationCode, UserHandle user) {
11620        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11621        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11622        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11623        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11624        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11625
11626        mContext.sendBroadcastAsUser(intent, user,
11627                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11628    }
11629
11630    private ComponentName matchComponentForVerifier(String packageName,
11631            List<ResolveInfo> receivers) {
11632        ActivityInfo targetReceiver = null;
11633
11634        final int NR = receivers.size();
11635        for (int i = 0; i < NR; i++) {
11636            final ResolveInfo info = receivers.get(i);
11637            if (info.activityInfo == null) {
11638                continue;
11639            }
11640
11641            if (packageName.equals(info.activityInfo.packageName)) {
11642                targetReceiver = info.activityInfo;
11643                break;
11644            }
11645        }
11646
11647        if (targetReceiver == null) {
11648            return null;
11649        }
11650
11651        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11652    }
11653
11654    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11655            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11656        if (pkgInfo.verifiers.length == 0) {
11657            return null;
11658        }
11659
11660        final int N = pkgInfo.verifiers.length;
11661        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11662        for (int i = 0; i < N; i++) {
11663            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11664
11665            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11666                    receivers);
11667            if (comp == null) {
11668                continue;
11669            }
11670
11671            final int verifierUid = getUidForVerifier(verifierInfo);
11672            if (verifierUid == -1) {
11673                continue;
11674            }
11675
11676            if (DEBUG_VERIFY) {
11677                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11678                        + " with the correct signature");
11679            }
11680            sufficientVerifiers.add(comp);
11681            verificationState.addSufficientVerifier(verifierUid);
11682        }
11683
11684        return sufficientVerifiers;
11685    }
11686
11687    private int getUidForVerifier(VerifierInfo verifierInfo) {
11688        synchronized (mPackages) {
11689            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11690            if (pkg == null) {
11691                return -1;
11692            } else if (pkg.mSignatures.length != 1) {
11693                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11694                        + " has more than one signature; ignoring");
11695                return -1;
11696            }
11697
11698            /*
11699             * If the public key of the package's signature does not match
11700             * our expected public key, then this is a different package and
11701             * we should skip.
11702             */
11703
11704            final byte[] expectedPublicKey;
11705            try {
11706                final Signature verifierSig = pkg.mSignatures[0];
11707                final PublicKey publicKey = verifierSig.getPublicKey();
11708                expectedPublicKey = publicKey.getEncoded();
11709            } catch (CertificateException e) {
11710                return -1;
11711            }
11712
11713            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11714
11715            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11716                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11717                        + " does not have the expected public key; ignoring");
11718                return -1;
11719            }
11720
11721            return pkg.applicationInfo.uid;
11722        }
11723    }
11724
11725    @Override
11726    public void finishPackageInstall(int token) {
11727        enforceSystemOrRoot("Only the system is allowed to finish installs");
11728
11729        if (DEBUG_INSTALL) {
11730            Slog.v(TAG, "BM finishing package install for " + token);
11731        }
11732        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11733
11734        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11735        mHandler.sendMessage(msg);
11736    }
11737
11738    /**
11739     * Get the verification agent timeout.
11740     *
11741     * @return verification timeout in milliseconds
11742     */
11743    private long getVerificationTimeout() {
11744        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11745                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11746                DEFAULT_VERIFICATION_TIMEOUT);
11747    }
11748
11749    /**
11750     * Get the default verification agent response code.
11751     *
11752     * @return default verification response code
11753     */
11754    private int getDefaultVerificationResponse() {
11755        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11756                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11757                DEFAULT_VERIFICATION_RESPONSE);
11758    }
11759
11760    /**
11761     * Check whether or not package verification has been enabled.
11762     *
11763     * @return true if verification should be performed
11764     */
11765    private boolean isVerificationEnabled(int userId, int installFlags) {
11766        if (!DEFAULT_VERIFY_ENABLE) {
11767            return false;
11768        }
11769        // Ephemeral apps don't get the full verification treatment
11770        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11771            if (DEBUG_EPHEMERAL) {
11772                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11773            }
11774            return false;
11775        }
11776
11777        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11778
11779        // Check if installing from ADB
11780        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11781            // Do not run verification in a test harness environment
11782            if (ActivityManager.isRunningInTestHarness()) {
11783                return false;
11784            }
11785            if (ensureVerifyAppsEnabled) {
11786                return true;
11787            }
11788            // Check if the developer does not want package verification for ADB installs
11789            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11790                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11791                return false;
11792            }
11793        }
11794
11795        if (ensureVerifyAppsEnabled) {
11796            return true;
11797        }
11798
11799        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11800                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11801    }
11802
11803    @Override
11804    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11805            throws RemoteException {
11806        mContext.enforceCallingOrSelfPermission(
11807                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11808                "Only intentfilter verification agents can verify applications");
11809
11810        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11811        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11812                Binder.getCallingUid(), verificationCode, failedDomains);
11813        msg.arg1 = id;
11814        msg.obj = response;
11815        mHandler.sendMessage(msg);
11816    }
11817
11818    @Override
11819    public int getIntentVerificationStatus(String packageName, int userId) {
11820        synchronized (mPackages) {
11821            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11822        }
11823    }
11824
11825    @Override
11826    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11827        mContext.enforceCallingOrSelfPermission(
11828                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11829
11830        boolean result = false;
11831        synchronized (mPackages) {
11832            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11833        }
11834        if (result) {
11835            scheduleWritePackageRestrictionsLocked(userId);
11836        }
11837        return result;
11838    }
11839
11840    @Override
11841    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11842            String packageName) {
11843        synchronized (mPackages) {
11844            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11845        }
11846    }
11847
11848    @Override
11849    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11850        if (TextUtils.isEmpty(packageName)) {
11851            return ParceledListSlice.emptyList();
11852        }
11853        synchronized (mPackages) {
11854            PackageParser.Package pkg = mPackages.get(packageName);
11855            if (pkg == null || pkg.activities == null) {
11856                return ParceledListSlice.emptyList();
11857            }
11858            final int count = pkg.activities.size();
11859            ArrayList<IntentFilter> result = new ArrayList<>();
11860            for (int n=0; n<count; n++) {
11861                PackageParser.Activity activity = pkg.activities.get(n);
11862                if (activity.intents != null && activity.intents.size() > 0) {
11863                    result.addAll(activity.intents);
11864                }
11865            }
11866            return new ParceledListSlice<>(result);
11867        }
11868    }
11869
11870    @Override
11871    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11872        mContext.enforceCallingOrSelfPermission(
11873                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11874
11875        synchronized (mPackages) {
11876            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11877            if (packageName != null) {
11878                result |= updateIntentVerificationStatus(packageName,
11879                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11880                        userId);
11881                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11882                        packageName, userId);
11883            }
11884            return result;
11885        }
11886    }
11887
11888    @Override
11889    public String getDefaultBrowserPackageName(int userId) {
11890        synchronized (mPackages) {
11891            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11892        }
11893    }
11894
11895    /**
11896     * Get the "allow unknown sources" setting.
11897     *
11898     * @return the current "allow unknown sources" setting
11899     */
11900    private int getUnknownSourcesSettings() {
11901        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11902                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11903                -1);
11904    }
11905
11906    @Override
11907    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11908        final int uid = Binder.getCallingUid();
11909        // writer
11910        synchronized (mPackages) {
11911            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11912            if (targetPackageSetting == null) {
11913                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11914            }
11915
11916            PackageSetting installerPackageSetting;
11917            if (installerPackageName != null) {
11918                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11919                if (installerPackageSetting == null) {
11920                    throw new IllegalArgumentException("Unknown installer package: "
11921                            + installerPackageName);
11922                }
11923            } else {
11924                installerPackageSetting = null;
11925            }
11926
11927            Signature[] callerSignature;
11928            Object obj = mSettings.getUserIdLPr(uid);
11929            if (obj != null) {
11930                if (obj instanceof SharedUserSetting) {
11931                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11932                } else if (obj instanceof PackageSetting) {
11933                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11934                } else {
11935                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11936                }
11937            } else {
11938                throw new SecurityException("Unknown calling UID: " + uid);
11939            }
11940
11941            // Verify: can't set installerPackageName to a package that is
11942            // not signed with the same cert as the caller.
11943            if (installerPackageSetting != null) {
11944                if (compareSignatures(callerSignature,
11945                        installerPackageSetting.signatures.mSignatures)
11946                        != PackageManager.SIGNATURE_MATCH) {
11947                    throw new SecurityException(
11948                            "Caller does not have same cert as new installer package "
11949                            + installerPackageName);
11950                }
11951            }
11952
11953            // Verify: if target already has an installer package, it must
11954            // be signed with the same cert as the caller.
11955            if (targetPackageSetting.installerPackageName != null) {
11956                PackageSetting setting = mSettings.mPackages.get(
11957                        targetPackageSetting.installerPackageName);
11958                // If the currently set package isn't valid, then it's always
11959                // okay to change it.
11960                if (setting != null) {
11961                    if (compareSignatures(callerSignature,
11962                            setting.signatures.mSignatures)
11963                            != PackageManager.SIGNATURE_MATCH) {
11964                        throw new SecurityException(
11965                                "Caller does not have same cert as old installer package "
11966                                + targetPackageSetting.installerPackageName);
11967                    }
11968                }
11969            }
11970
11971            // Okay!
11972            targetPackageSetting.installerPackageName = installerPackageName;
11973            if (installerPackageName != null) {
11974                mSettings.mInstallerPackages.add(installerPackageName);
11975            }
11976            scheduleWriteSettingsLocked();
11977        }
11978    }
11979
11980    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11981        // Queue up an async operation since the package installation may take a little while.
11982        mHandler.post(new Runnable() {
11983            public void run() {
11984                mHandler.removeCallbacks(this);
11985                 // Result object to be returned
11986                PackageInstalledInfo res = new PackageInstalledInfo();
11987                res.setReturnCode(currentStatus);
11988                res.uid = -1;
11989                res.pkg = null;
11990                res.removedInfo = null;
11991                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11992                    args.doPreInstall(res.returnCode);
11993                    synchronized (mInstallLock) {
11994                        installPackageTracedLI(args, res);
11995                    }
11996                    args.doPostInstall(res.returnCode, res.uid);
11997                }
11998
11999                // A restore should be performed at this point if (a) the install
12000                // succeeded, (b) the operation is not an update, and (c) the new
12001                // package has not opted out of backup participation.
12002                final boolean update = res.removedInfo != null
12003                        && res.removedInfo.removedPackage != null;
12004                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12005                boolean doRestore = !update
12006                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12007
12008                // Set up the post-install work request bookkeeping.  This will be used
12009                // and cleaned up by the post-install event handling regardless of whether
12010                // there's a restore pass performed.  Token values are >= 1.
12011                int token;
12012                if (mNextInstallToken < 0) mNextInstallToken = 1;
12013                token = mNextInstallToken++;
12014
12015                PostInstallData data = new PostInstallData(args, res);
12016                mRunningInstalls.put(token, data);
12017                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12018
12019                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12020                    // Pass responsibility to the Backup Manager.  It will perform a
12021                    // restore if appropriate, then pass responsibility back to the
12022                    // Package Manager to run the post-install observer callbacks
12023                    // and broadcasts.
12024                    IBackupManager bm = IBackupManager.Stub.asInterface(
12025                            ServiceManager.getService(Context.BACKUP_SERVICE));
12026                    if (bm != null) {
12027                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12028                                + " to BM for possible restore");
12029                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12030                        try {
12031                            // TODO: http://b/22388012
12032                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12033                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12034                            } else {
12035                                doRestore = false;
12036                            }
12037                        } catch (RemoteException e) {
12038                            // can't happen; the backup manager is local
12039                        } catch (Exception e) {
12040                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12041                            doRestore = false;
12042                        }
12043                    } else {
12044                        Slog.e(TAG, "Backup Manager not found!");
12045                        doRestore = false;
12046                    }
12047                }
12048
12049                if (!doRestore) {
12050                    // No restore possible, or the Backup Manager was mysteriously not
12051                    // available -- just fire the post-install work request directly.
12052                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12053
12054                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12055
12056                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12057                    mHandler.sendMessage(msg);
12058                }
12059            }
12060        });
12061    }
12062
12063    private abstract class HandlerParams {
12064        private static final int MAX_RETRIES = 4;
12065
12066        /**
12067         * Number of times startCopy() has been attempted and had a non-fatal
12068         * error.
12069         */
12070        private int mRetries = 0;
12071
12072        /** User handle for the user requesting the information or installation. */
12073        private final UserHandle mUser;
12074        String traceMethod;
12075        int traceCookie;
12076
12077        HandlerParams(UserHandle user) {
12078            mUser = user;
12079        }
12080
12081        UserHandle getUser() {
12082            return mUser;
12083        }
12084
12085        HandlerParams setTraceMethod(String traceMethod) {
12086            this.traceMethod = traceMethod;
12087            return this;
12088        }
12089
12090        HandlerParams setTraceCookie(int traceCookie) {
12091            this.traceCookie = traceCookie;
12092            return this;
12093        }
12094
12095        final boolean startCopy() {
12096            boolean res;
12097            try {
12098                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12099
12100                if (++mRetries > MAX_RETRIES) {
12101                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12102                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12103                    handleServiceError();
12104                    return false;
12105                } else {
12106                    handleStartCopy();
12107                    res = true;
12108                }
12109            } catch (RemoteException e) {
12110                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12111                mHandler.sendEmptyMessage(MCS_RECONNECT);
12112                res = false;
12113            }
12114            handleReturnCode();
12115            return res;
12116        }
12117
12118        final void serviceError() {
12119            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12120            handleServiceError();
12121            handleReturnCode();
12122        }
12123
12124        abstract void handleStartCopy() throws RemoteException;
12125        abstract void handleServiceError();
12126        abstract void handleReturnCode();
12127    }
12128
12129    class MeasureParams extends HandlerParams {
12130        private final PackageStats mStats;
12131        private boolean mSuccess;
12132
12133        private final IPackageStatsObserver mObserver;
12134
12135        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12136            super(new UserHandle(stats.userHandle));
12137            mObserver = observer;
12138            mStats = stats;
12139        }
12140
12141        @Override
12142        public String toString() {
12143            return "MeasureParams{"
12144                + Integer.toHexString(System.identityHashCode(this))
12145                + " " + mStats.packageName + "}";
12146        }
12147
12148        @Override
12149        void handleStartCopy() throws RemoteException {
12150            synchronized (mInstallLock) {
12151                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12152            }
12153
12154            if (mSuccess) {
12155                final boolean mounted;
12156                if (Environment.isExternalStorageEmulated()) {
12157                    mounted = true;
12158                } else {
12159                    final String status = Environment.getExternalStorageState();
12160                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12161                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12162                }
12163
12164                if (mounted) {
12165                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12166
12167                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12168                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12169
12170                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12171                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12172
12173                    // Always subtract cache size, since it's a subdirectory
12174                    mStats.externalDataSize -= mStats.externalCacheSize;
12175
12176                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12177                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12178
12179                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12180                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12181                }
12182            }
12183        }
12184
12185        @Override
12186        void handleReturnCode() {
12187            if (mObserver != null) {
12188                try {
12189                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12190                } catch (RemoteException e) {
12191                    Slog.i(TAG, "Observer no longer exists.");
12192                }
12193            }
12194        }
12195
12196        @Override
12197        void handleServiceError() {
12198            Slog.e(TAG, "Could not measure application " + mStats.packageName
12199                            + " external storage");
12200        }
12201    }
12202
12203    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12204            throws RemoteException {
12205        long result = 0;
12206        for (File path : paths) {
12207            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12208        }
12209        return result;
12210    }
12211
12212    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12213        for (File path : paths) {
12214            try {
12215                mcs.clearDirectory(path.getAbsolutePath());
12216            } catch (RemoteException e) {
12217            }
12218        }
12219    }
12220
12221    static class OriginInfo {
12222        /**
12223         * Location where install is coming from, before it has been
12224         * copied/renamed into place. This could be a single monolithic APK
12225         * file, or a cluster directory. This location may be untrusted.
12226         */
12227        final File file;
12228        final String cid;
12229
12230        /**
12231         * Flag indicating that {@link #file} or {@link #cid} has already been
12232         * staged, meaning downstream users don't need to defensively copy the
12233         * contents.
12234         */
12235        final boolean staged;
12236
12237        /**
12238         * Flag indicating that {@link #file} or {@link #cid} is an already
12239         * installed app that is being moved.
12240         */
12241        final boolean existing;
12242
12243        final String resolvedPath;
12244        final File resolvedFile;
12245
12246        static OriginInfo fromNothing() {
12247            return new OriginInfo(null, null, false, false);
12248        }
12249
12250        static OriginInfo fromUntrustedFile(File file) {
12251            return new OriginInfo(file, null, false, false);
12252        }
12253
12254        static OriginInfo fromExistingFile(File file) {
12255            return new OriginInfo(file, null, false, true);
12256        }
12257
12258        static OriginInfo fromStagedFile(File file) {
12259            return new OriginInfo(file, null, true, false);
12260        }
12261
12262        static OriginInfo fromStagedContainer(String cid) {
12263            return new OriginInfo(null, cid, true, false);
12264        }
12265
12266        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12267            this.file = file;
12268            this.cid = cid;
12269            this.staged = staged;
12270            this.existing = existing;
12271
12272            if (cid != null) {
12273                resolvedPath = PackageHelper.getSdDir(cid);
12274                resolvedFile = new File(resolvedPath);
12275            } else if (file != null) {
12276                resolvedPath = file.getAbsolutePath();
12277                resolvedFile = file;
12278            } else {
12279                resolvedPath = null;
12280                resolvedFile = null;
12281            }
12282        }
12283    }
12284
12285    static class MoveInfo {
12286        final int moveId;
12287        final String fromUuid;
12288        final String toUuid;
12289        final String packageName;
12290        final String dataAppName;
12291        final int appId;
12292        final String seinfo;
12293        final int targetSdkVersion;
12294
12295        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12296                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12297            this.moveId = moveId;
12298            this.fromUuid = fromUuid;
12299            this.toUuid = toUuid;
12300            this.packageName = packageName;
12301            this.dataAppName = dataAppName;
12302            this.appId = appId;
12303            this.seinfo = seinfo;
12304            this.targetSdkVersion = targetSdkVersion;
12305        }
12306    }
12307
12308    static class VerificationInfo {
12309        /** A constant used to indicate that a uid value is not present. */
12310        public static final int NO_UID = -1;
12311
12312        /** URI referencing where the package was downloaded from. */
12313        final Uri originatingUri;
12314
12315        /** HTTP referrer URI associated with the originatingURI. */
12316        final Uri referrer;
12317
12318        /** UID of the application that the install request originated from. */
12319        final int originatingUid;
12320
12321        /** UID of application requesting the install */
12322        final int installerUid;
12323
12324        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12325            this.originatingUri = originatingUri;
12326            this.referrer = referrer;
12327            this.originatingUid = originatingUid;
12328            this.installerUid = installerUid;
12329        }
12330    }
12331
12332    class InstallParams extends HandlerParams {
12333        final OriginInfo origin;
12334        final MoveInfo move;
12335        final IPackageInstallObserver2 observer;
12336        int installFlags;
12337        final String installerPackageName;
12338        final String volumeUuid;
12339        private InstallArgs mArgs;
12340        private int mRet;
12341        final String packageAbiOverride;
12342        final String[] grantedRuntimePermissions;
12343        final VerificationInfo verificationInfo;
12344        final Certificate[][] certificates;
12345
12346        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12347                int installFlags, String installerPackageName, String volumeUuid,
12348                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12349                String[] grantedPermissions, Certificate[][] certificates) {
12350            super(user);
12351            this.origin = origin;
12352            this.move = move;
12353            this.observer = observer;
12354            this.installFlags = installFlags;
12355            this.installerPackageName = installerPackageName;
12356            this.volumeUuid = volumeUuid;
12357            this.verificationInfo = verificationInfo;
12358            this.packageAbiOverride = packageAbiOverride;
12359            this.grantedRuntimePermissions = grantedPermissions;
12360            this.certificates = certificates;
12361        }
12362
12363        @Override
12364        public String toString() {
12365            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12366                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12367        }
12368
12369        private int installLocationPolicy(PackageInfoLite pkgLite) {
12370            String packageName = pkgLite.packageName;
12371            int installLocation = pkgLite.installLocation;
12372            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12373            // reader
12374            synchronized (mPackages) {
12375                // Currently installed package which the new package is attempting to replace or
12376                // null if no such package is installed.
12377                PackageParser.Package installedPkg = mPackages.get(packageName);
12378                // Package which currently owns the data which the new package will own if installed.
12379                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12380                // will be null whereas dataOwnerPkg will contain information about the package
12381                // which was uninstalled while keeping its data.
12382                PackageParser.Package dataOwnerPkg = installedPkg;
12383                if (dataOwnerPkg  == null) {
12384                    PackageSetting ps = mSettings.mPackages.get(packageName);
12385                    if (ps != null) {
12386                        dataOwnerPkg = ps.pkg;
12387                    }
12388                }
12389
12390                if (dataOwnerPkg != null) {
12391                    // If installed, the package will get access to data left on the device by its
12392                    // predecessor. As a security measure, this is permited only if this is not a
12393                    // version downgrade or if the predecessor package is marked as debuggable and
12394                    // a downgrade is explicitly requested.
12395                    //
12396                    // On debuggable platform builds, downgrades are permitted even for
12397                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12398                    // not offer security guarantees and thus it's OK to disable some security
12399                    // mechanisms to make debugging/testing easier on those builds. However, even on
12400                    // debuggable builds downgrades of packages are permitted only if requested via
12401                    // installFlags. This is because we aim to keep the behavior of debuggable
12402                    // platform builds as close as possible to the behavior of non-debuggable
12403                    // platform builds.
12404                    final boolean downgradeRequested =
12405                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12406                    final boolean packageDebuggable =
12407                                (dataOwnerPkg.applicationInfo.flags
12408                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12409                    final boolean downgradePermitted =
12410                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12411                    if (!downgradePermitted) {
12412                        try {
12413                            checkDowngrade(dataOwnerPkg, pkgLite);
12414                        } catch (PackageManagerException e) {
12415                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12416                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12417                        }
12418                    }
12419                }
12420
12421                if (installedPkg != null) {
12422                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12423                        // Check for updated system application.
12424                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12425                            if (onSd) {
12426                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12427                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12428                            }
12429                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12430                        } else {
12431                            if (onSd) {
12432                                // Install flag overrides everything.
12433                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12434                            }
12435                            // If current upgrade specifies particular preference
12436                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12437                                // Application explicitly specified internal.
12438                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12439                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12440                                // App explictly prefers external. Let policy decide
12441                            } else {
12442                                // Prefer previous location
12443                                if (isExternal(installedPkg)) {
12444                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12445                                }
12446                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12447                            }
12448                        }
12449                    } else {
12450                        // Invalid install. Return error code
12451                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12452                    }
12453                }
12454            }
12455            // All the special cases have been taken care of.
12456            // Return result based on recommended install location.
12457            if (onSd) {
12458                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12459            }
12460            return pkgLite.recommendedInstallLocation;
12461        }
12462
12463        /*
12464         * Invoke remote method to get package information and install
12465         * location values. Override install location based on default
12466         * policy if needed and then create install arguments based
12467         * on the install location.
12468         */
12469        public void handleStartCopy() throws RemoteException {
12470            int ret = PackageManager.INSTALL_SUCCEEDED;
12471
12472            // If we're already staged, we've firmly committed to an install location
12473            if (origin.staged) {
12474                if (origin.file != null) {
12475                    installFlags |= PackageManager.INSTALL_INTERNAL;
12476                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12477                } else if (origin.cid != null) {
12478                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12479                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12480                } else {
12481                    throw new IllegalStateException("Invalid stage location");
12482                }
12483            }
12484
12485            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12486            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12487            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12488            PackageInfoLite pkgLite = null;
12489
12490            if (onInt && onSd) {
12491                // Check if both bits are set.
12492                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12493                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12494            } else if (onSd && ephemeral) {
12495                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12496                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12497            } else {
12498                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12499                        packageAbiOverride);
12500
12501                if (DEBUG_EPHEMERAL && ephemeral) {
12502                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12503                }
12504
12505                /*
12506                 * If we have too little free space, try to free cache
12507                 * before giving up.
12508                 */
12509                if (!origin.staged && pkgLite.recommendedInstallLocation
12510                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12511                    // TODO: focus freeing disk space on the target device
12512                    final StorageManager storage = StorageManager.from(mContext);
12513                    final long lowThreshold = storage.getStorageLowBytes(
12514                            Environment.getDataDirectory());
12515
12516                    final long sizeBytes = mContainerService.calculateInstalledSize(
12517                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12518
12519                    try {
12520                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12521                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12522                                installFlags, packageAbiOverride);
12523                    } catch (InstallerException e) {
12524                        Slog.w(TAG, "Failed to free cache", e);
12525                    }
12526
12527                    /*
12528                     * The cache free must have deleted the file we
12529                     * downloaded to install.
12530                     *
12531                     * TODO: fix the "freeCache" call to not delete
12532                     *       the file we care about.
12533                     */
12534                    if (pkgLite.recommendedInstallLocation
12535                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12536                        pkgLite.recommendedInstallLocation
12537                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12538                    }
12539                }
12540            }
12541
12542            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12543                int loc = pkgLite.recommendedInstallLocation;
12544                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12545                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12546                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12547                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12548                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12549                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12550                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12551                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12552                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12553                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12554                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12555                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12556                } else {
12557                    // Override with defaults if needed.
12558                    loc = installLocationPolicy(pkgLite);
12559                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12560                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12561                    } else if (!onSd && !onInt) {
12562                        // Override install location with flags
12563                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12564                            // Set the flag to install on external media.
12565                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12566                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12567                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12568                            if (DEBUG_EPHEMERAL) {
12569                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12570                            }
12571                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12572                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12573                                    |PackageManager.INSTALL_INTERNAL);
12574                        } else {
12575                            // Make sure the flag for installing on external
12576                            // media is unset
12577                            installFlags |= PackageManager.INSTALL_INTERNAL;
12578                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12579                        }
12580                    }
12581                }
12582            }
12583
12584            final InstallArgs args = createInstallArgs(this);
12585            mArgs = args;
12586
12587            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12588                // TODO: http://b/22976637
12589                // Apps installed for "all" users use the device owner to verify the app
12590                UserHandle verifierUser = getUser();
12591                if (verifierUser == UserHandle.ALL) {
12592                    verifierUser = UserHandle.SYSTEM;
12593                }
12594
12595                /*
12596                 * Determine if we have any installed package verifiers. If we
12597                 * do, then we'll defer to them to verify the packages.
12598                 */
12599                final int requiredUid = mRequiredVerifierPackage == null ? -1
12600                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12601                                verifierUser.getIdentifier());
12602                if (!origin.existing && requiredUid != -1
12603                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12604                    final Intent verification = new Intent(
12605                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12606                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12607                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12608                            PACKAGE_MIME_TYPE);
12609                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12610
12611                    // Query all live verifiers based on current user state
12612                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12613                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12614
12615                    if (DEBUG_VERIFY) {
12616                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12617                                + verification.toString() + " with " + pkgLite.verifiers.length
12618                                + " optional verifiers");
12619                    }
12620
12621                    final int verificationId = mPendingVerificationToken++;
12622
12623                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12624
12625                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12626                            installerPackageName);
12627
12628                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12629                            installFlags);
12630
12631                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12632                            pkgLite.packageName);
12633
12634                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12635                            pkgLite.versionCode);
12636
12637                    if (verificationInfo != null) {
12638                        if (verificationInfo.originatingUri != null) {
12639                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12640                                    verificationInfo.originatingUri);
12641                        }
12642                        if (verificationInfo.referrer != null) {
12643                            verification.putExtra(Intent.EXTRA_REFERRER,
12644                                    verificationInfo.referrer);
12645                        }
12646                        if (verificationInfo.originatingUid >= 0) {
12647                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12648                                    verificationInfo.originatingUid);
12649                        }
12650                        if (verificationInfo.installerUid >= 0) {
12651                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12652                                    verificationInfo.installerUid);
12653                        }
12654                    }
12655
12656                    final PackageVerificationState verificationState = new PackageVerificationState(
12657                            requiredUid, args);
12658
12659                    mPendingVerification.append(verificationId, verificationState);
12660
12661                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12662                            receivers, verificationState);
12663
12664                    /*
12665                     * If any sufficient verifiers were listed in the package
12666                     * manifest, attempt to ask them.
12667                     */
12668                    if (sufficientVerifiers != null) {
12669                        final int N = sufficientVerifiers.size();
12670                        if (N == 0) {
12671                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12672                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12673                        } else {
12674                            for (int i = 0; i < N; i++) {
12675                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12676
12677                                final Intent sufficientIntent = new Intent(verification);
12678                                sufficientIntent.setComponent(verifierComponent);
12679                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12680                            }
12681                        }
12682                    }
12683
12684                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12685                            mRequiredVerifierPackage, receivers);
12686                    if (ret == PackageManager.INSTALL_SUCCEEDED
12687                            && mRequiredVerifierPackage != null) {
12688                        Trace.asyncTraceBegin(
12689                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12690                        /*
12691                         * Send the intent to the required verification agent,
12692                         * but only start the verification timeout after the
12693                         * target BroadcastReceivers have run.
12694                         */
12695                        verification.setComponent(requiredVerifierComponent);
12696                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12697                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12698                                new BroadcastReceiver() {
12699                                    @Override
12700                                    public void onReceive(Context context, Intent intent) {
12701                                        final Message msg = mHandler
12702                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12703                                        msg.arg1 = verificationId;
12704                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12705                                    }
12706                                }, null, 0, null, null);
12707
12708                        /*
12709                         * We don't want the copy to proceed until verification
12710                         * succeeds, so null out this field.
12711                         */
12712                        mArgs = null;
12713                    }
12714                } else {
12715                    /*
12716                     * No package verification is enabled, so immediately start
12717                     * the remote call to initiate copy using temporary file.
12718                     */
12719                    ret = args.copyApk(mContainerService, true);
12720                }
12721            }
12722
12723            mRet = ret;
12724        }
12725
12726        @Override
12727        void handleReturnCode() {
12728            // If mArgs is null, then MCS couldn't be reached. When it
12729            // reconnects, it will try again to install. At that point, this
12730            // will succeed.
12731            if (mArgs != null) {
12732                processPendingInstall(mArgs, mRet);
12733            }
12734        }
12735
12736        @Override
12737        void handleServiceError() {
12738            mArgs = createInstallArgs(this);
12739            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12740        }
12741
12742        public boolean isForwardLocked() {
12743            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12744        }
12745    }
12746
12747    /**
12748     * Used during creation of InstallArgs
12749     *
12750     * @param installFlags package installation flags
12751     * @return true if should be installed on external storage
12752     */
12753    private static boolean installOnExternalAsec(int installFlags) {
12754        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12755            return false;
12756        }
12757        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12758            return true;
12759        }
12760        return false;
12761    }
12762
12763    /**
12764     * Used during creation of InstallArgs
12765     *
12766     * @param installFlags package installation flags
12767     * @return true if should be installed as forward locked
12768     */
12769    private static boolean installForwardLocked(int installFlags) {
12770        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12771    }
12772
12773    private InstallArgs createInstallArgs(InstallParams params) {
12774        if (params.move != null) {
12775            return new MoveInstallArgs(params);
12776        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12777            return new AsecInstallArgs(params);
12778        } else {
12779            return new FileInstallArgs(params);
12780        }
12781    }
12782
12783    /**
12784     * Create args that describe an existing installed package. Typically used
12785     * when cleaning up old installs, or used as a move source.
12786     */
12787    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12788            String resourcePath, String[] instructionSets) {
12789        final boolean isInAsec;
12790        if (installOnExternalAsec(installFlags)) {
12791            /* Apps on SD card are always in ASEC containers. */
12792            isInAsec = true;
12793        } else if (installForwardLocked(installFlags)
12794                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12795            /*
12796             * Forward-locked apps are only in ASEC containers if they're the
12797             * new style
12798             */
12799            isInAsec = true;
12800        } else {
12801            isInAsec = false;
12802        }
12803
12804        if (isInAsec) {
12805            return new AsecInstallArgs(codePath, instructionSets,
12806                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12807        } else {
12808            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12809        }
12810    }
12811
12812    static abstract class InstallArgs {
12813        /** @see InstallParams#origin */
12814        final OriginInfo origin;
12815        /** @see InstallParams#move */
12816        final MoveInfo move;
12817
12818        final IPackageInstallObserver2 observer;
12819        // Always refers to PackageManager flags only
12820        final int installFlags;
12821        final String installerPackageName;
12822        final String volumeUuid;
12823        final UserHandle user;
12824        final String abiOverride;
12825        final String[] installGrantPermissions;
12826        /** If non-null, drop an async trace when the install completes */
12827        final String traceMethod;
12828        final int traceCookie;
12829        final Certificate[][] certificates;
12830
12831        // The list of instruction sets supported by this app. This is currently
12832        // only used during the rmdex() phase to clean up resources. We can get rid of this
12833        // if we move dex files under the common app path.
12834        /* nullable */ String[] instructionSets;
12835
12836        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12837                int installFlags, String installerPackageName, String volumeUuid,
12838                UserHandle user, String[] instructionSets,
12839                String abiOverride, String[] installGrantPermissions,
12840                String traceMethod, int traceCookie, Certificate[][] certificates) {
12841            this.origin = origin;
12842            this.move = move;
12843            this.installFlags = installFlags;
12844            this.observer = observer;
12845            this.installerPackageName = installerPackageName;
12846            this.volumeUuid = volumeUuid;
12847            this.user = user;
12848            this.instructionSets = instructionSets;
12849            this.abiOverride = abiOverride;
12850            this.installGrantPermissions = installGrantPermissions;
12851            this.traceMethod = traceMethod;
12852            this.traceCookie = traceCookie;
12853            this.certificates = certificates;
12854        }
12855
12856        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12857        abstract int doPreInstall(int status);
12858
12859        /**
12860         * Rename package into final resting place. All paths on the given
12861         * scanned package should be updated to reflect the rename.
12862         */
12863        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12864        abstract int doPostInstall(int status, int uid);
12865
12866        /** @see PackageSettingBase#codePathString */
12867        abstract String getCodePath();
12868        /** @see PackageSettingBase#resourcePathString */
12869        abstract String getResourcePath();
12870
12871        // Need installer lock especially for dex file removal.
12872        abstract void cleanUpResourcesLI();
12873        abstract boolean doPostDeleteLI(boolean delete);
12874
12875        /**
12876         * Called before the source arguments are copied. This is used mostly
12877         * for MoveParams when it needs to read the source file to put it in the
12878         * destination.
12879         */
12880        int doPreCopy() {
12881            return PackageManager.INSTALL_SUCCEEDED;
12882        }
12883
12884        /**
12885         * Called after the source arguments are copied. This is used mostly for
12886         * MoveParams when it needs to read the source file to put it in the
12887         * destination.
12888         */
12889        int doPostCopy(int uid) {
12890            return PackageManager.INSTALL_SUCCEEDED;
12891        }
12892
12893        protected boolean isFwdLocked() {
12894            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12895        }
12896
12897        protected boolean isExternalAsec() {
12898            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12899        }
12900
12901        protected boolean isEphemeral() {
12902            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12903        }
12904
12905        UserHandle getUser() {
12906            return user;
12907        }
12908    }
12909
12910    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12911        if (!allCodePaths.isEmpty()) {
12912            if (instructionSets == null) {
12913                throw new IllegalStateException("instructionSet == null");
12914            }
12915            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12916            for (String codePath : allCodePaths) {
12917                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12918                    try {
12919                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12920                    } catch (InstallerException ignored) {
12921                    }
12922                }
12923            }
12924        }
12925    }
12926
12927    /**
12928     * Logic to handle installation of non-ASEC applications, including copying
12929     * and renaming logic.
12930     */
12931    class FileInstallArgs extends InstallArgs {
12932        private File codeFile;
12933        private File resourceFile;
12934
12935        // Example topology:
12936        // /data/app/com.example/base.apk
12937        // /data/app/com.example/split_foo.apk
12938        // /data/app/com.example/lib/arm/libfoo.so
12939        // /data/app/com.example/lib/arm64/libfoo.so
12940        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12941
12942        /** New install */
12943        FileInstallArgs(InstallParams params) {
12944            super(params.origin, params.move, params.observer, params.installFlags,
12945                    params.installerPackageName, params.volumeUuid,
12946                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12947                    params.grantedRuntimePermissions,
12948                    params.traceMethod, params.traceCookie, params.certificates);
12949            if (isFwdLocked()) {
12950                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12951            }
12952        }
12953
12954        /** Existing install */
12955        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12956            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12957                    null, null, null, 0, null /*certificates*/);
12958            this.codeFile = (codePath != null) ? new File(codePath) : null;
12959            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12960        }
12961
12962        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12963            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12964            try {
12965                return doCopyApk(imcs, temp);
12966            } finally {
12967                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12968            }
12969        }
12970
12971        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12972            if (origin.staged) {
12973                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12974                codeFile = origin.file;
12975                resourceFile = origin.file;
12976                return PackageManager.INSTALL_SUCCEEDED;
12977            }
12978
12979            try {
12980                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12981                final File tempDir =
12982                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12983                codeFile = tempDir;
12984                resourceFile = tempDir;
12985            } catch (IOException e) {
12986                Slog.w(TAG, "Failed to create copy file: " + e);
12987                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12988            }
12989
12990            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12991                @Override
12992                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12993                    if (!FileUtils.isValidExtFilename(name)) {
12994                        throw new IllegalArgumentException("Invalid filename: " + name);
12995                    }
12996                    try {
12997                        final File file = new File(codeFile, name);
12998                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12999                                O_RDWR | O_CREAT, 0644);
13000                        Os.chmod(file.getAbsolutePath(), 0644);
13001                        return new ParcelFileDescriptor(fd);
13002                    } catch (ErrnoException e) {
13003                        throw new RemoteException("Failed to open: " + e.getMessage());
13004                    }
13005                }
13006            };
13007
13008            int ret = PackageManager.INSTALL_SUCCEEDED;
13009            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13010            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13011                Slog.e(TAG, "Failed to copy package");
13012                return ret;
13013            }
13014
13015            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13016            NativeLibraryHelper.Handle handle = null;
13017            try {
13018                handle = NativeLibraryHelper.Handle.create(codeFile);
13019                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13020                        abiOverride);
13021            } catch (IOException e) {
13022                Slog.e(TAG, "Copying native libraries failed", e);
13023                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13024            } finally {
13025                IoUtils.closeQuietly(handle);
13026            }
13027
13028            return ret;
13029        }
13030
13031        int doPreInstall(int status) {
13032            if (status != PackageManager.INSTALL_SUCCEEDED) {
13033                cleanUp();
13034            }
13035            return status;
13036        }
13037
13038        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13039            if (status != PackageManager.INSTALL_SUCCEEDED) {
13040                cleanUp();
13041                return false;
13042            }
13043
13044            final File targetDir = codeFile.getParentFile();
13045            final File beforeCodeFile = codeFile;
13046            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13047
13048            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13049            try {
13050                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13051            } catch (ErrnoException e) {
13052                Slog.w(TAG, "Failed to rename", e);
13053                return false;
13054            }
13055
13056            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13057                Slog.w(TAG, "Failed to restorecon");
13058                return false;
13059            }
13060
13061            // Reflect the rename internally
13062            codeFile = afterCodeFile;
13063            resourceFile = afterCodeFile;
13064
13065            // Reflect the rename in scanned details
13066            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13067            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13068                    afterCodeFile, pkg.baseCodePath));
13069            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13070                    afterCodeFile, pkg.splitCodePaths));
13071
13072            // Reflect the rename in app info
13073            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13074            pkg.setApplicationInfoCodePath(pkg.codePath);
13075            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13076            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13077            pkg.setApplicationInfoResourcePath(pkg.codePath);
13078            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13079            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13080
13081            return true;
13082        }
13083
13084        int doPostInstall(int status, int uid) {
13085            if (status != PackageManager.INSTALL_SUCCEEDED) {
13086                cleanUp();
13087            }
13088            return status;
13089        }
13090
13091        @Override
13092        String getCodePath() {
13093            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13094        }
13095
13096        @Override
13097        String getResourcePath() {
13098            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13099        }
13100
13101        private boolean cleanUp() {
13102            if (codeFile == null || !codeFile.exists()) {
13103                return false;
13104            }
13105
13106            removeCodePathLI(codeFile);
13107
13108            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13109                resourceFile.delete();
13110            }
13111
13112            return true;
13113        }
13114
13115        void cleanUpResourcesLI() {
13116            // Try enumerating all code paths before deleting
13117            List<String> allCodePaths = Collections.EMPTY_LIST;
13118            if (codeFile != null && codeFile.exists()) {
13119                try {
13120                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13121                    allCodePaths = pkg.getAllCodePaths();
13122                } catch (PackageParserException e) {
13123                    // Ignored; we tried our best
13124                }
13125            }
13126
13127            cleanUp();
13128            removeDexFiles(allCodePaths, instructionSets);
13129        }
13130
13131        boolean doPostDeleteLI(boolean delete) {
13132            // XXX err, shouldn't we respect the delete flag?
13133            cleanUpResourcesLI();
13134            return true;
13135        }
13136    }
13137
13138    private boolean isAsecExternal(String cid) {
13139        final String asecPath = PackageHelper.getSdFilesystem(cid);
13140        return !asecPath.startsWith(mAsecInternalPath);
13141    }
13142
13143    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13144            PackageManagerException {
13145        if (copyRet < 0) {
13146            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13147                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13148                throw new PackageManagerException(copyRet, message);
13149            }
13150        }
13151    }
13152
13153    /**
13154     * Extract the MountService "container ID" from the full code path of an
13155     * .apk.
13156     */
13157    static String cidFromCodePath(String fullCodePath) {
13158        int eidx = fullCodePath.lastIndexOf("/");
13159        String subStr1 = fullCodePath.substring(0, eidx);
13160        int sidx = subStr1.lastIndexOf("/");
13161        return subStr1.substring(sidx+1, eidx);
13162    }
13163
13164    /**
13165     * Logic to handle installation of ASEC applications, including copying and
13166     * renaming logic.
13167     */
13168    class AsecInstallArgs extends InstallArgs {
13169        static final String RES_FILE_NAME = "pkg.apk";
13170        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13171
13172        String cid;
13173        String packagePath;
13174        String resourcePath;
13175
13176        /** New install */
13177        AsecInstallArgs(InstallParams params) {
13178            super(params.origin, params.move, params.observer, params.installFlags,
13179                    params.installerPackageName, params.volumeUuid,
13180                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13181                    params.grantedRuntimePermissions,
13182                    params.traceMethod, params.traceCookie, params.certificates);
13183        }
13184
13185        /** Existing install */
13186        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13187                        boolean isExternal, boolean isForwardLocked) {
13188            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13189              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13190                    instructionSets, null, null, null, 0, null /*certificates*/);
13191            // Hackily pretend we're still looking at a full code path
13192            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13193                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13194            }
13195
13196            // Extract cid from fullCodePath
13197            int eidx = fullCodePath.lastIndexOf("/");
13198            String subStr1 = fullCodePath.substring(0, eidx);
13199            int sidx = subStr1.lastIndexOf("/");
13200            cid = subStr1.substring(sidx+1, eidx);
13201            setMountPath(subStr1);
13202        }
13203
13204        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13205            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13206              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13207                    instructionSets, null, null, null, 0, null /*certificates*/);
13208            this.cid = cid;
13209            setMountPath(PackageHelper.getSdDir(cid));
13210        }
13211
13212        void createCopyFile() {
13213            cid = mInstallerService.allocateExternalStageCidLegacy();
13214        }
13215
13216        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13217            if (origin.staged && origin.cid != null) {
13218                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13219                cid = origin.cid;
13220                setMountPath(PackageHelper.getSdDir(cid));
13221                return PackageManager.INSTALL_SUCCEEDED;
13222            }
13223
13224            if (temp) {
13225                createCopyFile();
13226            } else {
13227                /*
13228                 * Pre-emptively destroy the container since it's destroyed if
13229                 * copying fails due to it existing anyway.
13230                 */
13231                PackageHelper.destroySdDir(cid);
13232            }
13233
13234            final String newMountPath = imcs.copyPackageToContainer(
13235                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13236                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13237
13238            if (newMountPath != null) {
13239                setMountPath(newMountPath);
13240                return PackageManager.INSTALL_SUCCEEDED;
13241            } else {
13242                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13243            }
13244        }
13245
13246        @Override
13247        String getCodePath() {
13248            return packagePath;
13249        }
13250
13251        @Override
13252        String getResourcePath() {
13253            return resourcePath;
13254        }
13255
13256        int doPreInstall(int status) {
13257            if (status != PackageManager.INSTALL_SUCCEEDED) {
13258                // Destroy container
13259                PackageHelper.destroySdDir(cid);
13260            } else {
13261                boolean mounted = PackageHelper.isContainerMounted(cid);
13262                if (!mounted) {
13263                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13264                            Process.SYSTEM_UID);
13265                    if (newMountPath != null) {
13266                        setMountPath(newMountPath);
13267                    } else {
13268                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13269                    }
13270                }
13271            }
13272            return status;
13273        }
13274
13275        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13276            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13277            String newMountPath = null;
13278            if (PackageHelper.isContainerMounted(cid)) {
13279                // Unmount the container
13280                if (!PackageHelper.unMountSdDir(cid)) {
13281                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13282                    return false;
13283                }
13284            }
13285            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13286                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13287                        " which might be stale. Will try to clean up.");
13288                // Clean up the stale container and proceed to recreate.
13289                if (!PackageHelper.destroySdDir(newCacheId)) {
13290                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13291                    return false;
13292                }
13293                // Successfully cleaned up stale container. Try to rename again.
13294                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13295                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13296                            + " inspite of cleaning it up.");
13297                    return false;
13298                }
13299            }
13300            if (!PackageHelper.isContainerMounted(newCacheId)) {
13301                Slog.w(TAG, "Mounting container " + newCacheId);
13302                newMountPath = PackageHelper.mountSdDir(newCacheId,
13303                        getEncryptKey(), Process.SYSTEM_UID);
13304            } else {
13305                newMountPath = PackageHelper.getSdDir(newCacheId);
13306            }
13307            if (newMountPath == null) {
13308                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13309                return false;
13310            }
13311            Log.i(TAG, "Succesfully renamed " + cid +
13312                    " to " + newCacheId +
13313                    " at new path: " + newMountPath);
13314            cid = newCacheId;
13315
13316            final File beforeCodeFile = new File(packagePath);
13317            setMountPath(newMountPath);
13318            final File afterCodeFile = new File(packagePath);
13319
13320            // Reflect the rename in scanned details
13321            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13322            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13323                    afterCodeFile, pkg.baseCodePath));
13324            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13325                    afterCodeFile, pkg.splitCodePaths));
13326
13327            // Reflect the rename in app info
13328            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13329            pkg.setApplicationInfoCodePath(pkg.codePath);
13330            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13331            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13332            pkg.setApplicationInfoResourcePath(pkg.codePath);
13333            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13334            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13335
13336            return true;
13337        }
13338
13339        private void setMountPath(String mountPath) {
13340            final File mountFile = new File(mountPath);
13341
13342            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13343            if (monolithicFile.exists()) {
13344                packagePath = monolithicFile.getAbsolutePath();
13345                if (isFwdLocked()) {
13346                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13347                } else {
13348                    resourcePath = packagePath;
13349                }
13350            } else {
13351                packagePath = mountFile.getAbsolutePath();
13352                resourcePath = packagePath;
13353            }
13354        }
13355
13356        int doPostInstall(int status, int uid) {
13357            if (status != PackageManager.INSTALL_SUCCEEDED) {
13358                cleanUp();
13359            } else {
13360                final int groupOwner;
13361                final String protectedFile;
13362                if (isFwdLocked()) {
13363                    groupOwner = UserHandle.getSharedAppGid(uid);
13364                    protectedFile = RES_FILE_NAME;
13365                } else {
13366                    groupOwner = -1;
13367                    protectedFile = null;
13368                }
13369
13370                if (uid < Process.FIRST_APPLICATION_UID
13371                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13372                    Slog.e(TAG, "Failed to finalize " + cid);
13373                    PackageHelper.destroySdDir(cid);
13374                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13375                }
13376
13377                boolean mounted = PackageHelper.isContainerMounted(cid);
13378                if (!mounted) {
13379                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13380                }
13381            }
13382            return status;
13383        }
13384
13385        private void cleanUp() {
13386            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13387
13388            // Destroy secure container
13389            PackageHelper.destroySdDir(cid);
13390        }
13391
13392        private List<String> getAllCodePaths() {
13393            final File codeFile = new File(getCodePath());
13394            if (codeFile != null && codeFile.exists()) {
13395                try {
13396                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13397                    return pkg.getAllCodePaths();
13398                } catch (PackageParserException e) {
13399                    // Ignored; we tried our best
13400                }
13401            }
13402            return Collections.EMPTY_LIST;
13403        }
13404
13405        void cleanUpResourcesLI() {
13406            // Enumerate all code paths before deleting
13407            cleanUpResourcesLI(getAllCodePaths());
13408        }
13409
13410        private void cleanUpResourcesLI(List<String> allCodePaths) {
13411            cleanUp();
13412            removeDexFiles(allCodePaths, instructionSets);
13413        }
13414
13415        String getPackageName() {
13416            return getAsecPackageName(cid);
13417        }
13418
13419        boolean doPostDeleteLI(boolean delete) {
13420            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13421            final List<String> allCodePaths = getAllCodePaths();
13422            boolean mounted = PackageHelper.isContainerMounted(cid);
13423            if (mounted) {
13424                // Unmount first
13425                if (PackageHelper.unMountSdDir(cid)) {
13426                    mounted = false;
13427                }
13428            }
13429            if (!mounted && delete) {
13430                cleanUpResourcesLI(allCodePaths);
13431            }
13432            return !mounted;
13433        }
13434
13435        @Override
13436        int doPreCopy() {
13437            if (isFwdLocked()) {
13438                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13439                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13440                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13441                }
13442            }
13443
13444            return PackageManager.INSTALL_SUCCEEDED;
13445        }
13446
13447        @Override
13448        int doPostCopy(int uid) {
13449            if (isFwdLocked()) {
13450                if (uid < Process.FIRST_APPLICATION_UID
13451                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13452                                RES_FILE_NAME)) {
13453                    Slog.e(TAG, "Failed to finalize " + cid);
13454                    PackageHelper.destroySdDir(cid);
13455                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13456                }
13457            }
13458
13459            return PackageManager.INSTALL_SUCCEEDED;
13460        }
13461    }
13462
13463    /**
13464     * Logic to handle movement of existing installed applications.
13465     */
13466    class MoveInstallArgs extends InstallArgs {
13467        private File codeFile;
13468        private File resourceFile;
13469
13470        /** New install */
13471        MoveInstallArgs(InstallParams params) {
13472            super(params.origin, params.move, params.observer, params.installFlags,
13473                    params.installerPackageName, params.volumeUuid,
13474                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13475                    params.grantedRuntimePermissions,
13476                    params.traceMethod, params.traceCookie, params.certificates);
13477        }
13478
13479        int copyApk(IMediaContainerService imcs, boolean temp) {
13480            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13481                    + move.fromUuid + " to " + move.toUuid);
13482            synchronized (mInstaller) {
13483                try {
13484                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13485                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13486                } catch (InstallerException e) {
13487                    Slog.w(TAG, "Failed to move app", e);
13488                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13489                }
13490            }
13491
13492            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13493            resourceFile = codeFile;
13494            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13495
13496            return PackageManager.INSTALL_SUCCEEDED;
13497        }
13498
13499        int doPreInstall(int status) {
13500            if (status != PackageManager.INSTALL_SUCCEEDED) {
13501                cleanUp(move.toUuid);
13502            }
13503            return status;
13504        }
13505
13506        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13507            if (status != PackageManager.INSTALL_SUCCEEDED) {
13508                cleanUp(move.toUuid);
13509                return false;
13510            }
13511
13512            // Reflect the move in app info
13513            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13514            pkg.setApplicationInfoCodePath(pkg.codePath);
13515            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13516            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13517            pkg.setApplicationInfoResourcePath(pkg.codePath);
13518            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13519            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13520
13521            return true;
13522        }
13523
13524        int doPostInstall(int status, int uid) {
13525            if (status == PackageManager.INSTALL_SUCCEEDED) {
13526                cleanUp(move.fromUuid);
13527            } else {
13528                cleanUp(move.toUuid);
13529            }
13530            return status;
13531        }
13532
13533        @Override
13534        String getCodePath() {
13535            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13536        }
13537
13538        @Override
13539        String getResourcePath() {
13540            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13541        }
13542
13543        private boolean cleanUp(String volumeUuid) {
13544            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13545                    move.dataAppName);
13546            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13547            final int[] userIds = sUserManager.getUserIds();
13548            synchronized (mInstallLock) {
13549                // Clean up both app data and code
13550                // All package moves are frozen until finished
13551                for (int userId : userIds) {
13552                    try {
13553                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13554                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13555                    } catch (InstallerException e) {
13556                        Slog.w(TAG, String.valueOf(e));
13557                    }
13558                }
13559                removeCodePathLI(codeFile);
13560            }
13561            return true;
13562        }
13563
13564        void cleanUpResourcesLI() {
13565            throw new UnsupportedOperationException();
13566        }
13567
13568        boolean doPostDeleteLI(boolean delete) {
13569            throw new UnsupportedOperationException();
13570        }
13571    }
13572
13573    static String getAsecPackageName(String packageCid) {
13574        int idx = packageCid.lastIndexOf("-");
13575        if (idx == -1) {
13576            return packageCid;
13577        }
13578        return packageCid.substring(0, idx);
13579    }
13580
13581    // Utility method used to create code paths based on package name and available index.
13582    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13583        String idxStr = "";
13584        int idx = 1;
13585        // Fall back to default value of idx=1 if prefix is not
13586        // part of oldCodePath
13587        if (oldCodePath != null) {
13588            String subStr = oldCodePath;
13589            // Drop the suffix right away
13590            if (suffix != null && subStr.endsWith(suffix)) {
13591                subStr = subStr.substring(0, subStr.length() - suffix.length());
13592            }
13593            // If oldCodePath already contains prefix find out the
13594            // ending index to either increment or decrement.
13595            int sidx = subStr.lastIndexOf(prefix);
13596            if (sidx != -1) {
13597                subStr = subStr.substring(sidx + prefix.length());
13598                if (subStr != null) {
13599                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13600                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13601                    }
13602                    try {
13603                        idx = Integer.parseInt(subStr);
13604                        if (idx <= 1) {
13605                            idx++;
13606                        } else {
13607                            idx--;
13608                        }
13609                    } catch(NumberFormatException e) {
13610                    }
13611                }
13612            }
13613        }
13614        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13615        return prefix + idxStr;
13616    }
13617
13618    private File getNextCodePath(File targetDir, String packageName) {
13619        int suffix = 1;
13620        File result;
13621        do {
13622            result = new File(targetDir, packageName + "-" + suffix);
13623            suffix++;
13624        } while (result.exists());
13625        return result;
13626    }
13627
13628    // Utility method that returns the relative package path with respect
13629    // to the installation directory. Like say for /data/data/com.test-1.apk
13630    // string com.test-1 is returned.
13631    static String deriveCodePathName(String codePath) {
13632        if (codePath == null) {
13633            return null;
13634        }
13635        final File codeFile = new File(codePath);
13636        final String name = codeFile.getName();
13637        if (codeFile.isDirectory()) {
13638            return name;
13639        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13640            final int lastDot = name.lastIndexOf('.');
13641            return name.substring(0, lastDot);
13642        } else {
13643            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13644            return null;
13645        }
13646    }
13647
13648    static class PackageInstalledInfo {
13649        String name;
13650        int uid;
13651        // The set of users that originally had this package installed.
13652        int[] origUsers;
13653        // The set of users that now have this package installed.
13654        int[] newUsers;
13655        PackageParser.Package pkg;
13656        int returnCode;
13657        String returnMsg;
13658        PackageRemovedInfo removedInfo;
13659        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13660
13661        public void setError(int code, String msg) {
13662            setReturnCode(code);
13663            setReturnMessage(msg);
13664            Slog.w(TAG, msg);
13665        }
13666
13667        public void setError(String msg, PackageParserException e) {
13668            setReturnCode(e.error);
13669            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13670            Slog.w(TAG, msg, e);
13671        }
13672
13673        public void setError(String msg, PackageManagerException e) {
13674            returnCode = e.error;
13675            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13676            Slog.w(TAG, msg, e);
13677        }
13678
13679        public void setReturnCode(int returnCode) {
13680            this.returnCode = returnCode;
13681            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13682            for (int i = 0; i < childCount; i++) {
13683                addedChildPackages.valueAt(i).returnCode = returnCode;
13684            }
13685        }
13686
13687        private void setReturnMessage(String returnMsg) {
13688            this.returnMsg = returnMsg;
13689            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13690            for (int i = 0; i < childCount; i++) {
13691                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13692            }
13693        }
13694
13695        // In some error cases we want to convey more info back to the observer
13696        String origPackage;
13697        String origPermission;
13698    }
13699
13700    /*
13701     * Install a non-existing package.
13702     */
13703    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13704            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13705            PackageInstalledInfo res) {
13706        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13707
13708        // Remember this for later, in case we need to rollback this install
13709        String pkgName = pkg.packageName;
13710
13711        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13712
13713        synchronized(mPackages) {
13714            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13715                // A package with the same name is already installed, though
13716                // it has been renamed to an older name.  The package we
13717                // are trying to install should be installed as an update to
13718                // the existing one, but that has not been requested, so bail.
13719                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13720                        + " without first uninstalling package running as "
13721                        + mSettings.mRenamedPackages.get(pkgName));
13722                return;
13723            }
13724            if (mPackages.containsKey(pkgName)) {
13725                // Don't allow installation over an existing package with the same name.
13726                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13727                        + " without first uninstalling.");
13728                return;
13729            }
13730        }
13731
13732        try {
13733            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13734                    System.currentTimeMillis(), user);
13735
13736            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13737
13738            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13739                prepareAppDataAfterInstallLIF(newPackage);
13740
13741            } else {
13742                // Remove package from internal structures, but keep around any
13743                // data that might have already existed
13744                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13745                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13746            }
13747        } catch (PackageManagerException e) {
13748            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13749        }
13750
13751        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13752    }
13753
13754    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13755        // Can't rotate keys during boot or if sharedUser.
13756        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13757                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13758            return false;
13759        }
13760        // app is using upgradeKeySets; make sure all are valid
13761        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13762        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13763        for (int i = 0; i < upgradeKeySets.length; i++) {
13764            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13765                Slog.wtf(TAG, "Package "
13766                         + (oldPs.name != null ? oldPs.name : "<null>")
13767                         + " contains upgrade-key-set reference to unknown key-set: "
13768                         + upgradeKeySets[i]
13769                         + " reverting to signatures check.");
13770                return false;
13771            }
13772        }
13773        return true;
13774    }
13775
13776    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13777        // Upgrade keysets are being used.  Determine if new package has a superset of the
13778        // required keys.
13779        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13780        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13781        for (int i = 0; i < upgradeKeySets.length; i++) {
13782            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13783            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13784                return true;
13785            }
13786        }
13787        return false;
13788    }
13789
13790    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13791            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13792        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13793
13794        final PackageParser.Package oldPackage;
13795        final String pkgName = pkg.packageName;
13796        final int[] allUsers;
13797        final int[] installedUsers;
13798
13799        // First find the old package info and check signatures
13800        synchronized(mPackages) {
13801            oldPackage = mPackages.get(pkgName);
13802            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13803            if (isEphemeral && !oldIsEphemeral) {
13804                // can't downgrade from full to ephemeral
13805                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13806                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13807                return;
13808            }
13809            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13810            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13811            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13812                if (!checkUpgradeKeySetLP(ps, pkg)) {
13813                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13814                            "New package not signed by keys specified by upgrade-keysets: "
13815                                    + pkgName);
13816                    return;
13817                }
13818            } else {
13819                // default to original signature matching
13820                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13821                        != PackageManager.SIGNATURE_MATCH) {
13822                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13823                            "New package has a different signature: " + pkgName);
13824                    return;
13825                }
13826            }
13827
13828            // Check for shared user id changes
13829            String invalidPackageName =
13830                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13831            if (invalidPackageName != null) {
13832                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13833                        "Package " + invalidPackageName + " tried to change user "
13834                                + oldPackage.mSharedUserId);
13835                return;
13836            }
13837
13838            // In case of rollback, remember per-user/profile install state
13839            allUsers = sUserManager.getUserIds();
13840            installedUsers = ps.queryInstalledUsers(allUsers, true);
13841        }
13842
13843        // Update what is removed
13844        res.removedInfo = new PackageRemovedInfo();
13845        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13846        res.removedInfo.removedPackage = oldPackage.packageName;
13847        res.removedInfo.isUpdate = true;
13848        res.removedInfo.origUsers = installedUsers;
13849        final int childCount = (oldPackage.childPackages != null)
13850                ? oldPackage.childPackages.size() : 0;
13851        for (int i = 0; i < childCount; i++) {
13852            boolean childPackageUpdated = false;
13853            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13854            if (res.addedChildPackages != null) {
13855                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13856                if (childRes != null) {
13857                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13858                    childRes.removedInfo.removedPackage = childPkg.packageName;
13859                    childRes.removedInfo.isUpdate = true;
13860                    childPackageUpdated = true;
13861                }
13862            }
13863            if (!childPackageUpdated) {
13864                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13865                childRemovedRes.removedPackage = childPkg.packageName;
13866                childRemovedRes.isUpdate = false;
13867                childRemovedRes.dataRemoved = true;
13868                synchronized (mPackages) {
13869                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13870                    if (childPs != null) {
13871                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13872                    }
13873                }
13874                if (res.removedInfo.removedChildPackages == null) {
13875                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13876                }
13877                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13878            }
13879        }
13880
13881        boolean sysPkg = (isSystemApp(oldPackage));
13882        if (sysPkg) {
13883            // Set the system/privileged flags as needed
13884            final boolean privileged =
13885                    (oldPackage.applicationInfo.privateFlags
13886                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13887            final int systemPolicyFlags = policyFlags
13888                    | PackageParser.PARSE_IS_SYSTEM
13889                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13890
13891            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13892                    user, allUsers, installerPackageName, res);
13893        } else {
13894            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13895                    user, allUsers, installerPackageName, res);
13896        }
13897    }
13898
13899    public List<String> getPreviousCodePaths(String packageName) {
13900        final PackageSetting ps = mSettings.mPackages.get(packageName);
13901        final List<String> result = new ArrayList<String>();
13902        if (ps != null && ps.oldCodePaths != null) {
13903            result.addAll(ps.oldCodePaths);
13904        }
13905        return result;
13906    }
13907
13908    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13909            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13910            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13911        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13912                + deletedPackage);
13913
13914        String pkgName = deletedPackage.packageName;
13915        boolean deletedPkg = true;
13916        boolean addedPkg = false;
13917        boolean updatedSettings = false;
13918        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13919        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13920                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13921
13922        final long origUpdateTime = (pkg.mExtras != null)
13923                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13924
13925        // First delete the existing package while retaining the data directory
13926        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13927                res.removedInfo, true, pkg)) {
13928            // If the existing package wasn't successfully deleted
13929            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13930            deletedPkg = false;
13931        } else {
13932            // Successfully deleted the old package; proceed with replace.
13933
13934            // If deleted package lived in a container, give users a chance to
13935            // relinquish resources before killing.
13936            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13937                if (DEBUG_INSTALL) {
13938                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13939                }
13940                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13941                final ArrayList<String> pkgList = new ArrayList<String>(1);
13942                pkgList.add(deletedPackage.applicationInfo.packageName);
13943                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13944            }
13945
13946            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13947                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13948            clearAppProfilesLIF(pkg);
13949
13950            try {
13951                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13952                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13953                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13954
13955                // Update the in-memory copy of the previous code paths.
13956                PackageSetting ps = mSettings.mPackages.get(pkgName);
13957                if (!killApp) {
13958                    if (ps.oldCodePaths == null) {
13959                        ps.oldCodePaths = new ArraySet<>();
13960                    }
13961                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13962                    if (deletedPackage.splitCodePaths != null) {
13963                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13964                    }
13965                } else {
13966                    ps.oldCodePaths = null;
13967                }
13968                if (ps.childPackageNames != null) {
13969                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13970                        final String childPkgName = ps.childPackageNames.get(i);
13971                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13972                        childPs.oldCodePaths = ps.oldCodePaths;
13973                    }
13974                }
13975                prepareAppDataAfterInstallLIF(newPackage);
13976                addedPkg = true;
13977            } catch (PackageManagerException e) {
13978                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13979            }
13980        }
13981
13982        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13983            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13984
13985            // Revert all internal state mutations and added folders for the failed install
13986            if (addedPkg) {
13987                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13988                        res.removedInfo, true, null);
13989            }
13990
13991            // Restore the old package
13992            if (deletedPkg) {
13993                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13994                File restoreFile = new File(deletedPackage.codePath);
13995                // Parse old package
13996                boolean oldExternal = isExternal(deletedPackage);
13997                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13998                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13999                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14000                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14001                try {
14002                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14003                            null);
14004                } catch (PackageManagerException e) {
14005                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14006                            + e.getMessage());
14007                    return;
14008                }
14009
14010                synchronized (mPackages) {
14011                    // Ensure the installer package name up to date
14012                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14013
14014                    // Update permissions for restored package
14015                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14016
14017                    mSettings.writeLPr();
14018                }
14019
14020                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14021            }
14022        } else {
14023            synchronized (mPackages) {
14024                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14025                if (ps != null) {
14026                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14027                    if (res.removedInfo.removedChildPackages != null) {
14028                        final int childCount = res.removedInfo.removedChildPackages.size();
14029                        // Iterate in reverse as we may modify the collection
14030                        for (int i = childCount - 1; i >= 0; i--) {
14031                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14032                            if (res.addedChildPackages.containsKey(childPackageName)) {
14033                                res.removedInfo.removedChildPackages.removeAt(i);
14034                            } else {
14035                                PackageRemovedInfo childInfo = res.removedInfo
14036                                        .removedChildPackages.valueAt(i);
14037                                childInfo.removedForAllUsers = mPackages.get(
14038                                        childInfo.removedPackage) == null;
14039                            }
14040                        }
14041                    }
14042                }
14043            }
14044        }
14045    }
14046
14047    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14048            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14049            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14050        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14051                + ", old=" + deletedPackage);
14052
14053        final boolean disabledSystem;
14054
14055        // Remove existing system package
14056        removePackageLI(deletedPackage, true);
14057
14058        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14059        if (!disabledSystem) {
14060            // We didn't need to disable the .apk as a current system package,
14061            // which means we are replacing another update that is already
14062            // installed.  We need to make sure to delete the older one's .apk.
14063            res.removedInfo.args = createInstallArgsForExisting(0,
14064                    deletedPackage.applicationInfo.getCodePath(),
14065                    deletedPackage.applicationInfo.getResourcePath(),
14066                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14067        } else {
14068            res.removedInfo.args = null;
14069        }
14070
14071        // Successfully disabled the old package. Now proceed with re-installation
14072        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14073                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14074        clearAppProfilesLIF(pkg);
14075
14076        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14077        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14078                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14079
14080        PackageParser.Package newPackage = null;
14081        try {
14082            // Add the package to the internal data structures
14083            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14084
14085            // Set the update and install times
14086            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14087            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14088                    System.currentTimeMillis());
14089
14090            // Update the package dynamic state if succeeded
14091            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14092                // Now that the install succeeded make sure we remove data
14093                // directories for any child package the update removed.
14094                final int deletedChildCount = (deletedPackage.childPackages != null)
14095                        ? deletedPackage.childPackages.size() : 0;
14096                final int newChildCount = (newPackage.childPackages != null)
14097                        ? newPackage.childPackages.size() : 0;
14098                for (int i = 0; i < deletedChildCount; i++) {
14099                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14100                    boolean childPackageDeleted = true;
14101                    for (int j = 0; j < newChildCount; j++) {
14102                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14103                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14104                            childPackageDeleted = false;
14105                            break;
14106                        }
14107                    }
14108                    if (childPackageDeleted) {
14109                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14110                                deletedChildPkg.packageName);
14111                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14112                            PackageRemovedInfo removedChildRes = res.removedInfo
14113                                    .removedChildPackages.get(deletedChildPkg.packageName);
14114                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14115                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14116                        }
14117                    }
14118                }
14119
14120                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14121                prepareAppDataAfterInstallLIF(newPackage);
14122            }
14123        } catch (PackageManagerException e) {
14124            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14125            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14126        }
14127
14128        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14129            // Re installation failed. Restore old information
14130            // Remove new pkg information
14131            if (newPackage != null) {
14132                removeInstalledPackageLI(newPackage, true);
14133            }
14134            // Add back the old system package
14135            try {
14136                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14137            } catch (PackageManagerException e) {
14138                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14139            }
14140
14141            synchronized (mPackages) {
14142                if (disabledSystem) {
14143                    enableSystemPackageLPw(deletedPackage);
14144                }
14145
14146                // Ensure the installer package name up to date
14147                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14148
14149                // Update permissions for restored package
14150                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14151
14152                mSettings.writeLPr();
14153            }
14154
14155            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14156                    + " after failed upgrade");
14157        }
14158    }
14159
14160    /**
14161     * Checks whether the parent or any of the child packages have a change shared
14162     * user. For a package to be a valid update the shred users of the parent and
14163     * the children should match. We may later support changing child shared users.
14164     * @param oldPkg The updated package.
14165     * @param newPkg The update package.
14166     * @return The shared user that change between the versions.
14167     */
14168    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14169            PackageParser.Package newPkg) {
14170        // Check parent shared user
14171        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14172            return newPkg.packageName;
14173        }
14174        // Check child shared users
14175        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14176        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14177        for (int i = 0; i < newChildCount; i++) {
14178            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14179            // If this child was present, did it have the same shared user?
14180            for (int j = 0; j < oldChildCount; j++) {
14181                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14182                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14183                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14184                    return newChildPkg.packageName;
14185                }
14186            }
14187        }
14188        return null;
14189    }
14190
14191    private void removeNativeBinariesLI(PackageSetting ps) {
14192        // Remove the lib path for the parent package
14193        if (ps != null) {
14194            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14195            // Remove the lib path for the child packages
14196            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14197            for (int i = 0; i < childCount; i++) {
14198                PackageSetting childPs = null;
14199                synchronized (mPackages) {
14200                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14201                }
14202                if (childPs != null) {
14203                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14204                            .legacyNativeLibraryPathString);
14205                }
14206            }
14207        }
14208    }
14209
14210    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14211        // Enable the parent package
14212        mSettings.enableSystemPackageLPw(pkg.packageName);
14213        // Enable the child packages
14214        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14215        for (int i = 0; i < childCount; i++) {
14216            PackageParser.Package childPkg = pkg.childPackages.get(i);
14217            mSettings.enableSystemPackageLPw(childPkg.packageName);
14218        }
14219    }
14220
14221    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14222            PackageParser.Package newPkg) {
14223        // Disable the parent package (parent always replaced)
14224        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14225        // Disable the child packages
14226        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14227        for (int i = 0; i < childCount; i++) {
14228            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14229            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14230            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14231        }
14232        return disabled;
14233    }
14234
14235    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14236            String installerPackageName) {
14237        // Enable the parent package
14238        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14239        // Enable the child packages
14240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14241        for (int i = 0; i < childCount; i++) {
14242            PackageParser.Package childPkg = pkg.childPackages.get(i);
14243            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14244        }
14245    }
14246
14247    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14248        // Collect all used permissions in the UID
14249        ArraySet<String> usedPermissions = new ArraySet<>();
14250        final int packageCount = su.packages.size();
14251        for (int i = 0; i < packageCount; i++) {
14252            PackageSetting ps = su.packages.valueAt(i);
14253            if (ps.pkg == null) {
14254                continue;
14255            }
14256            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14257            for (int j = 0; j < requestedPermCount; j++) {
14258                String permission = ps.pkg.requestedPermissions.get(j);
14259                BasePermission bp = mSettings.mPermissions.get(permission);
14260                if (bp != null) {
14261                    usedPermissions.add(permission);
14262                }
14263            }
14264        }
14265
14266        PermissionsState permissionsState = su.getPermissionsState();
14267        // Prune install permissions
14268        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14269        final int installPermCount = installPermStates.size();
14270        for (int i = installPermCount - 1; i >= 0;  i--) {
14271            PermissionState permissionState = installPermStates.get(i);
14272            if (!usedPermissions.contains(permissionState.getName())) {
14273                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14274                if (bp != null) {
14275                    permissionsState.revokeInstallPermission(bp);
14276                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14277                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14278                }
14279            }
14280        }
14281
14282        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14283
14284        // Prune runtime permissions
14285        for (int userId : allUserIds) {
14286            List<PermissionState> runtimePermStates = permissionsState
14287                    .getRuntimePermissionStates(userId);
14288            final int runtimePermCount = runtimePermStates.size();
14289            for (int i = runtimePermCount - 1; i >= 0; i--) {
14290                PermissionState permissionState = runtimePermStates.get(i);
14291                if (!usedPermissions.contains(permissionState.getName())) {
14292                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14293                    if (bp != null) {
14294                        permissionsState.revokeRuntimePermission(bp, userId);
14295                        permissionsState.updatePermissionFlags(bp, userId,
14296                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14297                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14298                                runtimePermissionChangedUserIds, userId);
14299                    }
14300                }
14301            }
14302        }
14303
14304        return runtimePermissionChangedUserIds;
14305    }
14306
14307    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14308            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14309        // Update the parent package setting
14310        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14311                res, user);
14312        // Update the child packages setting
14313        final int childCount = (newPackage.childPackages != null)
14314                ? newPackage.childPackages.size() : 0;
14315        for (int i = 0; i < childCount; i++) {
14316            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14317            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14318            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14319                    childRes.origUsers, childRes, user);
14320        }
14321    }
14322
14323    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14324            String installerPackageName, int[] allUsers, int[] installedForUsers,
14325            PackageInstalledInfo res, UserHandle user) {
14326        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14327
14328        String pkgName = newPackage.packageName;
14329        synchronized (mPackages) {
14330            //write settings. the installStatus will be incomplete at this stage.
14331            //note that the new package setting would have already been
14332            //added to mPackages. It hasn't been persisted yet.
14333            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14335            mSettings.writeLPr();
14336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14337        }
14338
14339        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14340        synchronized (mPackages) {
14341            updatePermissionsLPw(newPackage.packageName, newPackage,
14342                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14343                            ? UPDATE_PERMISSIONS_ALL : 0));
14344            // For system-bundled packages, we assume that installing an upgraded version
14345            // of the package implies that the user actually wants to run that new code,
14346            // so we enable the package.
14347            PackageSetting ps = mSettings.mPackages.get(pkgName);
14348            final int userId = user.getIdentifier();
14349            if (ps != null) {
14350                if (isSystemApp(newPackage)) {
14351                    if (DEBUG_INSTALL) {
14352                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14353                    }
14354                    // Enable system package for requested users
14355                    if (res.origUsers != null) {
14356                        for (int origUserId : res.origUsers) {
14357                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14358                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14359                                        origUserId, installerPackageName);
14360                            }
14361                        }
14362                    }
14363                    // Also convey the prior install/uninstall state
14364                    if (allUsers != null && installedForUsers != null) {
14365                        for (int currentUserId : allUsers) {
14366                            final boolean installed = ArrayUtils.contains(
14367                                    installedForUsers, currentUserId);
14368                            if (DEBUG_INSTALL) {
14369                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14370                            }
14371                            ps.setInstalled(installed, currentUserId);
14372                        }
14373                        // these install state changes will be persisted in the
14374                        // upcoming call to mSettings.writeLPr().
14375                    }
14376                }
14377                // It's implied that when a user requests installation, they want the app to be
14378                // installed and enabled.
14379                if (userId != UserHandle.USER_ALL) {
14380                    ps.setInstalled(true, userId);
14381                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14382                }
14383            }
14384            res.name = pkgName;
14385            res.uid = newPackage.applicationInfo.uid;
14386            res.pkg = newPackage;
14387            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14388            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14389            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14390            //to update install status
14391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14392            mSettings.writeLPr();
14393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14394        }
14395
14396        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14397    }
14398
14399    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14400        try {
14401            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14402            installPackageLI(args, res);
14403        } finally {
14404            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14405        }
14406    }
14407
14408    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14409        final int installFlags = args.installFlags;
14410        final String installerPackageName = args.installerPackageName;
14411        final String volumeUuid = args.volumeUuid;
14412        final File tmpPackageFile = new File(args.getCodePath());
14413        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14414        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14415                || (args.volumeUuid != null));
14416        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14417        boolean replace = false;
14418        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14419        if (args.move != null) {
14420            // moving a complete application; perform an initial scan on the new install location
14421            scanFlags |= SCAN_INITIAL;
14422        }
14423        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14424            scanFlags |= SCAN_DONT_KILL_APP;
14425        }
14426
14427        // Result object to be returned
14428        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14429
14430        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14431
14432        // Sanity check
14433        if (ephemeral && (forwardLocked || onExternal)) {
14434            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14435                    + " external=" + onExternal);
14436            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14437            return;
14438        }
14439
14440        // Retrieve PackageSettings and parse package
14441        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14442                | PackageParser.PARSE_ENFORCE_CODE
14443                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14444                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14445                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14446        PackageParser pp = new PackageParser();
14447        pp.setSeparateProcesses(mSeparateProcesses);
14448        pp.setDisplayMetrics(mMetrics);
14449
14450        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14451        final PackageParser.Package pkg;
14452        try {
14453            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14454        } catch (PackageParserException e) {
14455            res.setError("Failed parse during installPackageLI", e);
14456            return;
14457        } finally {
14458            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14459        }
14460
14461        // If we are installing a clustered package add results for the children
14462        if (pkg.childPackages != null) {
14463            synchronized (mPackages) {
14464                final int childCount = pkg.childPackages.size();
14465                for (int i = 0; i < childCount; i++) {
14466                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14467                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14468                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14469                    childRes.pkg = childPkg;
14470                    childRes.name = childPkg.packageName;
14471                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14472                    if (childPs != null) {
14473                        childRes.origUsers = childPs.queryInstalledUsers(
14474                                sUserManager.getUserIds(), true);
14475                    }
14476                    if ((mPackages.containsKey(childPkg.packageName))) {
14477                        childRes.removedInfo = new PackageRemovedInfo();
14478                        childRes.removedInfo.removedPackage = childPkg.packageName;
14479                    }
14480                    if (res.addedChildPackages == null) {
14481                        res.addedChildPackages = new ArrayMap<>();
14482                    }
14483                    res.addedChildPackages.put(childPkg.packageName, childRes);
14484                }
14485            }
14486        }
14487
14488        // If package doesn't declare API override, mark that we have an install
14489        // time CPU ABI override.
14490        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14491            pkg.cpuAbiOverride = args.abiOverride;
14492        }
14493
14494        String pkgName = res.name = pkg.packageName;
14495        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14496            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14497                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14498                return;
14499            }
14500        }
14501
14502        try {
14503            // either use what we've been given or parse directly from the APK
14504            if (args.certificates != null) {
14505                try {
14506                    PackageParser.populateCertificates(pkg, args.certificates);
14507                } catch (PackageParserException e) {
14508                    // there was something wrong with the certificates we were given;
14509                    // try to pull them from the APK
14510                    PackageParser.collectCertificates(pkg, parseFlags);
14511                }
14512            } else {
14513                PackageParser.collectCertificates(pkg, parseFlags);
14514            }
14515        } catch (PackageParserException e) {
14516            res.setError("Failed collect during installPackageLI", e);
14517            return;
14518        }
14519
14520        // Get rid of all references to package scan path via parser.
14521        pp = null;
14522        String oldCodePath = null;
14523        boolean systemApp = false;
14524        synchronized (mPackages) {
14525            // Check if installing already existing package
14526            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14527                String oldName = mSettings.mRenamedPackages.get(pkgName);
14528                if (pkg.mOriginalPackages != null
14529                        && pkg.mOriginalPackages.contains(oldName)
14530                        && mPackages.containsKey(oldName)) {
14531                    // This package is derived from an original package,
14532                    // and this device has been updating from that original
14533                    // name.  We must continue using the original name, so
14534                    // rename the new package here.
14535                    pkg.setPackageName(oldName);
14536                    pkgName = pkg.packageName;
14537                    replace = true;
14538                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14539                            + oldName + " pkgName=" + pkgName);
14540                } else if (mPackages.containsKey(pkgName)) {
14541                    // This package, under its official name, already exists
14542                    // on the device; we should replace it.
14543                    replace = true;
14544                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14545                }
14546
14547                // Child packages are installed through the parent package
14548                if (pkg.parentPackage != null) {
14549                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14550                            "Package " + pkg.packageName + " is child of package "
14551                                    + pkg.parentPackage.parentPackage + ". Child packages "
14552                                    + "can be updated only through the parent package.");
14553                    return;
14554                }
14555
14556                if (replace) {
14557                    // Prevent apps opting out from runtime permissions
14558                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14559                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14560                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14561                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14562                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14563                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14564                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14565                                        + " doesn't support runtime permissions but the old"
14566                                        + " target SDK " + oldTargetSdk + " does.");
14567                        return;
14568                    }
14569
14570                    // Prevent installing of child packages
14571                    if (oldPackage.parentPackage != null) {
14572                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14573                                "Package " + pkg.packageName + " is child of package "
14574                                        + oldPackage.parentPackage + ". Child packages "
14575                                        + "can be updated only through the parent package.");
14576                        return;
14577                    }
14578                }
14579            }
14580
14581            PackageSetting ps = mSettings.mPackages.get(pkgName);
14582            if (ps != null) {
14583                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14584
14585                // Quick sanity check that we're signed correctly if updating;
14586                // we'll check this again later when scanning, but we want to
14587                // bail early here before tripping over redefined permissions.
14588                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14589                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14590                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14591                                + pkg.packageName + " upgrade keys do not match the "
14592                                + "previously installed version");
14593                        return;
14594                    }
14595                } else {
14596                    try {
14597                        verifySignaturesLP(ps, pkg);
14598                    } catch (PackageManagerException e) {
14599                        res.setError(e.error, e.getMessage());
14600                        return;
14601                    }
14602                }
14603
14604                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14605                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14606                    systemApp = (ps.pkg.applicationInfo.flags &
14607                            ApplicationInfo.FLAG_SYSTEM) != 0;
14608                }
14609                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14610            }
14611
14612            // Check whether the newly-scanned package wants to define an already-defined perm
14613            int N = pkg.permissions.size();
14614            for (int i = N-1; i >= 0; i--) {
14615                PackageParser.Permission perm = pkg.permissions.get(i);
14616                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14617                if (bp != null) {
14618                    // If the defining package is signed with our cert, it's okay.  This
14619                    // also includes the "updating the same package" case, of course.
14620                    // "updating same package" could also involve key-rotation.
14621                    final boolean sigsOk;
14622                    if (bp.sourcePackage.equals(pkg.packageName)
14623                            && (bp.packageSetting instanceof PackageSetting)
14624                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14625                                    scanFlags))) {
14626                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14627                    } else {
14628                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14629                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14630                    }
14631                    if (!sigsOk) {
14632                        // If the owning package is the system itself, we log but allow
14633                        // install to proceed; we fail the install on all other permission
14634                        // redefinitions.
14635                        if (!bp.sourcePackage.equals("android")) {
14636                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14637                                    + pkg.packageName + " attempting to redeclare permission "
14638                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14639                            res.origPermission = perm.info.name;
14640                            res.origPackage = bp.sourcePackage;
14641                            return;
14642                        } else {
14643                            Slog.w(TAG, "Package " + pkg.packageName
14644                                    + " attempting to redeclare system permission "
14645                                    + perm.info.name + "; ignoring new declaration");
14646                            pkg.permissions.remove(i);
14647                        }
14648                    }
14649                }
14650            }
14651        }
14652
14653        if (systemApp) {
14654            if (onExternal) {
14655                // Abort update; system app can't be replaced with app on sdcard
14656                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14657                        "Cannot install updates to system apps on sdcard");
14658                return;
14659            } else if (ephemeral) {
14660                // Abort update; system app can't be replaced with an ephemeral app
14661                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14662                        "Cannot update a system app with an ephemeral app");
14663                return;
14664            }
14665        }
14666
14667        if (args.move != null) {
14668            // We did an in-place move, so dex is ready to roll
14669            scanFlags |= SCAN_NO_DEX;
14670            scanFlags |= SCAN_MOVE;
14671
14672            synchronized (mPackages) {
14673                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14674                if (ps == null) {
14675                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14676                            "Missing settings for moved package " + pkgName);
14677                }
14678
14679                // We moved the entire application as-is, so bring over the
14680                // previously derived ABI information.
14681                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14682                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14683            }
14684
14685        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14686            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14687            scanFlags |= SCAN_NO_DEX;
14688
14689            try {
14690                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14691                    args.abiOverride : pkg.cpuAbiOverride);
14692                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14693                        true /* extract libs */);
14694            } catch (PackageManagerException pme) {
14695                Slog.e(TAG, "Error deriving application ABI", pme);
14696                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14697                return;
14698            }
14699
14700            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14701            // Do not run PackageDexOptimizer through the local performDexOpt
14702            // method because `pkg` is not in `mPackages` yet.
14703            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14704                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14706            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14707                String msg = "Extracting package failed for " + pkgName;
14708                res.setError(INSTALL_FAILED_DEXOPT, msg);
14709                return;
14710            }
14711
14712            // Notify BackgroundDexOptService that the package has been changed.
14713            // If this is an update of a package which used to fail to compile,
14714            // BDOS will remove it from its blacklist.
14715            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14716        }
14717
14718        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14719            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14720            return;
14721        }
14722
14723        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14724
14725        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14726                "installPackageLI")) {
14727            if (replace) {
14728                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14729                        installerPackageName, res);
14730            } else {
14731                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14732                        args.user, installerPackageName, volumeUuid, res);
14733            }
14734        }
14735        synchronized (mPackages) {
14736            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14737            if (ps != null) {
14738                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14739            }
14740
14741            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14742            for (int i = 0; i < childCount; i++) {
14743                PackageParser.Package childPkg = pkg.childPackages.get(i);
14744                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14745                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14746                if (childPs != null) {
14747                    childRes.newUsers = childPs.queryInstalledUsers(
14748                            sUserManager.getUserIds(), true);
14749                }
14750            }
14751        }
14752    }
14753
14754    private void startIntentFilterVerifications(int userId, boolean replacing,
14755            PackageParser.Package pkg) {
14756        if (mIntentFilterVerifierComponent == null) {
14757            Slog.w(TAG, "No IntentFilter verification will not be done as "
14758                    + "there is no IntentFilterVerifier available!");
14759            return;
14760        }
14761
14762        final int verifierUid = getPackageUid(
14763                mIntentFilterVerifierComponent.getPackageName(),
14764                MATCH_DEBUG_TRIAGED_MISSING,
14765                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14766
14767        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14768        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14769        mHandler.sendMessage(msg);
14770
14771        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14772        for (int i = 0; i < childCount; i++) {
14773            PackageParser.Package childPkg = pkg.childPackages.get(i);
14774            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14775            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14776            mHandler.sendMessage(msg);
14777        }
14778    }
14779
14780    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14781            PackageParser.Package pkg) {
14782        int size = pkg.activities.size();
14783        if (size == 0) {
14784            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14785                    "No activity, so no need to verify any IntentFilter!");
14786            return;
14787        }
14788
14789        final boolean hasDomainURLs = hasDomainURLs(pkg);
14790        if (!hasDomainURLs) {
14791            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14792                    "No domain URLs, so no need to verify any IntentFilter!");
14793            return;
14794        }
14795
14796        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14797                + " if any IntentFilter from the " + size
14798                + " Activities needs verification ...");
14799
14800        int count = 0;
14801        final String packageName = pkg.packageName;
14802
14803        synchronized (mPackages) {
14804            // If this is a new install and we see that we've already run verification for this
14805            // package, we have nothing to do: it means the state was restored from backup.
14806            if (!replacing) {
14807                IntentFilterVerificationInfo ivi =
14808                        mSettings.getIntentFilterVerificationLPr(packageName);
14809                if (ivi != null) {
14810                    if (DEBUG_DOMAIN_VERIFICATION) {
14811                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14812                                + ivi.getStatusString());
14813                    }
14814                    return;
14815                }
14816            }
14817
14818            // If any filters need to be verified, then all need to be.
14819            boolean needToVerify = false;
14820            for (PackageParser.Activity a : pkg.activities) {
14821                for (ActivityIntentInfo filter : a.intents) {
14822                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14823                        if (DEBUG_DOMAIN_VERIFICATION) {
14824                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14825                        }
14826                        needToVerify = true;
14827                        break;
14828                    }
14829                }
14830            }
14831
14832            if (needToVerify) {
14833                final int verificationId = mIntentFilterVerificationToken++;
14834                for (PackageParser.Activity a : pkg.activities) {
14835                    for (ActivityIntentInfo filter : a.intents) {
14836                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14837                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14838                                    "Verification needed for IntentFilter:" + filter.toString());
14839                            mIntentFilterVerifier.addOneIntentFilterVerification(
14840                                    verifierUid, userId, verificationId, filter, packageName);
14841                            count++;
14842                        }
14843                    }
14844                }
14845            }
14846        }
14847
14848        if (count > 0) {
14849            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14850                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14851                    +  " for userId:" + userId);
14852            mIntentFilterVerifier.startVerifications(userId);
14853        } else {
14854            if (DEBUG_DOMAIN_VERIFICATION) {
14855                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14856            }
14857        }
14858    }
14859
14860    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14861        final ComponentName cn  = filter.activity.getComponentName();
14862        final String packageName = cn.getPackageName();
14863
14864        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14865                packageName);
14866        if (ivi == null) {
14867            return true;
14868        }
14869        int status = ivi.getStatus();
14870        switch (status) {
14871            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14872            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14873                return true;
14874
14875            default:
14876                // Nothing to do
14877                return false;
14878        }
14879    }
14880
14881    private static boolean isMultiArch(ApplicationInfo info) {
14882        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14883    }
14884
14885    private static boolean isExternal(PackageParser.Package pkg) {
14886        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14887    }
14888
14889    private static boolean isExternal(PackageSetting ps) {
14890        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14891    }
14892
14893    private static boolean isEphemeral(PackageParser.Package pkg) {
14894        return pkg.applicationInfo.isEphemeralApp();
14895    }
14896
14897    private static boolean isEphemeral(PackageSetting ps) {
14898        return ps.pkg != null && isEphemeral(ps.pkg);
14899    }
14900
14901    private static boolean isSystemApp(PackageParser.Package pkg) {
14902        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14903    }
14904
14905    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14906        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14907    }
14908
14909    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14910        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14911    }
14912
14913    private static boolean isSystemApp(PackageSetting ps) {
14914        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14915    }
14916
14917    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14918        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14919    }
14920
14921    private int packageFlagsToInstallFlags(PackageSetting ps) {
14922        int installFlags = 0;
14923        if (isEphemeral(ps)) {
14924            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14925        }
14926        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14927            // This existing package was an external ASEC install when we have
14928            // the external flag without a UUID
14929            installFlags |= PackageManager.INSTALL_EXTERNAL;
14930        }
14931        if (ps.isForwardLocked()) {
14932            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14933        }
14934        return installFlags;
14935    }
14936
14937    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14938        if (isExternal(pkg)) {
14939            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14940                return StorageManager.UUID_PRIMARY_PHYSICAL;
14941            } else {
14942                return pkg.volumeUuid;
14943            }
14944        } else {
14945            return StorageManager.UUID_PRIVATE_INTERNAL;
14946        }
14947    }
14948
14949    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14950        if (isExternal(pkg)) {
14951            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14952                return mSettings.getExternalVersion();
14953            } else {
14954                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14955            }
14956        } else {
14957            return mSettings.getInternalVersion();
14958        }
14959    }
14960
14961    private void deleteTempPackageFiles() {
14962        final FilenameFilter filter = new FilenameFilter() {
14963            public boolean accept(File dir, String name) {
14964                return name.startsWith("vmdl") && name.endsWith(".tmp");
14965            }
14966        };
14967        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14968            file.delete();
14969        }
14970    }
14971
14972    @Override
14973    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14974            int flags) {
14975        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14976                flags);
14977    }
14978
14979    @Override
14980    public void deletePackage(final String packageName,
14981            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14982        mContext.enforceCallingOrSelfPermission(
14983                android.Manifest.permission.DELETE_PACKAGES, null);
14984        Preconditions.checkNotNull(packageName);
14985        Preconditions.checkNotNull(observer);
14986        final int uid = Binder.getCallingUid();
14987        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
14988        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14989        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14990            mContext.enforceCallingOrSelfPermission(
14991                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14992                    "deletePackage for user " + userId);
14993        }
14994
14995        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14996            try {
14997                observer.onPackageDeleted(packageName,
14998                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14999            } catch (RemoteException re) {
15000            }
15001            return;
15002        }
15003
15004        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15005            try {
15006                observer.onPackageDeleted(packageName,
15007                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15008            } catch (RemoteException re) {
15009            }
15010            return;
15011        }
15012
15013        if (DEBUG_REMOVE) {
15014            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15015                    + " deleteAllUsers: " + deleteAllUsers );
15016        }
15017        // Queue up an async operation since the package deletion may take a little while.
15018        mHandler.post(new Runnable() {
15019            public void run() {
15020                mHandler.removeCallbacks(this);
15021                int returnCode;
15022                if (!deleteAllUsers) {
15023                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15024                } else {
15025                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15026                    // If nobody is blocking uninstall, proceed with delete for all users
15027                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15028                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15029                    } else {
15030                        // Otherwise uninstall individually for users with blockUninstalls=false
15031                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15032                        for (int userId : users) {
15033                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15034                                returnCode = deletePackageX(packageName, userId, userFlags);
15035                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15036                                    Slog.w(TAG, "Package delete failed for user " + userId
15037                                            + ", returnCode " + returnCode);
15038                                }
15039                            }
15040                        }
15041                        // The app has only been marked uninstalled for certain users.
15042                        // We still need to report that delete was blocked
15043                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15044                    }
15045                }
15046                try {
15047                    observer.onPackageDeleted(packageName, returnCode, null);
15048                } catch (RemoteException e) {
15049                    Log.i(TAG, "Observer no longer exists.");
15050                } //end catch
15051            } //end run
15052        });
15053    }
15054
15055    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15056        int[] result = EMPTY_INT_ARRAY;
15057        for (int userId : userIds) {
15058            if (getBlockUninstallForUser(packageName, userId)) {
15059                result = ArrayUtils.appendInt(result, userId);
15060            }
15061        }
15062        return result;
15063    }
15064
15065    @Override
15066    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15067        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15068    }
15069
15070    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15071        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15072                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15073        try {
15074            if (dpm != null) {
15075                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15076                        /* callingUserOnly =*/ false);
15077                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15078                        : deviceOwnerComponentName.getPackageName();
15079                // Does the package contains the device owner?
15080                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15081                // this check is probably not needed, since DO should be registered as a device
15082                // admin on some user too. (Original bug for this: b/17657954)
15083                if (packageName.equals(deviceOwnerPackageName)) {
15084                    return true;
15085                }
15086                // Does it contain a device admin for any user?
15087                int[] users;
15088                if (userId == UserHandle.USER_ALL) {
15089                    users = sUserManager.getUserIds();
15090                } else {
15091                    users = new int[]{userId};
15092                }
15093                for (int i = 0; i < users.length; ++i) {
15094                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15095                        return true;
15096                    }
15097                }
15098            }
15099        } catch (RemoteException e) {
15100        }
15101        return false;
15102    }
15103
15104    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15105        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15106    }
15107
15108    /**
15109     *  This method is an internal method that could be get invoked either
15110     *  to delete an installed package or to clean up a failed installation.
15111     *  After deleting an installed package, a broadcast is sent to notify any
15112     *  listeners that the package has been removed. For cleaning up a failed
15113     *  installation, the broadcast is not necessary since the package's
15114     *  installation wouldn't have sent the initial broadcast either
15115     *  The key steps in deleting a package are
15116     *  deleting the package information in internal structures like mPackages,
15117     *  deleting the packages base directories through installd
15118     *  updating mSettings to reflect current status
15119     *  persisting settings for later use
15120     *  sending a broadcast if necessary
15121     */
15122    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15123        final PackageRemovedInfo info = new PackageRemovedInfo();
15124        final boolean res;
15125
15126        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15127                ? UserHandle.ALL : new UserHandle(userId);
15128
15129        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15130            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15131            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15132        }
15133
15134        PackageSetting uninstalledPs = null;
15135
15136        // for the uninstall-updates case and restricted profiles, remember the per-
15137        // user handle installed state
15138        int[] allUsers;
15139        synchronized (mPackages) {
15140            uninstalledPs = mSettings.mPackages.get(packageName);
15141            if (uninstalledPs == null) {
15142                Slog.w(TAG, "Not removing non-existent package " + packageName);
15143                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15144            }
15145            allUsers = sUserManager.getUserIds();
15146            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15147        }
15148
15149        synchronized (mInstallLock) {
15150            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15151            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15152                    "deletePackageX")) {
15153                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15154                        deleteFlags | REMOVE_CHATTY, info, true, null);
15155            }
15156            synchronized (mPackages) {
15157                if (res) {
15158                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15159                }
15160            }
15161        }
15162
15163        if (res) {
15164            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15165            info.sendPackageRemovedBroadcasts(killApp);
15166            info.sendSystemPackageUpdatedBroadcasts();
15167            info.sendSystemPackageAppearedBroadcasts();
15168        }
15169        // Force a gc here.
15170        Runtime.getRuntime().gc();
15171        // Delete the resources here after sending the broadcast to let
15172        // other processes clean up before deleting resources.
15173        if (info.args != null) {
15174            synchronized (mInstallLock) {
15175                info.args.doPostDeleteLI(true);
15176            }
15177        }
15178
15179        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15180    }
15181
15182    class PackageRemovedInfo {
15183        String removedPackage;
15184        int uid = -1;
15185        int removedAppId = -1;
15186        int[] origUsers;
15187        int[] removedUsers = null;
15188        boolean isRemovedPackageSystemUpdate = false;
15189        boolean isUpdate;
15190        boolean dataRemoved;
15191        boolean removedForAllUsers;
15192        // Clean up resources deleted packages.
15193        InstallArgs args = null;
15194        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15195        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15196
15197        void sendPackageRemovedBroadcasts(boolean killApp) {
15198            sendPackageRemovedBroadcastInternal(killApp);
15199            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15200            for (int i = 0; i < childCount; i++) {
15201                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15202                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15203            }
15204        }
15205
15206        void sendSystemPackageUpdatedBroadcasts() {
15207            if (isRemovedPackageSystemUpdate) {
15208                sendSystemPackageUpdatedBroadcastsInternal();
15209                final int childCount = (removedChildPackages != null)
15210                        ? removedChildPackages.size() : 0;
15211                for (int i = 0; i < childCount; i++) {
15212                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15213                    if (childInfo.isRemovedPackageSystemUpdate) {
15214                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15215                    }
15216                }
15217            }
15218        }
15219
15220        void sendSystemPackageAppearedBroadcasts() {
15221            final int packageCount = (appearedChildPackages != null)
15222                    ? appearedChildPackages.size() : 0;
15223            for (int i = 0; i < packageCount; i++) {
15224                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15225                for (int userId : installedInfo.newUsers) {
15226                    sendPackageAddedForUser(installedInfo.name, true,
15227                            UserHandle.getAppId(installedInfo.uid), userId);
15228                }
15229            }
15230        }
15231
15232        private void sendSystemPackageUpdatedBroadcastsInternal() {
15233            Bundle extras = new Bundle(2);
15234            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15235            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15236            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15237                    extras, 0, null, null, null);
15238            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15239                    extras, 0, null, null, null);
15240            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15241                    null, 0, removedPackage, null, null);
15242        }
15243
15244        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15245            Bundle extras = new Bundle(2);
15246            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15247            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15248            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15249            if (isUpdate || isRemovedPackageSystemUpdate) {
15250                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15251            }
15252            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15253            if (removedPackage != null) {
15254                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15255                        extras, 0, null, null, removedUsers);
15256                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15257                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15258                            removedPackage, extras, 0, null, null, removedUsers);
15259                }
15260            }
15261            if (removedAppId >= 0) {
15262                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15263                        removedUsers);
15264            }
15265        }
15266    }
15267
15268    /*
15269     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15270     * flag is not set, the data directory is removed as well.
15271     * make sure this flag is set for partially installed apps. If not its meaningless to
15272     * delete a partially installed application.
15273     */
15274    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15275            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15276        String packageName = ps.name;
15277        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15278        // Retrieve object to delete permissions for shared user later on
15279        final PackageParser.Package deletedPkg;
15280        final PackageSetting deletedPs;
15281        // reader
15282        synchronized (mPackages) {
15283            deletedPkg = mPackages.get(packageName);
15284            deletedPs = mSettings.mPackages.get(packageName);
15285            if (outInfo != null) {
15286                outInfo.removedPackage = packageName;
15287                outInfo.removedUsers = deletedPs != null
15288                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15289                        : null;
15290            }
15291        }
15292
15293        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15294
15295        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15296            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15297                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15298            destroyAppProfilesLIF(deletedPkg);
15299            if (outInfo != null) {
15300                outInfo.dataRemoved = true;
15301            }
15302            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15303        }
15304
15305        // writer
15306        synchronized (mPackages) {
15307            if (deletedPs != null) {
15308                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15309                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15310                    clearDefaultBrowserIfNeeded(packageName);
15311                    if (outInfo != null) {
15312                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15313                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15314                    }
15315                    updatePermissionsLPw(deletedPs.name, null, 0);
15316                    if (deletedPs.sharedUser != null) {
15317                        // Remove permissions associated with package. Since runtime
15318                        // permissions are per user we have to kill the removed package
15319                        // or packages running under the shared user of the removed
15320                        // package if revoking the permissions requested only by the removed
15321                        // package is successful and this causes a change in gids.
15322                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15323                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15324                                    userId);
15325                            if (userIdToKill == UserHandle.USER_ALL
15326                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15327                                // If gids changed for this user, kill all affected packages.
15328                                mHandler.post(new Runnable() {
15329                                    @Override
15330                                    public void run() {
15331                                        // This has to happen with no lock held.
15332                                        killApplication(deletedPs.name, deletedPs.appId,
15333                                                KILL_APP_REASON_GIDS_CHANGED);
15334                                    }
15335                                });
15336                                break;
15337                            }
15338                        }
15339                    }
15340                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15341                }
15342                // make sure to preserve per-user disabled state if this removal was just
15343                // a downgrade of a system app to the factory package
15344                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15345                    if (DEBUG_REMOVE) {
15346                        Slog.d(TAG, "Propagating install state across downgrade");
15347                    }
15348                    for (int userId : allUserHandles) {
15349                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15350                        if (DEBUG_REMOVE) {
15351                            Slog.d(TAG, "    user " + userId + " => " + installed);
15352                        }
15353                        ps.setInstalled(installed, userId);
15354                    }
15355                }
15356            }
15357            // can downgrade to reader
15358            if (writeSettings) {
15359                // Save settings now
15360                mSettings.writeLPr();
15361            }
15362        }
15363        if (outInfo != null) {
15364            // A user ID was deleted here. Go through all users and remove it
15365            // from KeyStore.
15366            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15367        }
15368    }
15369
15370    static boolean locationIsPrivileged(File path) {
15371        try {
15372            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15373                    .getCanonicalPath();
15374            return path.getCanonicalPath().startsWith(privilegedAppDir);
15375        } catch (IOException e) {
15376            Slog.e(TAG, "Unable to access code path " + path);
15377        }
15378        return false;
15379    }
15380
15381    /*
15382     * Tries to delete system package.
15383     */
15384    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15385            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15386            boolean writeSettings) {
15387        if (deletedPs.parentPackageName != null) {
15388            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15389            return false;
15390        }
15391
15392        final boolean applyUserRestrictions
15393                = (allUserHandles != null) && (outInfo.origUsers != null);
15394        final PackageSetting disabledPs;
15395        // Confirm if the system package has been updated
15396        // An updated system app can be deleted. This will also have to restore
15397        // the system pkg from system partition
15398        // reader
15399        synchronized (mPackages) {
15400            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15401        }
15402
15403        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15404                + " disabledPs=" + disabledPs);
15405
15406        if (disabledPs == null) {
15407            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15408            return false;
15409        } else if (DEBUG_REMOVE) {
15410            Slog.d(TAG, "Deleting system pkg from data partition");
15411        }
15412
15413        if (DEBUG_REMOVE) {
15414            if (applyUserRestrictions) {
15415                Slog.d(TAG, "Remembering install states:");
15416                for (int userId : allUserHandles) {
15417                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15418                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15419                }
15420            }
15421        }
15422
15423        // Delete the updated package
15424        outInfo.isRemovedPackageSystemUpdate = true;
15425        if (outInfo.removedChildPackages != null) {
15426            final int childCount = (deletedPs.childPackageNames != null)
15427                    ? deletedPs.childPackageNames.size() : 0;
15428            for (int i = 0; i < childCount; i++) {
15429                String childPackageName = deletedPs.childPackageNames.get(i);
15430                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15431                        .contains(childPackageName)) {
15432                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15433                            childPackageName);
15434                    if (childInfo != null) {
15435                        childInfo.isRemovedPackageSystemUpdate = true;
15436                    }
15437                }
15438            }
15439        }
15440
15441        if (disabledPs.versionCode < deletedPs.versionCode) {
15442            // Delete data for downgrades
15443            flags &= ~PackageManager.DELETE_KEEP_DATA;
15444        } else {
15445            // Preserve data by setting flag
15446            flags |= PackageManager.DELETE_KEEP_DATA;
15447        }
15448
15449        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15450                outInfo, writeSettings, disabledPs.pkg);
15451        if (!ret) {
15452            return false;
15453        }
15454
15455        // writer
15456        synchronized (mPackages) {
15457            // Reinstate the old system package
15458            enableSystemPackageLPw(disabledPs.pkg);
15459            // Remove any native libraries from the upgraded package.
15460            removeNativeBinariesLI(deletedPs);
15461        }
15462
15463        // Install the system package
15464        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15465        int parseFlags = mDefParseFlags
15466                | PackageParser.PARSE_MUST_BE_APK
15467                | PackageParser.PARSE_IS_SYSTEM
15468                | PackageParser.PARSE_IS_SYSTEM_DIR;
15469        if (locationIsPrivileged(disabledPs.codePath)) {
15470            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15471        }
15472
15473        final PackageParser.Package newPkg;
15474        try {
15475            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15476        } catch (PackageManagerException e) {
15477            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15478                    + e.getMessage());
15479            return false;
15480        }
15481
15482        prepareAppDataAfterInstallLIF(newPkg);
15483
15484        // writer
15485        synchronized (mPackages) {
15486            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15487
15488            // Propagate the permissions state as we do not want to drop on the floor
15489            // runtime permissions. The update permissions method below will take
15490            // care of removing obsolete permissions and grant install permissions.
15491            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15492            updatePermissionsLPw(newPkg.packageName, newPkg,
15493                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15494
15495            if (applyUserRestrictions) {
15496                if (DEBUG_REMOVE) {
15497                    Slog.d(TAG, "Propagating install state across reinstall");
15498                }
15499                for (int userId : allUserHandles) {
15500                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15501                    if (DEBUG_REMOVE) {
15502                        Slog.d(TAG, "    user " + userId + " => " + installed);
15503                    }
15504                    ps.setInstalled(installed, userId);
15505
15506                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15507                }
15508                // Regardless of writeSettings we need to ensure that this restriction
15509                // state propagation is persisted
15510                mSettings.writeAllUsersPackageRestrictionsLPr();
15511            }
15512            // can downgrade to reader here
15513            if (writeSettings) {
15514                mSettings.writeLPr();
15515            }
15516        }
15517        return true;
15518    }
15519
15520    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15521            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15522            PackageRemovedInfo outInfo, boolean writeSettings,
15523            PackageParser.Package replacingPackage) {
15524        synchronized (mPackages) {
15525            if (outInfo != null) {
15526                outInfo.uid = ps.appId;
15527            }
15528
15529            if (outInfo != null && outInfo.removedChildPackages != null) {
15530                final int childCount = (ps.childPackageNames != null)
15531                        ? ps.childPackageNames.size() : 0;
15532                for (int i = 0; i < childCount; i++) {
15533                    String childPackageName = ps.childPackageNames.get(i);
15534                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15535                    if (childPs == null) {
15536                        return false;
15537                    }
15538                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15539                            childPackageName);
15540                    if (childInfo != null) {
15541                        childInfo.uid = childPs.appId;
15542                    }
15543                }
15544            }
15545        }
15546
15547        // Delete package data from internal structures and also remove data if flag is set
15548        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15549
15550        // Delete the child packages data
15551        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15552        for (int i = 0; i < childCount; i++) {
15553            PackageSetting childPs;
15554            synchronized (mPackages) {
15555                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15556            }
15557            if (childPs != null) {
15558                PackageRemovedInfo childOutInfo = (outInfo != null
15559                        && outInfo.removedChildPackages != null)
15560                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15561                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15562                        && (replacingPackage != null
15563                        && !replacingPackage.hasChildPackage(childPs.name))
15564                        ? flags & ~DELETE_KEEP_DATA : flags;
15565                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15566                        deleteFlags, writeSettings);
15567            }
15568        }
15569
15570        // Delete application code and resources only for parent packages
15571        if (ps.parentPackageName == null) {
15572            if (deleteCodeAndResources && (outInfo != null)) {
15573                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15574                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15575                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15576            }
15577        }
15578
15579        return true;
15580    }
15581
15582    @Override
15583    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15584            int userId) {
15585        mContext.enforceCallingOrSelfPermission(
15586                android.Manifest.permission.DELETE_PACKAGES, null);
15587        synchronized (mPackages) {
15588            PackageSetting ps = mSettings.mPackages.get(packageName);
15589            if (ps == null) {
15590                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15591                return false;
15592            }
15593            if (!ps.getInstalled(userId)) {
15594                // Can't block uninstall for an app that is not installed or enabled.
15595                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15596                return false;
15597            }
15598            ps.setBlockUninstall(blockUninstall, userId);
15599            mSettings.writePackageRestrictionsLPr(userId);
15600        }
15601        return true;
15602    }
15603
15604    @Override
15605    public boolean getBlockUninstallForUser(String packageName, int userId) {
15606        synchronized (mPackages) {
15607            PackageSetting ps = mSettings.mPackages.get(packageName);
15608            if (ps == null) {
15609                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15610                return false;
15611            }
15612            return ps.getBlockUninstall(userId);
15613        }
15614    }
15615
15616    @Override
15617    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15618        int callingUid = Binder.getCallingUid();
15619        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15620            throw new SecurityException(
15621                    "setRequiredForSystemUser can only be run by the system or root");
15622        }
15623        synchronized (mPackages) {
15624            PackageSetting ps = mSettings.mPackages.get(packageName);
15625            if (ps == null) {
15626                Log.w(TAG, "Package doesn't exist: " + packageName);
15627                return false;
15628            }
15629            if (systemUserApp) {
15630                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15631            } else {
15632                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15633            }
15634            mSettings.writeLPr();
15635        }
15636        return true;
15637    }
15638
15639    /*
15640     * This method handles package deletion in general
15641     */
15642    private boolean deletePackageLIF(String packageName, UserHandle user,
15643            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15644            PackageRemovedInfo outInfo, boolean writeSettings,
15645            PackageParser.Package replacingPackage) {
15646        if (packageName == null) {
15647            Slog.w(TAG, "Attempt to delete null packageName.");
15648            return false;
15649        }
15650
15651        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15652
15653        PackageSetting ps;
15654
15655        synchronized (mPackages) {
15656            ps = mSettings.mPackages.get(packageName);
15657            if (ps == null) {
15658                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15659                return false;
15660            }
15661
15662            if (ps.parentPackageName != null && (!isSystemApp(ps)
15663                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15664                if (DEBUG_REMOVE) {
15665                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15666                            + ((user == null) ? UserHandle.USER_ALL : user));
15667                }
15668                final int removedUserId = (user != null) ? user.getIdentifier()
15669                        : UserHandle.USER_ALL;
15670                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15671                    return false;
15672                }
15673                markPackageUninstalledForUserLPw(ps, user);
15674                scheduleWritePackageRestrictionsLocked(user);
15675                return true;
15676            }
15677        }
15678
15679        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15680                && user.getIdentifier() != UserHandle.USER_ALL)) {
15681            // The caller is asking that the package only be deleted for a single
15682            // user.  To do this, we just mark its uninstalled state and delete
15683            // its data. If this is a system app, we only allow this to happen if
15684            // they have set the special DELETE_SYSTEM_APP which requests different
15685            // semantics than normal for uninstalling system apps.
15686            markPackageUninstalledForUserLPw(ps, user);
15687
15688            if (!isSystemApp(ps)) {
15689                // Do not uninstall the APK if an app should be cached
15690                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15691                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15692                    // Other user still have this package installed, so all
15693                    // we need to do is clear this user's data and save that
15694                    // it is uninstalled.
15695                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15696                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15697                        return false;
15698                    }
15699                    scheduleWritePackageRestrictionsLocked(user);
15700                    return true;
15701                } else {
15702                    // We need to set it back to 'installed' so the uninstall
15703                    // broadcasts will be sent correctly.
15704                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15705                    ps.setInstalled(true, user.getIdentifier());
15706                }
15707            } else {
15708                // This is a system app, so we assume that the
15709                // other users still have this package installed, so all
15710                // we need to do is clear this user's data and save that
15711                // it is uninstalled.
15712                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15713                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15714                    return false;
15715                }
15716                scheduleWritePackageRestrictionsLocked(user);
15717                return true;
15718            }
15719        }
15720
15721        // If we are deleting a composite package for all users, keep track
15722        // of result for each child.
15723        if (ps.childPackageNames != null && outInfo != null) {
15724            synchronized (mPackages) {
15725                final int childCount = ps.childPackageNames.size();
15726                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15727                for (int i = 0; i < childCount; i++) {
15728                    String childPackageName = ps.childPackageNames.get(i);
15729                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15730                    childInfo.removedPackage = childPackageName;
15731                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15732                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15733                    if (childPs != null) {
15734                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15735                    }
15736                }
15737            }
15738        }
15739
15740        boolean ret = false;
15741        if (isSystemApp(ps)) {
15742            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15743            // When an updated system application is deleted we delete the existing resources
15744            // as well and fall back to existing code in system partition
15745            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15746        } else {
15747            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15748            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15749                    outInfo, writeSettings, replacingPackage);
15750        }
15751
15752        // Take a note whether we deleted the package for all users
15753        if (outInfo != null) {
15754            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15755            if (outInfo.removedChildPackages != null) {
15756                synchronized (mPackages) {
15757                    final int childCount = outInfo.removedChildPackages.size();
15758                    for (int i = 0; i < childCount; i++) {
15759                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15760                        if (childInfo != null) {
15761                            childInfo.removedForAllUsers = mPackages.get(
15762                                    childInfo.removedPackage) == null;
15763                        }
15764                    }
15765                }
15766            }
15767            // If we uninstalled an update to a system app there may be some
15768            // child packages that appeared as they are declared in the system
15769            // app but were not declared in the update.
15770            if (isSystemApp(ps)) {
15771                synchronized (mPackages) {
15772                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15773                    final int childCount = (updatedPs.childPackageNames != null)
15774                            ? updatedPs.childPackageNames.size() : 0;
15775                    for (int i = 0; i < childCount; i++) {
15776                        String childPackageName = updatedPs.childPackageNames.get(i);
15777                        if (outInfo.removedChildPackages == null
15778                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15779                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15780                            if (childPs == null) {
15781                                continue;
15782                            }
15783                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15784                            installRes.name = childPackageName;
15785                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15786                            installRes.pkg = mPackages.get(childPackageName);
15787                            installRes.uid = childPs.pkg.applicationInfo.uid;
15788                            if (outInfo.appearedChildPackages == null) {
15789                                outInfo.appearedChildPackages = new ArrayMap<>();
15790                            }
15791                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15792                        }
15793                    }
15794                }
15795            }
15796        }
15797
15798        return ret;
15799    }
15800
15801    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15802        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15803                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15804        for (int nextUserId : userIds) {
15805            if (DEBUG_REMOVE) {
15806                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15807            }
15808            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15809                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15810                    false /*hidden*/, false /*suspended*/, null, null, null,
15811                    false /*blockUninstall*/,
15812                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15813        }
15814    }
15815
15816    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15817            PackageRemovedInfo outInfo) {
15818        final PackageParser.Package pkg;
15819        synchronized (mPackages) {
15820            pkg = mPackages.get(ps.name);
15821        }
15822
15823        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15824                : new int[] {userId};
15825        for (int nextUserId : userIds) {
15826            if (DEBUG_REMOVE) {
15827                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15828                        + nextUserId);
15829            }
15830
15831            destroyAppDataLIF(pkg, userId,
15832                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15833            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15834            schedulePackageCleaning(ps.name, nextUserId, false);
15835            synchronized (mPackages) {
15836                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15837                    scheduleWritePackageRestrictionsLocked(nextUserId);
15838                }
15839                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15840            }
15841        }
15842
15843        if (outInfo != null) {
15844            outInfo.removedPackage = ps.name;
15845            outInfo.removedAppId = ps.appId;
15846            outInfo.removedUsers = userIds;
15847        }
15848
15849        return true;
15850    }
15851
15852    private final class ClearStorageConnection implements ServiceConnection {
15853        IMediaContainerService mContainerService;
15854
15855        @Override
15856        public void onServiceConnected(ComponentName name, IBinder service) {
15857            synchronized (this) {
15858                mContainerService = IMediaContainerService.Stub.asInterface(service);
15859                notifyAll();
15860            }
15861        }
15862
15863        @Override
15864        public void onServiceDisconnected(ComponentName name) {
15865        }
15866    }
15867
15868    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15869        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15870
15871        final boolean mounted;
15872        if (Environment.isExternalStorageEmulated()) {
15873            mounted = true;
15874        } else {
15875            final String status = Environment.getExternalStorageState();
15876
15877            mounted = status.equals(Environment.MEDIA_MOUNTED)
15878                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15879        }
15880
15881        if (!mounted) {
15882            return;
15883        }
15884
15885        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15886        int[] users;
15887        if (userId == UserHandle.USER_ALL) {
15888            users = sUserManager.getUserIds();
15889        } else {
15890            users = new int[] { userId };
15891        }
15892        final ClearStorageConnection conn = new ClearStorageConnection();
15893        if (mContext.bindServiceAsUser(
15894                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15895            try {
15896                for (int curUser : users) {
15897                    long timeout = SystemClock.uptimeMillis() + 5000;
15898                    synchronized (conn) {
15899                        long now = SystemClock.uptimeMillis();
15900                        while (conn.mContainerService == null && now < timeout) {
15901                            try {
15902                                conn.wait(timeout - now);
15903                            } catch (InterruptedException e) {
15904                            }
15905                        }
15906                    }
15907                    if (conn.mContainerService == null) {
15908                        return;
15909                    }
15910
15911                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15912                    clearDirectory(conn.mContainerService,
15913                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15914                    if (allData) {
15915                        clearDirectory(conn.mContainerService,
15916                                userEnv.buildExternalStorageAppDataDirs(packageName));
15917                        clearDirectory(conn.mContainerService,
15918                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15919                    }
15920                }
15921            } finally {
15922                mContext.unbindService(conn);
15923            }
15924        }
15925    }
15926
15927    @Override
15928    public void clearApplicationProfileData(String packageName) {
15929        enforceSystemOrRoot("Only the system can clear all profile data");
15930
15931        final PackageParser.Package pkg;
15932        synchronized (mPackages) {
15933            pkg = mPackages.get(packageName);
15934        }
15935
15936        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15937            synchronized (mInstallLock) {
15938                clearAppProfilesLIF(pkg);
15939            }
15940        }
15941    }
15942
15943    @Override
15944    public void clearApplicationUserData(final String packageName,
15945            final IPackageDataObserver observer, final int userId) {
15946        mContext.enforceCallingOrSelfPermission(
15947                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15948
15949        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15950                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15951
15952        final DevicePolicyManagerInternal dpmi = LocalServices
15953                .getService(DevicePolicyManagerInternal.class);
15954        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15955            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15956        }
15957        // Queue up an async operation since the package deletion may take a little while.
15958        mHandler.post(new Runnable() {
15959            public void run() {
15960                mHandler.removeCallbacks(this);
15961                final boolean succeeded;
15962                try (PackageFreezer freezer = freezePackage(packageName,
15963                        "clearApplicationUserData")) {
15964                    synchronized (mInstallLock) {
15965                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15966                    }
15967                    clearExternalStorageDataSync(packageName, userId, true);
15968                }
15969                if (succeeded) {
15970                    // invoke DeviceStorageMonitor's update method to clear any notifications
15971                    DeviceStorageMonitorInternal dsm = LocalServices
15972                            .getService(DeviceStorageMonitorInternal.class);
15973                    if (dsm != null) {
15974                        dsm.checkMemory();
15975                    }
15976                }
15977                if(observer != null) {
15978                    try {
15979                        observer.onRemoveCompleted(packageName, succeeded);
15980                    } catch (RemoteException e) {
15981                        Log.i(TAG, "Observer no longer exists.");
15982                    }
15983                } //end if observer
15984            } //end run
15985        });
15986    }
15987
15988    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
15989        if (packageName == null) {
15990            Slog.w(TAG, "Attempt to delete null packageName.");
15991            return false;
15992        }
15993
15994        // Try finding details about the requested package
15995        PackageParser.Package pkg;
15996        synchronized (mPackages) {
15997            pkg = mPackages.get(packageName);
15998            if (pkg == null) {
15999                final PackageSetting ps = mSettings.mPackages.get(packageName);
16000                if (ps != null) {
16001                    pkg = ps.pkg;
16002                }
16003            }
16004
16005            if (pkg == null) {
16006                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16007                return false;
16008            }
16009
16010            PackageSetting ps = (PackageSetting) pkg.mExtras;
16011            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16012        }
16013
16014        clearAppDataLIF(pkg, userId,
16015                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16016
16017        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16018        removeKeystoreDataIfNeeded(userId, appId);
16019
16020        final UserManager um = mContext.getSystemService(UserManager.class);
16021        final int flags;
16022        if (um.isUserUnlocked(userId)) {
16023            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16024        } else if (um.isUserRunning(userId)) {
16025            flags = StorageManager.FLAG_STORAGE_DE;
16026        } else {
16027            flags = 0;
16028        }
16029        prepareAppDataContentsLIF(pkg, userId, flags);
16030
16031        return true;
16032    }
16033
16034    /**
16035     * Reverts user permission state changes (permissions and flags) in
16036     * all packages for a given user.
16037     *
16038     * @param userId The device user for which to do a reset.
16039     */
16040    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16041        final int packageCount = mPackages.size();
16042        for (int i = 0; i < packageCount; i++) {
16043            PackageParser.Package pkg = mPackages.valueAt(i);
16044            PackageSetting ps = (PackageSetting) pkg.mExtras;
16045            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16046        }
16047    }
16048
16049    /**
16050     * Reverts user permission state changes (permissions and flags).
16051     *
16052     * @param ps The package for which to reset.
16053     * @param userId The device user for which to do a reset.
16054     */
16055    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16056            final PackageSetting ps, final int userId) {
16057        if (ps.pkg == null) {
16058            return;
16059        }
16060
16061        // These are flags that can change base on user actions.
16062        final int userSettableMask = FLAG_PERMISSION_USER_SET
16063                | FLAG_PERMISSION_USER_FIXED
16064                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16065                | FLAG_PERMISSION_REVIEW_REQUIRED;
16066
16067        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16068                | FLAG_PERMISSION_POLICY_FIXED;
16069
16070        boolean writeInstallPermissions = false;
16071        boolean writeRuntimePermissions = false;
16072
16073        final int permissionCount = ps.pkg.requestedPermissions.size();
16074        for (int i = 0; i < permissionCount; i++) {
16075            String permission = ps.pkg.requestedPermissions.get(i);
16076
16077            BasePermission bp = mSettings.mPermissions.get(permission);
16078            if (bp == null) {
16079                continue;
16080            }
16081
16082            // If shared user we just reset the state to which only this app contributed.
16083            if (ps.sharedUser != null) {
16084                boolean used = false;
16085                final int packageCount = ps.sharedUser.packages.size();
16086                for (int j = 0; j < packageCount; j++) {
16087                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16088                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16089                            && pkg.pkg.requestedPermissions.contains(permission)) {
16090                        used = true;
16091                        break;
16092                    }
16093                }
16094                if (used) {
16095                    continue;
16096                }
16097            }
16098
16099            PermissionsState permissionsState = ps.getPermissionsState();
16100
16101            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16102
16103            // Always clear the user settable flags.
16104            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16105                    bp.name) != null;
16106            // If permission review is enabled and this is a legacy app, mark the
16107            // permission as requiring a review as this is the initial state.
16108            int flags = 0;
16109            if (Build.PERMISSIONS_REVIEW_REQUIRED
16110                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16111                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16112            }
16113            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16114                if (hasInstallState) {
16115                    writeInstallPermissions = true;
16116                } else {
16117                    writeRuntimePermissions = true;
16118                }
16119            }
16120
16121            // Below is only runtime permission handling.
16122            if (!bp.isRuntime()) {
16123                continue;
16124            }
16125
16126            // Never clobber system or policy.
16127            if ((oldFlags & policyOrSystemFlags) != 0) {
16128                continue;
16129            }
16130
16131            // If this permission was granted by default, make sure it is.
16132            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16133                if (permissionsState.grantRuntimePermission(bp, userId)
16134                        != PERMISSION_OPERATION_FAILURE) {
16135                    writeRuntimePermissions = true;
16136                }
16137            // If permission review is enabled the permissions for a legacy apps
16138            // are represented as constantly granted runtime ones, so don't revoke.
16139            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16140                // Otherwise, reset the permission.
16141                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16142                switch (revokeResult) {
16143                    case PERMISSION_OPERATION_SUCCESS:
16144                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16145                        writeRuntimePermissions = true;
16146                        final int appId = ps.appId;
16147                        mHandler.post(new Runnable() {
16148                            @Override
16149                            public void run() {
16150                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16151                            }
16152                        });
16153                    } break;
16154                }
16155            }
16156        }
16157
16158        // Synchronously write as we are taking permissions away.
16159        if (writeRuntimePermissions) {
16160            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16161        }
16162
16163        // Synchronously write as we are taking permissions away.
16164        if (writeInstallPermissions) {
16165            mSettings.writeLPr();
16166        }
16167    }
16168
16169    /**
16170     * Remove entries from the keystore daemon. Will only remove it if the
16171     * {@code appId} is valid.
16172     */
16173    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16174        if (appId < 0) {
16175            return;
16176        }
16177
16178        final KeyStore keyStore = KeyStore.getInstance();
16179        if (keyStore != null) {
16180            if (userId == UserHandle.USER_ALL) {
16181                for (final int individual : sUserManager.getUserIds()) {
16182                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16183                }
16184            } else {
16185                keyStore.clearUid(UserHandle.getUid(userId, appId));
16186            }
16187        } else {
16188            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16189        }
16190    }
16191
16192    @Override
16193    public void deleteApplicationCacheFiles(final String packageName,
16194            final IPackageDataObserver observer) {
16195        final int userId = UserHandle.getCallingUserId();
16196        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16197    }
16198
16199    @Override
16200    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16201            final IPackageDataObserver observer) {
16202        mContext.enforceCallingOrSelfPermission(
16203                android.Manifest.permission.DELETE_CACHE_FILES, null);
16204        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16205                /* requireFullPermission= */ true, /* checkShell= */ false,
16206                "delete application cache files");
16207
16208        final PackageParser.Package pkg;
16209        synchronized (mPackages) {
16210            pkg = mPackages.get(packageName);
16211        }
16212
16213        // Queue up an async operation since the package deletion may take a little while.
16214        mHandler.post(new Runnable() {
16215            public void run() {
16216                synchronized (mInstallLock) {
16217                    final int flags = StorageManager.FLAG_STORAGE_DE
16218                            | StorageManager.FLAG_STORAGE_CE;
16219                    // We're only clearing cache files, so we don't care if the
16220                    // app is unfrozen and still able to run
16221                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16222                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16223                }
16224                clearExternalStorageDataSync(packageName, userId, false);
16225                if (observer != null) {
16226                    try {
16227                        observer.onRemoveCompleted(packageName, true);
16228                    } catch (RemoteException e) {
16229                        Log.i(TAG, "Observer no longer exists.");
16230                    }
16231                }
16232            }
16233        });
16234    }
16235
16236    @Override
16237    public void getPackageSizeInfo(final String packageName, int userHandle,
16238            final IPackageStatsObserver observer) {
16239        mContext.enforceCallingOrSelfPermission(
16240                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16241        if (packageName == null) {
16242            throw new IllegalArgumentException("Attempt to get size of null packageName");
16243        }
16244
16245        PackageStats stats = new PackageStats(packageName, userHandle);
16246
16247        /*
16248         * Queue up an async operation since the package measurement may take a
16249         * little while.
16250         */
16251        Message msg = mHandler.obtainMessage(INIT_COPY);
16252        msg.obj = new MeasureParams(stats, observer);
16253        mHandler.sendMessage(msg);
16254    }
16255
16256    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16257        final PackageSetting ps;
16258        synchronized (mPackages) {
16259            ps = mSettings.mPackages.get(packageName);
16260            if (ps == null) {
16261                Slog.w(TAG, "Failed to find settings for " + packageName);
16262                return false;
16263            }
16264        }
16265        try {
16266            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16267                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16268                    ps.getCeDataInode(userId), ps.codePathString, stats);
16269        } catch (InstallerException e) {
16270            Slog.w(TAG, String.valueOf(e));
16271            return false;
16272        }
16273
16274        // For now, ignore code size of packages on system partition
16275        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16276            stats.codeSize = 0;
16277        }
16278
16279        return true;
16280    }
16281
16282    private int getUidTargetSdkVersionLockedLPr(int uid) {
16283        Object obj = mSettings.getUserIdLPr(uid);
16284        if (obj instanceof SharedUserSetting) {
16285            final SharedUserSetting sus = (SharedUserSetting) obj;
16286            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16287            final Iterator<PackageSetting> it = sus.packages.iterator();
16288            while (it.hasNext()) {
16289                final PackageSetting ps = it.next();
16290                if (ps.pkg != null) {
16291                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16292                    if (v < vers) vers = v;
16293                }
16294            }
16295            return vers;
16296        } else if (obj instanceof PackageSetting) {
16297            final PackageSetting ps = (PackageSetting) obj;
16298            if (ps.pkg != null) {
16299                return ps.pkg.applicationInfo.targetSdkVersion;
16300            }
16301        }
16302        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16303    }
16304
16305    @Override
16306    public void addPreferredActivity(IntentFilter filter, int match,
16307            ComponentName[] set, ComponentName activity, int userId) {
16308        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16309                "Adding preferred");
16310    }
16311
16312    private void addPreferredActivityInternal(IntentFilter filter, int match,
16313            ComponentName[] set, ComponentName activity, boolean always, int userId,
16314            String opname) {
16315        // writer
16316        int callingUid = Binder.getCallingUid();
16317        enforceCrossUserPermission(callingUid, userId,
16318                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16319        if (filter.countActions() == 0) {
16320            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16321            return;
16322        }
16323        synchronized (mPackages) {
16324            if (mContext.checkCallingOrSelfPermission(
16325                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16326                    != PackageManager.PERMISSION_GRANTED) {
16327                if (getUidTargetSdkVersionLockedLPr(callingUid)
16328                        < Build.VERSION_CODES.FROYO) {
16329                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16330                            + callingUid);
16331                    return;
16332                }
16333                mContext.enforceCallingOrSelfPermission(
16334                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16335            }
16336
16337            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16338            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16339                    + userId + ":");
16340            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16341            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16342            scheduleWritePackageRestrictionsLocked(userId);
16343        }
16344    }
16345
16346    @Override
16347    public void replacePreferredActivity(IntentFilter filter, int match,
16348            ComponentName[] set, ComponentName activity, int userId) {
16349        if (filter.countActions() != 1) {
16350            throw new IllegalArgumentException(
16351                    "replacePreferredActivity expects filter to have only 1 action.");
16352        }
16353        if (filter.countDataAuthorities() != 0
16354                || filter.countDataPaths() != 0
16355                || filter.countDataSchemes() > 1
16356                || filter.countDataTypes() != 0) {
16357            throw new IllegalArgumentException(
16358                    "replacePreferredActivity expects filter to have no data authorities, " +
16359                    "paths, or types; and at most one scheme.");
16360        }
16361
16362        final int callingUid = Binder.getCallingUid();
16363        enforceCrossUserPermission(callingUid, userId,
16364                true /* requireFullPermission */, false /* checkShell */,
16365                "replace preferred activity");
16366        synchronized (mPackages) {
16367            if (mContext.checkCallingOrSelfPermission(
16368                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16369                    != PackageManager.PERMISSION_GRANTED) {
16370                if (getUidTargetSdkVersionLockedLPr(callingUid)
16371                        < Build.VERSION_CODES.FROYO) {
16372                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16373                            + Binder.getCallingUid());
16374                    return;
16375                }
16376                mContext.enforceCallingOrSelfPermission(
16377                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16378            }
16379
16380            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16381            if (pir != null) {
16382                // Get all of the existing entries that exactly match this filter.
16383                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16384                if (existing != null && existing.size() == 1) {
16385                    PreferredActivity cur = existing.get(0);
16386                    if (DEBUG_PREFERRED) {
16387                        Slog.i(TAG, "Checking replace of preferred:");
16388                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16389                        if (!cur.mPref.mAlways) {
16390                            Slog.i(TAG, "  -- CUR; not mAlways!");
16391                        } else {
16392                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16393                            Slog.i(TAG, "  -- CUR: mSet="
16394                                    + Arrays.toString(cur.mPref.mSetComponents));
16395                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16396                            Slog.i(TAG, "  -- NEW: mMatch="
16397                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16398                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16399                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16400                        }
16401                    }
16402                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16403                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16404                            && cur.mPref.sameSet(set)) {
16405                        // Setting the preferred activity to what it happens to be already
16406                        if (DEBUG_PREFERRED) {
16407                            Slog.i(TAG, "Replacing with same preferred activity "
16408                                    + cur.mPref.mShortComponent + " for user "
16409                                    + userId + ":");
16410                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16411                        }
16412                        return;
16413                    }
16414                }
16415
16416                if (existing != null) {
16417                    if (DEBUG_PREFERRED) {
16418                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16419                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16420                    }
16421                    for (int i = 0; i < existing.size(); i++) {
16422                        PreferredActivity pa = existing.get(i);
16423                        if (DEBUG_PREFERRED) {
16424                            Slog.i(TAG, "Removing existing preferred activity "
16425                                    + pa.mPref.mComponent + ":");
16426                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16427                        }
16428                        pir.removeFilter(pa);
16429                    }
16430                }
16431            }
16432            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16433                    "Replacing preferred");
16434        }
16435    }
16436
16437    @Override
16438    public void clearPackagePreferredActivities(String packageName) {
16439        final int uid = Binder.getCallingUid();
16440        // writer
16441        synchronized (mPackages) {
16442            PackageParser.Package pkg = mPackages.get(packageName);
16443            if (pkg == null || pkg.applicationInfo.uid != uid) {
16444                if (mContext.checkCallingOrSelfPermission(
16445                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16446                        != PackageManager.PERMISSION_GRANTED) {
16447                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16448                            < Build.VERSION_CODES.FROYO) {
16449                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16450                                + Binder.getCallingUid());
16451                        return;
16452                    }
16453                    mContext.enforceCallingOrSelfPermission(
16454                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16455                }
16456            }
16457
16458            int user = UserHandle.getCallingUserId();
16459            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16460                scheduleWritePackageRestrictionsLocked(user);
16461            }
16462        }
16463    }
16464
16465    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16466    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16467        ArrayList<PreferredActivity> removed = null;
16468        boolean changed = false;
16469        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16470            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16471            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16472            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16473                continue;
16474            }
16475            Iterator<PreferredActivity> it = pir.filterIterator();
16476            while (it.hasNext()) {
16477                PreferredActivity pa = it.next();
16478                // Mark entry for removal only if it matches the package name
16479                // and the entry is of type "always".
16480                if (packageName == null ||
16481                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16482                                && pa.mPref.mAlways)) {
16483                    if (removed == null) {
16484                        removed = new ArrayList<PreferredActivity>();
16485                    }
16486                    removed.add(pa);
16487                }
16488            }
16489            if (removed != null) {
16490                for (int j=0; j<removed.size(); j++) {
16491                    PreferredActivity pa = removed.get(j);
16492                    pir.removeFilter(pa);
16493                }
16494                changed = true;
16495            }
16496        }
16497        return changed;
16498    }
16499
16500    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16501    private void clearIntentFilterVerificationsLPw(int userId) {
16502        final int packageCount = mPackages.size();
16503        for (int i = 0; i < packageCount; i++) {
16504            PackageParser.Package pkg = mPackages.valueAt(i);
16505            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16506        }
16507    }
16508
16509    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16510    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16511        if (userId == UserHandle.USER_ALL) {
16512            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16513                    sUserManager.getUserIds())) {
16514                for (int oneUserId : sUserManager.getUserIds()) {
16515                    scheduleWritePackageRestrictionsLocked(oneUserId);
16516                }
16517            }
16518        } else {
16519            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16520                scheduleWritePackageRestrictionsLocked(userId);
16521            }
16522        }
16523    }
16524
16525    void clearDefaultBrowserIfNeeded(String packageName) {
16526        for (int oneUserId : sUserManager.getUserIds()) {
16527            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16528            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16529            if (packageName.equals(defaultBrowserPackageName)) {
16530                setDefaultBrowserPackageName(null, oneUserId);
16531            }
16532        }
16533    }
16534
16535    @Override
16536    public void resetApplicationPreferences(int userId) {
16537        mContext.enforceCallingOrSelfPermission(
16538                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16539        // writer
16540        synchronized (mPackages) {
16541            final long identity = Binder.clearCallingIdentity();
16542            try {
16543                clearPackagePreferredActivitiesLPw(null, userId);
16544                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16545                // TODO: We have to reset the default SMS and Phone. This requires
16546                // significant refactoring to keep all default apps in the package
16547                // manager (cleaner but more work) or have the services provide
16548                // callbacks to the package manager to request a default app reset.
16549                applyFactoryDefaultBrowserLPw(userId);
16550                clearIntentFilterVerificationsLPw(userId);
16551                primeDomainVerificationsLPw(userId);
16552                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16553                scheduleWritePackageRestrictionsLocked(userId);
16554            } finally {
16555                Binder.restoreCallingIdentity(identity);
16556            }
16557        }
16558    }
16559
16560    @Override
16561    public int getPreferredActivities(List<IntentFilter> outFilters,
16562            List<ComponentName> outActivities, String packageName) {
16563
16564        int num = 0;
16565        final int userId = UserHandle.getCallingUserId();
16566        // reader
16567        synchronized (mPackages) {
16568            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16569            if (pir != null) {
16570                final Iterator<PreferredActivity> it = pir.filterIterator();
16571                while (it.hasNext()) {
16572                    final PreferredActivity pa = it.next();
16573                    if (packageName == null
16574                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16575                                    && pa.mPref.mAlways)) {
16576                        if (outFilters != null) {
16577                            outFilters.add(new IntentFilter(pa));
16578                        }
16579                        if (outActivities != null) {
16580                            outActivities.add(pa.mPref.mComponent);
16581                        }
16582                    }
16583                }
16584            }
16585        }
16586
16587        return num;
16588    }
16589
16590    @Override
16591    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16592            int userId) {
16593        int callingUid = Binder.getCallingUid();
16594        if (callingUid != Process.SYSTEM_UID) {
16595            throw new SecurityException(
16596                    "addPersistentPreferredActivity can only be run by the system");
16597        }
16598        if (filter.countActions() == 0) {
16599            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16600            return;
16601        }
16602        synchronized (mPackages) {
16603            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16604                    ":");
16605            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16606            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16607                    new PersistentPreferredActivity(filter, activity));
16608            scheduleWritePackageRestrictionsLocked(userId);
16609        }
16610    }
16611
16612    @Override
16613    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16614        int callingUid = Binder.getCallingUid();
16615        if (callingUid != Process.SYSTEM_UID) {
16616            throw new SecurityException(
16617                    "clearPackagePersistentPreferredActivities can only be run by the system");
16618        }
16619        ArrayList<PersistentPreferredActivity> removed = null;
16620        boolean changed = false;
16621        synchronized (mPackages) {
16622            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16623                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16624                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16625                        .valueAt(i);
16626                if (userId != thisUserId) {
16627                    continue;
16628                }
16629                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16630                while (it.hasNext()) {
16631                    PersistentPreferredActivity ppa = it.next();
16632                    // Mark entry for removal only if it matches the package name.
16633                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16634                        if (removed == null) {
16635                            removed = new ArrayList<PersistentPreferredActivity>();
16636                        }
16637                        removed.add(ppa);
16638                    }
16639                }
16640                if (removed != null) {
16641                    for (int j=0; j<removed.size(); j++) {
16642                        PersistentPreferredActivity ppa = removed.get(j);
16643                        ppir.removeFilter(ppa);
16644                    }
16645                    changed = true;
16646                }
16647            }
16648
16649            if (changed) {
16650                scheduleWritePackageRestrictionsLocked(userId);
16651            }
16652        }
16653    }
16654
16655    /**
16656     * Common machinery for picking apart a restored XML blob and passing
16657     * it to a caller-supplied functor to be applied to the running system.
16658     */
16659    private void restoreFromXml(XmlPullParser parser, int userId,
16660            String expectedStartTag, BlobXmlRestorer functor)
16661            throws IOException, XmlPullParserException {
16662        int type;
16663        while ((type = parser.next()) != XmlPullParser.START_TAG
16664                && type != XmlPullParser.END_DOCUMENT) {
16665        }
16666        if (type != XmlPullParser.START_TAG) {
16667            // oops didn't find a start tag?!
16668            if (DEBUG_BACKUP) {
16669                Slog.e(TAG, "Didn't find start tag during restore");
16670            }
16671            return;
16672        }
16673Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16674        // this is supposed to be TAG_PREFERRED_BACKUP
16675        if (!expectedStartTag.equals(parser.getName())) {
16676            if (DEBUG_BACKUP) {
16677                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16678            }
16679            return;
16680        }
16681
16682        // skip interfering stuff, then we're aligned with the backing implementation
16683        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16684Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16685        functor.apply(parser, userId);
16686    }
16687
16688    private interface BlobXmlRestorer {
16689        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16690    }
16691
16692    /**
16693     * Non-Binder method, support for the backup/restore mechanism: write the
16694     * full set of preferred activities in its canonical XML format.  Returns the
16695     * XML output as a byte array, or null if there is none.
16696     */
16697    @Override
16698    public byte[] getPreferredActivityBackup(int userId) {
16699        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16700            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16701        }
16702
16703        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16704        try {
16705            final XmlSerializer serializer = new FastXmlSerializer();
16706            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16707            serializer.startDocument(null, true);
16708            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16709
16710            synchronized (mPackages) {
16711                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16712            }
16713
16714            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16715            serializer.endDocument();
16716            serializer.flush();
16717        } catch (Exception e) {
16718            if (DEBUG_BACKUP) {
16719                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16720            }
16721            return null;
16722        }
16723
16724        return dataStream.toByteArray();
16725    }
16726
16727    @Override
16728    public void restorePreferredActivities(byte[] backup, int userId) {
16729        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16730            throw new SecurityException("Only the system may call restorePreferredActivities()");
16731        }
16732
16733        try {
16734            final XmlPullParser parser = Xml.newPullParser();
16735            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16736            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16737                    new BlobXmlRestorer() {
16738                        @Override
16739                        public void apply(XmlPullParser parser, int userId)
16740                                throws XmlPullParserException, IOException {
16741                            synchronized (mPackages) {
16742                                mSettings.readPreferredActivitiesLPw(parser, userId);
16743                            }
16744                        }
16745                    } );
16746        } catch (Exception e) {
16747            if (DEBUG_BACKUP) {
16748                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16749            }
16750        }
16751    }
16752
16753    /**
16754     * Non-Binder method, support for the backup/restore mechanism: write the
16755     * default browser (etc) settings in its canonical XML format.  Returns the default
16756     * browser XML representation as a byte array, or null if there is none.
16757     */
16758    @Override
16759    public byte[] getDefaultAppsBackup(int userId) {
16760        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16761            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16762        }
16763
16764        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16765        try {
16766            final XmlSerializer serializer = new FastXmlSerializer();
16767            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16768            serializer.startDocument(null, true);
16769            serializer.startTag(null, TAG_DEFAULT_APPS);
16770
16771            synchronized (mPackages) {
16772                mSettings.writeDefaultAppsLPr(serializer, userId);
16773            }
16774
16775            serializer.endTag(null, TAG_DEFAULT_APPS);
16776            serializer.endDocument();
16777            serializer.flush();
16778        } catch (Exception e) {
16779            if (DEBUG_BACKUP) {
16780                Slog.e(TAG, "Unable to write default apps for backup", e);
16781            }
16782            return null;
16783        }
16784
16785        return dataStream.toByteArray();
16786    }
16787
16788    @Override
16789    public void restoreDefaultApps(byte[] backup, int userId) {
16790        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16791            throw new SecurityException("Only the system may call restoreDefaultApps()");
16792        }
16793
16794        try {
16795            final XmlPullParser parser = Xml.newPullParser();
16796            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16797            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16798                    new BlobXmlRestorer() {
16799                        @Override
16800                        public void apply(XmlPullParser parser, int userId)
16801                                throws XmlPullParserException, IOException {
16802                            synchronized (mPackages) {
16803                                mSettings.readDefaultAppsLPw(parser, userId);
16804                            }
16805                        }
16806                    } );
16807        } catch (Exception e) {
16808            if (DEBUG_BACKUP) {
16809                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16810            }
16811        }
16812    }
16813
16814    @Override
16815    public byte[] getIntentFilterVerificationBackup(int userId) {
16816        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16817            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16818        }
16819
16820        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16821        try {
16822            final XmlSerializer serializer = new FastXmlSerializer();
16823            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16824            serializer.startDocument(null, true);
16825            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16826
16827            synchronized (mPackages) {
16828                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16829            }
16830
16831            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16832            serializer.endDocument();
16833            serializer.flush();
16834        } catch (Exception e) {
16835            if (DEBUG_BACKUP) {
16836                Slog.e(TAG, "Unable to write default apps for backup", e);
16837            }
16838            return null;
16839        }
16840
16841        return dataStream.toByteArray();
16842    }
16843
16844    @Override
16845    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16846        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16847            throw new SecurityException("Only the system may call restorePreferredActivities()");
16848        }
16849
16850        try {
16851            final XmlPullParser parser = Xml.newPullParser();
16852            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16853            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16854                    new BlobXmlRestorer() {
16855                        @Override
16856                        public void apply(XmlPullParser parser, int userId)
16857                                throws XmlPullParserException, IOException {
16858                            synchronized (mPackages) {
16859                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16860                                mSettings.writeLPr();
16861                            }
16862                        }
16863                    } );
16864        } catch (Exception e) {
16865            if (DEBUG_BACKUP) {
16866                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16867            }
16868        }
16869    }
16870
16871    @Override
16872    public byte[] getPermissionGrantBackup(int userId) {
16873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16874            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16875        }
16876
16877        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16878        try {
16879            final XmlSerializer serializer = new FastXmlSerializer();
16880            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16881            serializer.startDocument(null, true);
16882            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16883
16884            synchronized (mPackages) {
16885                serializeRuntimePermissionGrantsLPr(serializer, userId);
16886            }
16887
16888            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16889            serializer.endDocument();
16890            serializer.flush();
16891        } catch (Exception e) {
16892            if (DEBUG_BACKUP) {
16893                Slog.e(TAG, "Unable to write default apps for backup", e);
16894            }
16895            return null;
16896        }
16897
16898        return dataStream.toByteArray();
16899    }
16900
16901    @Override
16902    public void restorePermissionGrants(byte[] backup, int userId) {
16903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16904            throw new SecurityException("Only the system may call restorePermissionGrants()");
16905        }
16906
16907        try {
16908            final XmlPullParser parser = Xml.newPullParser();
16909            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16910            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16911                    new BlobXmlRestorer() {
16912                        @Override
16913                        public void apply(XmlPullParser parser, int userId)
16914                                throws XmlPullParserException, IOException {
16915                            synchronized (mPackages) {
16916                                processRestoredPermissionGrantsLPr(parser, userId);
16917                            }
16918                        }
16919                    } );
16920        } catch (Exception e) {
16921            if (DEBUG_BACKUP) {
16922                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16923            }
16924        }
16925    }
16926
16927    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16928            throws IOException {
16929        serializer.startTag(null, TAG_ALL_GRANTS);
16930
16931        final int N = mSettings.mPackages.size();
16932        for (int i = 0; i < N; i++) {
16933            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16934            boolean pkgGrantsKnown = false;
16935
16936            PermissionsState packagePerms = ps.getPermissionsState();
16937
16938            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16939                final int grantFlags = state.getFlags();
16940                // only look at grants that are not system/policy fixed
16941                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16942                    final boolean isGranted = state.isGranted();
16943                    // And only back up the user-twiddled state bits
16944                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16945                        final String packageName = mSettings.mPackages.keyAt(i);
16946                        if (!pkgGrantsKnown) {
16947                            serializer.startTag(null, TAG_GRANT);
16948                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16949                            pkgGrantsKnown = true;
16950                        }
16951
16952                        final boolean userSet =
16953                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16954                        final boolean userFixed =
16955                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16956                        final boolean revoke =
16957                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16958
16959                        serializer.startTag(null, TAG_PERMISSION);
16960                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16961                        if (isGranted) {
16962                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16963                        }
16964                        if (userSet) {
16965                            serializer.attribute(null, ATTR_USER_SET, "true");
16966                        }
16967                        if (userFixed) {
16968                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16969                        }
16970                        if (revoke) {
16971                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16972                        }
16973                        serializer.endTag(null, TAG_PERMISSION);
16974                    }
16975                }
16976            }
16977
16978            if (pkgGrantsKnown) {
16979                serializer.endTag(null, TAG_GRANT);
16980            }
16981        }
16982
16983        serializer.endTag(null, TAG_ALL_GRANTS);
16984    }
16985
16986    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16987            throws XmlPullParserException, IOException {
16988        String pkgName = null;
16989        int outerDepth = parser.getDepth();
16990        int type;
16991        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16992                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16993            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16994                continue;
16995            }
16996
16997            final String tagName = parser.getName();
16998            if (tagName.equals(TAG_GRANT)) {
16999                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17000                if (DEBUG_BACKUP) {
17001                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17002                }
17003            } else if (tagName.equals(TAG_PERMISSION)) {
17004
17005                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17006                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17007
17008                int newFlagSet = 0;
17009                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17010                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17011                }
17012                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17013                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17014                }
17015                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17016                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17017                }
17018                if (DEBUG_BACKUP) {
17019                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17020                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17021                }
17022                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17023                if (ps != null) {
17024                    // Already installed so we apply the grant immediately
17025                    if (DEBUG_BACKUP) {
17026                        Slog.v(TAG, "        + already installed; applying");
17027                    }
17028                    PermissionsState perms = ps.getPermissionsState();
17029                    BasePermission bp = mSettings.mPermissions.get(permName);
17030                    if (bp != null) {
17031                        if (isGranted) {
17032                            perms.grantRuntimePermission(bp, userId);
17033                        }
17034                        if (newFlagSet != 0) {
17035                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17036                        }
17037                    }
17038                } else {
17039                    // Need to wait for post-restore install to apply the grant
17040                    if (DEBUG_BACKUP) {
17041                        Slog.v(TAG, "        - not yet installed; saving for later");
17042                    }
17043                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17044                            isGranted, newFlagSet, userId);
17045                }
17046            } else {
17047                PackageManagerService.reportSettingsProblem(Log.WARN,
17048                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17049                XmlUtils.skipCurrentTag(parser);
17050            }
17051        }
17052
17053        scheduleWriteSettingsLocked();
17054        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17055    }
17056
17057    @Override
17058    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17059            int sourceUserId, int targetUserId, int flags) {
17060        mContext.enforceCallingOrSelfPermission(
17061                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17062        int callingUid = Binder.getCallingUid();
17063        enforceOwnerRights(ownerPackage, callingUid);
17064        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17065        if (intentFilter.countActions() == 0) {
17066            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17067            return;
17068        }
17069        synchronized (mPackages) {
17070            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17071                    ownerPackage, targetUserId, flags);
17072            CrossProfileIntentResolver resolver =
17073                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17074            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17075            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17076            if (existing != null) {
17077                int size = existing.size();
17078                for (int i = 0; i < size; i++) {
17079                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17080                        return;
17081                    }
17082                }
17083            }
17084            resolver.addFilter(newFilter);
17085            scheduleWritePackageRestrictionsLocked(sourceUserId);
17086        }
17087    }
17088
17089    @Override
17090    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17091        mContext.enforceCallingOrSelfPermission(
17092                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17093        int callingUid = Binder.getCallingUid();
17094        enforceOwnerRights(ownerPackage, callingUid);
17095        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17096        synchronized (mPackages) {
17097            CrossProfileIntentResolver resolver =
17098                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17099            ArraySet<CrossProfileIntentFilter> set =
17100                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17101            for (CrossProfileIntentFilter filter : set) {
17102                if (filter.getOwnerPackage().equals(ownerPackage)) {
17103                    resolver.removeFilter(filter);
17104                }
17105            }
17106            scheduleWritePackageRestrictionsLocked(sourceUserId);
17107        }
17108    }
17109
17110    // Enforcing that callingUid is owning pkg on userId
17111    private void enforceOwnerRights(String pkg, int callingUid) {
17112        // The system owns everything.
17113        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17114            return;
17115        }
17116        int callingUserId = UserHandle.getUserId(callingUid);
17117        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17118        if (pi == null) {
17119            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17120                    + callingUserId);
17121        }
17122        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17123            throw new SecurityException("Calling uid " + callingUid
17124                    + " does not own package " + pkg);
17125        }
17126    }
17127
17128    @Override
17129    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17130        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17131    }
17132
17133    private Intent getHomeIntent() {
17134        Intent intent = new Intent(Intent.ACTION_MAIN);
17135        intent.addCategory(Intent.CATEGORY_HOME);
17136        return intent;
17137    }
17138
17139    private IntentFilter getHomeFilter() {
17140        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17141        filter.addCategory(Intent.CATEGORY_HOME);
17142        filter.addCategory(Intent.CATEGORY_DEFAULT);
17143        return filter;
17144    }
17145
17146    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17147            int userId) {
17148        Intent intent  = getHomeIntent();
17149        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17150                PackageManager.GET_META_DATA, userId);
17151        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17152                true, false, false, userId);
17153
17154        allHomeCandidates.clear();
17155        if (list != null) {
17156            for (ResolveInfo ri : list) {
17157                allHomeCandidates.add(ri);
17158            }
17159        }
17160        return (preferred == null || preferred.activityInfo == null)
17161                ? null
17162                : new ComponentName(preferred.activityInfo.packageName,
17163                        preferred.activityInfo.name);
17164    }
17165
17166    @Override
17167    public void setHomeActivity(ComponentName comp, int userId) {
17168        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17169        getHomeActivitiesAsUser(homeActivities, userId);
17170
17171        boolean found = false;
17172
17173        final int size = homeActivities.size();
17174        final ComponentName[] set = new ComponentName[size];
17175        for (int i = 0; i < size; i++) {
17176            final ResolveInfo candidate = homeActivities.get(i);
17177            final ActivityInfo info = candidate.activityInfo;
17178            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17179            set[i] = activityName;
17180            if (!found && activityName.equals(comp)) {
17181                found = true;
17182            }
17183        }
17184        if (!found) {
17185            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17186                    + userId);
17187        }
17188        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17189                set, comp, userId);
17190    }
17191
17192    private @Nullable String getSetupWizardPackageName() {
17193        final Intent intent = new Intent(Intent.ACTION_MAIN);
17194        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17195
17196        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17197                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17198                        | MATCH_DISABLED_COMPONENTS,
17199                UserHandle.myUserId());
17200        if (matches.size() == 1) {
17201            return matches.get(0).getComponentInfo().packageName;
17202        } else {
17203            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17204                    + ": matches=" + matches);
17205            return null;
17206        }
17207    }
17208
17209    @Override
17210    public void setApplicationEnabledSetting(String appPackageName,
17211            int newState, int flags, int userId, String callingPackage) {
17212        if (!sUserManager.exists(userId)) return;
17213        if (callingPackage == null) {
17214            callingPackage = Integer.toString(Binder.getCallingUid());
17215        }
17216        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17217    }
17218
17219    @Override
17220    public void setComponentEnabledSetting(ComponentName componentName,
17221            int newState, int flags, int userId) {
17222        if (!sUserManager.exists(userId)) return;
17223        setEnabledSetting(componentName.getPackageName(),
17224                componentName.getClassName(), newState, flags, userId, null);
17225    }
17226
17227    private void setEnabledSetting(final String packageName, String className, int newState,
17228            final int flags, int userId, String callingPackage) {
17229        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17230              || newState == COMPONENT_ENABLED_STATE_ENABLED
17231              || newState == COMPONENT_ENABLED_STATE_DISABLED
17232              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17233              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17234            throw new IllegalArgumentException("Invalid new component state: "
17235                    + newState);
17236        }
17237        PackageSetting pkgSetting;
17238        final int uid = Binder.getCallingUid();
17239        final int permission;
17240        if (uid == Process.SYSTEM_UID) {
17241            permission = PackageManager.PERMISSION_GRANTED;
17242        } else {
17243            permission = mContext.checkCallingOrSelfPermission(
17244                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17245        }
17246        enforceCrossUserPermission(uid, userId,
17247                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17248        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17249        boolean sendNow = false;
17250        boolean isApp = (className == null);
17251        String componentName = isApp ? packageName : className;
17252        int packageUid = -1;
17253        ArrayList<String> components;
17254
17255        // writer
17256        synchronized (mPackages) {
17257            pkgSetting = mSettings.mPackages.get(packageName);
17258            if (pkgSetting == null) {
17259                if (className == null) {
17260                    throw new IllegalArgumentException("Unknown package: " + packageName);
17261                }
17262                throw new IllegalArgumentException(
17263                        "Unknown component: " + packageName + "/" + className);
17264            }
17265            // Allow root and verify that userId is not being specified by a different user
17266            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17267                throw new SecurityException(
17268                        "Permission Denial: attempt to change component state from pid="
17269                        + Binder.getCallingPid()
17270                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17271            }
17272            if (className == null) {
17273                // We're dealing with an application/package level state change
17274                if (pkgSetting.getEnabled(userId) == newState) {
17275                    // Nothing to do
17276                    return;
17277                }
17278                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17279                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17280                    // Don't care about who enables an app.
17281                    callingPackage = null;
17282                }
17283                pkgSetting.setEnabled(newState, userId, callingPackage);
17284                // pkgSetting.pkg.mSetEnabled = newState;
17285            } else {
17286                // We're dealing with a component level state change
17287                // First, verify that this is a valid class name.
17288                PackageParser.Package pkg = pkgSetting.pkg;
17289                if (pkg == null || !pkg.hasComponentClassName(className)) {
17290                    if (pkg != null &&
17291                            pkg.applicationInfo.targetSdkVersion >=
17292                                    Build.VERSION_CODES.JELLY_BEAN) {
17293                        throw new IllegalArgumentException("Component class " + className
17294                                + " does not exist in " + packageName);
17295                    } else {
17296                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17297                                + className + " does not exist in " + packageName);
17298                    }
17299                }
17300                switch (newState) {
17301                case COMPONENT_ENABLED_STATE_ENABLED:
17302                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17303                        return;
17304                    }
17305                    break;
17306                case COMPONENT_ENABLED_STATE_DISABLED:
17307                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17308                        return;
17309                    }
17310                    break;
17311                case COMPONENT_ENABLED_STATE_DEFAULT:
17312                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17313                        return;
17314                    }
17315                    break;
17316                default:
17317                    Slog.e(TAG, "Invalid new component state: " + newState);
17318                    return;
17319                }
17320            }
17321            scheduleWritePackageRestrictionsLocked(userId);
17322            components = mPendingBroadcasts.get(userId, packageName);
17323            final boolean newPackage = components == null;
17324            if (newPackage) {
17325                components = new ArrayList<String>();
17326            }
17327            if (!components.contains(componentName)) {
17328                components.add(componentName);
17329            }
17330            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17331                sendNow = true;
17332                // Purge entry from pending broadcast list if another one exists already
17333                // since we are sending one right away.
17334                mPendingBroadcasts.remove(userId, packageName);
17335            } else {
17336                if (newPackage) {
17337                    mPendingBroadcasts.put(userId, packageName, components);
17338                }
17339                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17340                    // Schedule a message
17341                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17342                }
17343            }
17344        }
17345
17346        long callingId = Binder.clearCallingIdentity();
17347        try {
17348            if (sendNow) {
17349                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17350                sendPackageChangedBroadcast(packageName,
17351                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17352            }
17353        } finally {
17354            Binder.restoreCallingIdentity(callingId);
17355        }
17356    }
17357
17358    @Override
17359    public void flushPackageRestrictionsAsUser(int userId) {
17360        if (!sUserManager.exists(userId)) {
17361            return;
17362        }
17363        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17364                false /* checkShell */, "flushPackageRestrictions");
17365        synchronized (mPackages) {
17366            mSettings.writePackageRestrictionsLPr(userId);
17367            mDirtyUsers.remove(userId);
17368            if (mDirtyUsers.isEmpty()) {
17369                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17370            }
17371        }
17372    }
17373
17374    private void sendPackageChangedBroadcast(String packageName,
17375            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17376        if (DEBUG_INSTALL)
17377            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17378                    + componentNames);
17379        Bundle extras = new Bundle(4);
17380        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17381        String nameList[] = new String[componentNames.size()];
17382        componentNames.toArray(nameList);
17383        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17384        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17385        extras.putInt(Intent.EXTRA_UID, packageUid);
17386        // If this is not reporting a change of the overall package, then only send it
17387        // to registered receivers.  We don't want to launch a swath of apps for every
17388        // little component state change.
17389        final int flags = !componentNames.contains(packageName)
17390                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17391        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17392                new int[] {UserHandle.getUserId(packageUid)});
17393    }
17394
17395    @Override
17396    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17397        if (!sUserManager.exists(userId)) return;
17398        final int uid = Binder.getCallingUid();
17399        final int permission = mContext.checkCallingOrSelfPermission(
17400                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17401        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17402        enforceCrossUserPermission(uid, userId,
17403                true /* requireFullPermission */, true /* checkShell */, "stop package");
17404        // writer
17405        synchronized (mPackages) {
17406            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17407                    allowedByPermission, uid, userId)) {
17408                scheduleWritePackageRestrictionsLocked(userId);
17409            }
17410        }
17411    }
17412
17413    @Override
17414    public String getInstallerPackageName(String packageName) {
17415        // reader
17416        synchronized (mPackages) {
17417            return mSettings.getInstallerPackageNameLPr(packageName);
17418        }
17419    }
17420
17421    @Override
17422    public int getApplicationEnabledSetting(String packageName, int userId) {
17423        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17424        int uid = Binder.getCallingUid();
17425        enforceCrossUserPermission(uid, userId,
17426                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17427        // reader
17428        synchronized (mPackages) {
17429            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17430        }
17431    }
17432
17433    @Override
17434    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17435        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17436        int uid = Binder.getCallingUid();
17437        enforceCrossUserPermission(uid, userId,
17438                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17439        // reader
17440        synchronized (mPackages) {
17441            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17442        }
17443    }
17444
17445    @Override
17446    public void enterSafeMode() {
17447        enforceSystemOrRoot("Only the system can request entering safe mode");
17448
17449        if (!mSystemReady) {
17450            mSafeMode = true;
17451        }
17452    }
17453
17454    @Override
17455    public void systemReady() {
17456        mSystemReady = true;
17457
17458        // Read the compatibilty setting when the system is ready.
17459        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17460                mContext.getContentResolver(),
17461                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17462        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17463        if (DEBUG_SETTINGS) {
17464            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17465        }
17466
17467        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17468
17469        synchronized (mPackages) {
17470            // Verify that all of the preferred activity components actually
17471            // exist.  It is possible for applications to be updated and at
17472            // that point remove a previously declared activity component that
17473            // had been set as a preferred activity.  We try to clean this up
17474            // the next time we encounter that preferred activity, but it is
17475            // possible for the user flow to never be able to return to that
17476            // situation so here we do a sanity check to make sure we haven't
17477            // left any junk around.
17478            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17479            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17480                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17481                removed.clear();
17482                for (PreferredActivity pa : pir.filterSet()) {
17483                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17484                        removed.add(pa);
17485                    }
17486                }
17487                if (removed.size() > 0) {
17488                    for (int r=0; r<removed.size(); r++) {
17489                        PreferredActivity pa = removed.get(r);
17490                        Slog.w(TAG, "Removing dangling preferred activity: "
17491                                + pa.mPref.mComponent);
17492                        pir.removeFilter(pa);
17493                    }
17494                    mSettings.writePackageRestrictionsLPr(
17495                            mSettings.mPreferredActivities.keyAt(i));
17496                }
17497            }
17498
17499            for (int userId : UserManagerService.getInstance().getUserIds()) {
17500                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17501                    grantPermissionsUserIds = ArrayUtils.appendInt(
17502                            grantPermissionsUserIds, userId);
17503                }
17504            }
17505        }
17506        sUserManager.systemReady();
17507
17508        // If we upgraded grant all default permissions before kicking off.
17509        for (int userId : grantPermissionsUserIds) {
17510            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17511        }
17512
17513        // Kick off any messages waiting for system ready
17514        if (mPostSystemReadyMessages != null) {
17515            for (Message msg : mPostSystemReadyMessages) {
17516                msg.sendToTarget();
17517            }
17518            mPostSystemReadyMessages = null;
17519        }
17520
17521        // Watch for external volumes that come and go over time
17522        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17523        storage.registerListener(mStorageListener);
17524
17525        mInstallerService.systemReady();
17526        mPackageDexOptimizer.systemReady();
17527
17528        MountServiceInternal mountServiceInternal = LocalServices.getService(
17529                MountServiceInternal.class);
17530        mountServiceInternal.addExternalStoragePolicy(
17531                new MountServiceInternal.ExternalStorageMountPolicy() {
17532            @Override
17533            public int getMountMode(int uid, String packageName) {
17534                if (Process.isIsolated(uid)) {
17535                    return Zygote.MOUNT_EXTERNAL_NONE;
17536                }
17537                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17538                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17539                }
17540                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17541                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17542                }
17543                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17544                    return Zygote.MOUNT_EXTERNAL_READ;
17545                }
17546                return Zygote.MOUNT_EXTERNAL_WRITE;
17547            }
17548
17549            @Override
17550            public boolean hasExternalStorage(int uid, String packageName) {
17551                return true;
17552            }
17553        });
17554
17555        // Now that we're mostly running, clean up stale users and apps
17556        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17557        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17558    }
17559
17560    @Override
17561    public boolean isSafeMode() {
17562        return mSafeMode;
17563    }
17564
17565    @Override
17566    public boolean hasSystemUidErrors() {
17567        return mHasSystemUidErrors;
17568    }
17569
17570    static String arrayToString(int[] array) {
17571        StringBuffer buf = new StringBuffer(128);
17572        buf.append('[');
17573        if (array != null) {
17574            for (int i=0; i<array.length; i++) {
17575                if (i > 0) buf.append(", ");
17576                buf.append(array[i]);
17577            }
17578        }
17579        buf.append(']');
17580        return buf.toString();
17581    }
17582
17583    static class DumpState {
17584        public static final int DUMP_LIBS = 1 << 0;
17585        public static final int DUMP_FEATURES = 1 << 1;
17586        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17587        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17588        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17589        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17590        public static final int DUMP_PERMISSIONS = 1 << 6;
17591        public static final int DUMP_PACKAGES = 1 << 7;
17592        public static final int DUMP_SHARED_USERS = 1 << 8;
17593        public static final int DUMP_MESSAGES = 1 << 9;
17594        public static final int DUMP_PROVIDERS = 1 << 10;
17595        public static final int DUMP_VERIFIERS = 1 << 11;
17596        public static final int DUMP_PREFERRED = 1 << 12;
17597        public static final int DUMP_PREFERRED_XML = 1 << 13;
17598        public static final int DUMP_KEYSETS = 1 << 14;
17599        public static final int DUMP_VERSION = 1 << 15;
17600        public static final int DUMP_INSTALLS = 1 << 16;
17601        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17602        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17603        public static final int DUMP_FROZEN = 1 << 19;
17604
17605        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17606
17607        private int mTypes;
17608
17609        private int mOptions;
17610
17611        private boolean mTitlePrinted;
17612
17613        private SharedUserSetting mSharedUser;
17614
17615        public boolean isDumping(int type) {
17616            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17617                return true;
17618            }
17619
17620            return (mTypes & type) != 0;
17621        }
17622
17623        public void setDump(int type) {
17624            mTypes |= type;
17625        }
17626
17627        public boolean isOptionEnabled(int option) {
17628            return (mOptions & option) != 0;
17629        }
17630
17631        public void setOptionEnabled(int option) {
17632            mOptions |= option;
17633        }
17634
17635        public boolean onTitlePrinted() {
17636            final boolean printed = mTitlePrinted;
17637            mTitlePrinted = true;
17638            return printed;
17639        }
17640
17641        public boolean getTitlePrinted() {
17642            return mTitlePrinted;
17643        }
17644
17645        public void setTitlePrinted(boolean enabled) {
17646            mTitlePrinted = enabled;
17647        }
17648
17649        public SharedUserSetting getSharedUser() {
17650            return mSharedUser;
17651        }
17652
17653        public void setSharedUser(SharedUserSetting user) {
17654            mSharedUser = user;
17655        }
17656    }
17657
17658    @Override
17659    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17660            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17661        (new PackageManagerShellCommand(this)).exec(
17662                this, in, out, err, args, resultReceiver);
17663    }
17664
17665    @Override
17666    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17667        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17668                != PackageManager.PERMISSION_GRANTED) {
17669            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17670                    + Binder.getCallingPid()
17671                    + ", uid=" + Binder.getCallingUid()
17672                    + " without permission "
17673                    + android.Manifest.permission.DUMP);
17674            return;
17675        }
17676
17677        DumpState dumpState = new DumpState();
17678        boolean fullPreferred = false;
17679        boolean checkin = false;
17680
17681        String packageName = null;
17682        ArraySet<String> permissionNames = null;
17683
17684        int opti = 0;
17685        while (opti < args.length) {
17686            String opt = args[opti];
17687            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17688                break;
17689            }
17690            opti++;
17691
17692            if ("-a".equals(opt)) {
17693                // Right now we only know how to print all.
17694            } else if ("-h".equals(opt)) {
17695                pw.println("Package manager dump options:");
17696                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17697                pw.println("    --checkin: dump for a checkin");
17698                pw.println("    -f: print details of intent filters");
17699                pw.println("    -h: print this help");
17700                pw.println("  cmd may be one of:");
17701                pw.println("    l[ibraries]: list known shared libraries");
17702                pw.println("    f[eatures]: list device features");
17703                pw.println("    k[eysets]: print known keysets");
17704                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17705                pw.println("    perm[issions]: dump permissions");
17706                pw.println("    permission [name ...]: dump declaration and use of given permission");
17707                pw.println("    pref[erred]: print preferred package settings");
17708                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17709                pw.println("    prov[iders]: dump content providers");
17710                pw.println("    p[ackages]: dump installed packages");
17711                pw.println("    s[hared-users]: dump shared user IDs");
17712                pw.println("    m[essages]: print collected runtime messages");
17713                pw.println("    v[erifiers]: print package verifier info");
17714                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17715                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17716                pw.println("    version: print database version info");
17717                pw.println("    write: write current settings now");
17718                pw.println("    installs: details about install sessions");
17719                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17720                pw.println("    <package.name>: info about given package");
17721                return;
17722            } else if ("--checkin".equals(opt)) {
17723                checkin = true;
17724            } else if ("-f".equals(opt)) {
17725                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17726            } else {
17727                pw.println("Unknown argument: " + opt + "; use -h for help");
17728            }
17729        }
17730
17731        // Is the caller requesting to dump a particular piece of data?
17732        if (opti < args.length) {
17733            String cmd = args[opti];
17734            opti++;
17735            // Is this a package name?
17736            if ("android".equals(cmd) || cmd.contains(".")) {
17737                packageName = cmd;
17738                // When dumping a single package, we always dump all of its
17739                // filter information since the amount of data will be reasonable.
17740                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17741            } else if ("check-permission".equals(cmd)) {
17742                if (opti >= args.length) {
17743                    pw.println("Error: check-permission missing permission argument");
17744                    return;
17745                }
17746                String perm = args[opti];
17747                opti++;
17748                if (opti >= args.length) {
17749                    pw.println("Error: check-permission missing package argument");
17750                    return;
17751                }
17752                String pkg = args[opti];
17753                opti++;
17754                int user = UserHandle.getUserId(Binder.getCallingUid());
17755                if (opti < args.length) {
17756                    try {
17757                        user = Integer.parseInt(args[opti]);
17758                    } catch (NumberFormatException e) {
17759                        pw.println("Error: check-permission user argument is not a number: "
17760                                + args[opti]);
17761                        return;
17762                    }
17763                }
17764                pw.println(checkPermission(perm, pkg, user));
17765                return;
17766            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17767                dumpState.setDump(DumpState.DUMP_LIBS);
17768            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17769                dumpState.setDump(DumpState.DUMP_FEATURES);
17770            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17771                if (opti >= args.length) {
17772                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17773                            | DumpState.DUMP_SERVICE_RESOLVERS
17774                            | DumpState.DUMP_RECEIVER_RESOLVERS
17775                            | DumpState.DUMP_CONTENT_RESOLVERS);
17776                } else {
17777                    while (opti < args.length) {
17778                        String name = args[opti];
17779                        if ("a".equals(name) || "activity".equals(name)) {
17780                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17781                        } else if ("s".equals(name) || "service".equals(name)) {
17782                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17783                        } else if ("r".equals(name) || "receiver".equals(name)) {
17784                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17785                        } else if ("c".equals(name) || "content".equals(name)) {
17786                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17787                        } else {
17788                            pw.println("Error: unknown resolver table type: " + name);
17789                            return;
17790                        }
17791                        opti++;
17792                    }
17793                }
17794            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17795                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17796            } else if ("permission".equals(cmd)) {
17797                if (opti >= args.length) {
17798                    pw.println("Error: permission requires permission name");
17799                    return;
17800                }
17801                permissionNames = new ArraySet<>();
17802                while (opti < args.length) {
17803                    permissionNames.add(args[opti]);
17804                    opti++;
17805                }
17806                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17807                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17808            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17809                dumpState.setDump(DumpState.DUMP_PREFERRED);
17810            } else if ("preferred-xml".equals(cmd)) {
17811                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17812                if (opti < args.length && "--full".equals(args[opti])) {
17813                    fullPreferred = true;
17814                    opti++;
17815                }
17816            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17817                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17818            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17819                dumpState.setDump(DumpState.DUMP_PACKAGES);
17820            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17821                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17822            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17823                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17824            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17825                dumpState.setDump(DumpState.DUMP_MESSAGES);
17826            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17827                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17828            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17829                    || "intent-filter-verifiers".equals(cmd)) {
17830                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17831            } else if ("version".equals(cmd)) {
17832                dumpState.setDump(DumpState.DUMP_VERSION);
17833            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17834                dumpState.setDump(DumpState.DUMP_KEYSETS);
17835            } else if ("installs".equals(cmd)) {
17836                dumpState.setDump(DumpState.DUMP_INSTALLS);
17837            } else if ("frozen".equals(cmd)) {
17838                dumpState.setDump(DumpState.DUMP_FROZEN);
17839            } else if ("write".equals(cmd)) {
17840                synchronized (mPackages) {
17841                    mSettings.writeLPr();
17842                    pw.println("Settings written.");
17843                    return;
17844                }
17845            }
17846        }
17847
17848        if (checkin) {
17849            pw.println("vers,1");
17850        }
17851
17852        // reader
17853        synchronized (mPackages) {
17854            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17855                if (!checkin) {
17856                    if (dumpState.onTitlePrinted())
17857                        pw.println();
17858                    pw.println("Database versions:");
17859                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17860                }
17861            }
17862
17863            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17864                if (!checkin) {
17865                    if (dumpState.onTitlePrinted())
17866                        pw.println();
17867                    pw.println("Verifiers:");
17868                    pw.print("  Required: ");
17869                    pw.print(mRequiredVerifierPackage);
17870                    pw.print(" (uid=");
17871                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17872                            UserHandle.USER_SYSTEM));
17873                    pw.println(")");
17874                } else if (mRequiredVerifierPackage != null) {
17875                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17876                    pw.print(",");
17877                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17878                            UserHandle.USER_SYSTEM));
17879                }
17880            }
17881
17882            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17883                    packageName == null) {
17884                if (mIntentFilterVerifierComponent != null) {
17885                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17886                    if (!checkin) {
17887                        if (dumpState.onTitlePrinted())
17888                            pw.println();
17889                        pw.println("Intent Filter Verifier:");
17890                        pw.print("  Using: ");
17891                        pw.print(verifierPackageName);
17892                        pw.print(" (uid=");
17893                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17894                                UserHandle.USER_SYSTEM));
17895                        pw.println(")");
17896                    } else if (verifierPackageName != null) {
17897                        pw.print("ifv,"); pw.print(verifierPackageName);
17898                        pw.print(",");
17899                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17900                                UserHandle.USER_SYSTEM));
17901                    }
17902                } else {
17903                    pw.println();
17904                    pw.println("No Intent Filter Verifier available!");
17905                }
17906            }
17907
17908            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17909                boolean printedHeader = false;
17910                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17911                while (it.hasNext()) {
17912                    String name = it.next();
17913                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17914                    if (!checkin) {
17915                        if (!printedHeader) {
17916                            if (dumpState.onTitlePrinted())
17917                                pw.println();
17918                            pw.println("Libraries:");
17919                            printedHeader = true;
17920                        }
17921                        pw.print("  ");
17922                    } else {
17923                        pw.print("lib,");
17924                    }
17925                    pw.print(name);
17926                    if (!checkin) {
17927                        pw.print(" -> ");
17928                    }
17929                    if (ent.path != null) {
17930                        if (!checkin) {
17931                            pw.print("(jar) ");
17932                            pw.print(ent.path);
17933                        } else {
17934                            pw.print(",jar,");
17935                            pw.print(ent.path);
17936                        }
17937                    } else {
17938                        if (!checkin) {
17939                            pw.print("(apk) ");
17940                            pw.print(ent.apk);
17941                        } else {
17942                            pw.print(",apk,");
17943                            pw.print(ent.apk);
17944                        }
17945                    }
17946                    pw.println();
17947                }
17948            }
17949
17950            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17951                if (dumpState.onTitlePrinted())
17952                    pw.println();
17953                if (!checkin) {
17954                    pw.println("Features:");
17955                }
17956
17957                for (FeatureInfo feat : mAvailableFeatures.values()) {
17958                    if (checkin) {
17959                        pw.print("feat,");
17960                        pw.print(feat.name);
17961                        pw.print(",");
17962                        pw.println(feat.version);
17963                    } else {
17964                        pw.print("  ");
17965                        pw.print(feat.name);
17966                        if (feat.version > 0) {
17967                            pw.print(" version=");
17968                            pw.print(feat.version);
17969                        }
17970                        pw.println();
17971                    }
17972                }
17973            }
17974
17975            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17976                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17977                        : "Activity Resolver Table:", "  ", packageName,
17978                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17979                    dumpState.setTitlePrinted(true);
17980                }
17981            }
17982            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17983                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17984                        : "Receiver Resolver Table:", "  ", packageName,
17985                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17986                    dumpState.setTitlePrinted(true);
17987                }
17988            }
17989            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17990                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17991                        : "Service Resolver Table:", "  ", packageName,
17992                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17993                    dumpState.setTitlePrinted(true);
17994                }
17995            }
17996            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17997                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17998                        : "Provider Resolver Table:", "  ", packageName,
17999                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18000                    dumpState.setTitlePrinted(true);
18001                }
18002            }
18003
18004            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18005                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18006                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18007                    int user = mSettings.mPreferredActivities.keyAt(i);
18008                    if (pir.dump(pw,
18009                            dumpState.getTitlePrinted()
18010                                ? "\nPreferred Activities User " + user + ":"
18011                                : "Preferred Activities User " + user + ":", "  ",
18012                            packageName, true, false)) {
18013                        dumpState.setTitlePrinted(true);
18014                    }
18015                }
18016            }
18017
18018            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18019                pw.flush();
18020                FileOutputStream fout = new FileOutputStream(fd);
18021                BufferedOutputStream str = new BufferedOutputStream(fout);
18022                XmlSerializer serializer = new FastXmlSerializer();
18023                try {
18024                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18025                    serializer.startDocument(null, true);
18026                    serializer.setFeature(
18027                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18028                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18029                    serializer.endDocument();
18030                    serializer.flush();
18031                } catch (IllegalArgumentException e) {
18032                    pw.println("Failed writing: " + e);
18033                } catch (IllegalStateException e) {
18034                    pw.println("Failed writing: " + e);
18035                } catch (IOException e) {
18036                    pw.println("Failed writing: " + e);
18037                }
18038            }
18039
18040            if (!checkin
18041                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18042                    && packageName == null) {
18043                pw.println();
18044                int count = mSettings.mPackages.size();
18045                if (count == 0) {
18046                    pw.println("No applications!");
18047                    pw.println();
18048                } else {
18049                    final String prefix = "  ";
18050                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18051                    if (allPackageSettings.size() == 0) {
18052                        pw.println("No domain preferred apps!");
18053                        pw.println();
18054                    } else {
18055                        pw.println("App verification status:");
18056                        pw.println();
18057                        count = 0;
18058                        for (PackageSetting ps : allPackageSettings) {
18059                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18060                            if (ivi == null || ivi.getPackageName() == null) continue;
18061                            pw.println(prefix + "Package: " + ivi.getPackageName());
18062                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18063                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18064                            pw.println();
18065                            count++;
18066                        }
18067                        if (count == 0) {
18068                            pw.println(prefix + "No app verification established.");
18069                            pw.println();
18070                        }
18071                        for (int userId : sUserManager.getUserIds()) {
18072                            pw.println("App linkages for user " + userId + ":");
18073                            pw.println();
18074                            count = 0;
18075                            for (PackageSetting ps : allPackageSettings) {
18076                                final long status = ps.getDomainVerificationStatusForUser(userId);
18077                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18078                                    continue;
18079                                }
18080                                pw.println(prefix + "Package: " + ps.name);
18081                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18082                                String statusStr = IntentFilterVerificationInfo.
18083                                        getStatusStringFromValue(status);
18084                                pw.println(prefix + "Status:  " + statusStr);
18085                                pw.println();
18086                                count++;
18087                            }
18088                            if (count == 0) {
18089                                pw.println(prefix + "No configured app linkages.");
18090                                pw.println();
18091                            }
18092                        }
18093                    }
18094                }
18095            }
18096
18097            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18098                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18099                if (packageName == null && permissionNames == null) {
18100                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18101                        if (iperm == 0) {
18102                            if (dumpState.onTitlePrinted())
18103                                pw.println();
18104                            pw.println("AppOp Permissions:");
18105                        }
18106                        pw.print("  AppOp Permission ");
18107                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18108                        pw.println(":");
18109                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18110                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18111                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18112                        }
18113                    }
18114                }
18115            }
18116
18117            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18118                boolean printedSomething = false;
18119                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18120                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18121                        continue;
18122                    }
18123                    if (!printedSomething) {
18124                        if (dumpState.onTitlePrinted())
18125                            pw.println();
18126                        pw.println("Registered ContentProviders:");
18127                        printedSomething = true;
18128                    }
18129                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18130                    pw.print("    "); pw.println(p.toString());
18131                }
18132                printedSomething = false;
18133                for (Map.Entry<String, PackageParser.Provider> entry :
18134                        mProvidersByAuthority.entrySet()) {
18135                    PackageParser.Provider p = entry.getValue();
18136                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18137                        continue;
18138                    }
18139                    if (!printedSomething) {
18140                        if (dumpState.onTitlePrinted())
18141                            pw.println();
18142                        pw.println("ContentProvider Authorities:");
18143                        printedSomething = true;
18144                    }
18145                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18146                    pw.print("    "); pw.println(p.toString());
18147                    if (p.info != null && p.info.applicationInfo != null) {
18148                        final String appInfo = p.info.applicationInfo.toString();
18149                        pw.print("      applicationInfo="); pw.println(appInfo);
18150                    }
18151                }
18152            }
18153
18154            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18155                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18156            }
18157
18158            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18159                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18160            }
18161
18162            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18163                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18164            }
18165
18166            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18167                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18168            }
18169
18170            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18171                // XXX should handle packageName != null by dumping only install data that
18172                // the given package is involved with.
18173                if (dumpState.onTitlePrinted()) pw.println();
18174                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18175            }
18176
18177            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18178                // XXX should handle packageName != null by dumping only install data that
18179                // the given package is involved with.
18180                if (dumpState.onTitlePrinted()) pw.println();
18181
18182                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18183                ipw.println();
18184                ipw.println("Frozen packages:");
18185                ipw.increaseIndent();
18186                if (mFrozenPackages.size() == 0) {
18187                    ipw.println("(none)");
18188                } else {
18189                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18190                        ipw.println(mFrozenPackages.valueAt(i));
18191                    }
18192                }
18193                ipw.decreaseIndent();
18194            }
18195
18196            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18197                if (dumpState.onTitlePrinted()) pw.println();
18198                mSettings.dumpReadMessagesLPr(pw, dumpState);
18199
18200                pw.println();
18201                pw.println("Package warning messages:");
18202                BufferedReader in = null;
18203                String line = null;
18204                try {
18205                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18206                    while ((line = in.readLine()) != null) {
18207                        if (line.contains("ignored: updated version")) continue;
18208                        pw.println(line);
18209                    }
18210                } catch (IOException ignored) {
18211                } finally {
18212                    IoUtils.closeQuietly(in);
18213                }
18214            }
18215
18216            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18217                BufferedReader in = null;
18218                String line = null;
18219                try {
18220                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18221                    while ((line = in.readLine()) != null) {
18222                        if (line.contains("ignored: updated version")) continue;
18223                        pw.print("msg,");
18224                        pw.println(line);
18225                    }
18226                } catch (IOException ignored) {
18227                } finally {
18228                    IoUtils.closeQuietly(in);
18229                }
18230            }
18231        }
18232    }
18233
18234    private String dumpDomainString(String packageName) {
18235        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18236                .getList();
18237        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18238
18239        ArraySet<String> result = new ArraySet<>();
18240        if (iviList.size() > 0) {
18241            for (IntentFilterVerificationInfo ivi : iviList) {
18242                for (String host : ivi.getDomains()) {
18243                    result.add(host);
18244                }
18245            }
18246        }
18247        if (filters != null && filters.size() > 0) {
18248            for (IntentFilter filter : filters) {
18249                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18250                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18251                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18252                    result.addAll(filter.getHostsList());
18253                }
18254            }
18255        }
18256
18257        StringBuilder sb = new StringBuilder(result.size() * 16);
18258        for (String domain : result) {
18259            if (sb.length() > 0) sb.append(" ");
18260            sb.append(domain);
18261        }
18262        return sb.toString();
18263    }
18264
18265    // ------- apps on sdcard specific code -------
18266    static final boolean DEBUG_SD_INSTALL = false;
18267
18268    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18269
18270    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18271
18272    private boolean mMediaMounted = false;
18273
18274    static String getEncryptKey() {
18275        try {
18276            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18277                    SD_ENCRYPTION_KEYSTORE_NAME);
18278            if (sdEncKey == null) {
18279                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18280                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18281                if (sdEncKey == null) {
18282                    Slog.e(TAG, "Failed to create encryption keys");
18283                    return null;
18284                }
18285            }
18286            return sdEncKey;
18287        } catch (NoSuchAlgorithmException nsae) {
18288            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18289            return null;
18290        } catch (IOException ioe) {
18291            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18292            return null;
18293        }
18294    }
18295
18296    /*
18297     * Update media status on PackageManager.
18298     */
18299    @Override
18300    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18301        int callingUid = Binder.getCallingUid();
18302        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18303            throw new SecurityException("Media status can only be updated by the system");
18304        }
18305        // reader; this apparently protects mMediaMounted, but should probably
18306        // be a different lock in that case.
18307        synchronized (mPackages) {
18308            Log.i(TAG, "Updating external media status from "
18309                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18310                    + (mediaStatus ? "mounted" : "unmounted"));
18311            if (DEBUG_SD_INSTALL)
18312                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18313                        + ", mMediaMounted=" + mMediaMounted);
18314            if (mediaStatus == mMediaMounted) {
18315                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18316                        : 0, -1);
18317                mHandler.sendMessage(msg);
18318                return;
18319            }
18320            mMediaMounted = mediaStatus;
18321        }
18322        // Queue up an async operation since the package installation may take a
18323        // little while.
18324        mHandler.post(new Runnable() {
18325            public void run() {
18326                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18327            }
18328        });
18329    }
18330
18331    /**
18332     * Called by MountService when the initial ASECs to scan are available.
18333     * Should block until all the ASEC containers are finished being scanned.
18334     */
18335    public void scanAvailableAsecs() {
18336        updateExternalMediaStatusInner(true, false, false);
18337    }
18338
18339    /*
18340     * Collect information of applications on external media, map them against
18341     * existing containers and update information based on current mount status.
18342     * Please note that we always have to report status if reportStatus has been
18343     * set to true especially when unloading packages.
18344     */
18345    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18346            boolean externalStorage) {
18347        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18348        int[] uidArr = EmptyArray.INT;
18349
18350        final String[] list = PackageHelper.getSecureContainerList();
18351        if (ArrayUtils.isEmpty(list)) {
18352            Log.i(TAG, "No secure containers found");
18353        } else {
18354            // Process list of secure containers and categorize them
18355            // as active or stale based on their package internal state.
18356
18357            // reader
18358            synchronized (mPackages) {
18359                for (String cid : list) {
18360                    // Leave stages untouched for now; installer service owns them
18361                    if (PackageInstallerService.isStageName(cid)) continue;
18362
18363                    if (DEBUG_SD_INSTALL)
18364                        Log.i(TAG, "Processing container " + cid);
18365                    String pkgName = getAsecPackageName(cid);
18366                    if (pkgName == null) {
18367                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18368                        continue;
18369                    }
18370                    if (DEBUG_SD_INSTALL)
18371                        Log.i(TAG, "Looking for pkg : " + pkgName);
18372
18373                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18374                    if (ps == null) {
18375                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18376                        continue;
18377                    }
18378
18379                    /*
18380                     * Skip packages that are not external if we're unmounting
18381                     * external storage.
18382                     */
18383                    if (externalStorage && !isMounted && !isExternal(ps)) {
18384                        continue;
18385                    }
18386
18387                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18388                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18389                    // The package status is changed only if the code path
18390                    // matches between settings and the container id.
18391                    if (ps.codePathString != null
18392                            && ps.codePathString.startsWith(args.getCodePath())) {
18393                        if (DEBUG_SD_INSTALL) {
18394                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18395                                    + " at code path: " + ps.codePathString);
18396                        }
18397
18398                        // We do have a valid package installed on sdcard
18399                        processCids.put(args, ps.codePathString);
18400                        final int uid = ps.appId;
18401                        if (uid != -1) {
18402                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18403                        }
18404                    } else {
18405                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18406                                + ps.codePathString);
18407                    }
18408                }
18409            }
18410
18411            Arrays.sort(uidArr);
18412        }
18413
18414        // Process packages with valid entries.
18415        if (isMounted) {
18416            if (DEBUG_SD_INSTALL)
18417                Log.i(TAG, "Loading packages");
18418            loadMediaPackages(processCids, uidArr, externalStorage);
18419            startCleaningPackages();
18420            mInstallerService.onSecureContainersAvailable();
18421        } else {
18422            if (DEBUG_SD_INSTALL)
18423                Log.i(TAG, "Unloading packages");
18424            unloadMediaPackages(processCids, uidArr, reportStatus);
18425        }
18426    }
18427
18428    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18429            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18430        final int size = infos.size();
18431        final String[] packageNames = new String[size];
18432        final int[] packageUids = new int[size];
18433        for (int i = 0; i < size; i++) {
18434            final ApplicationInfo info = infos.get(i);
18435            packageNames[i] = info.packageName;
18436            packageUids[i] = info.uid;
18437        }
18438        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18439                finishedReceiver);
18440    }
18441
18442    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18443            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18444        sendResourcesChangedBroadcast(mediaStatus, replacing,
18445                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18446    }
18447
18448    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18449            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18450        int size = pkgList.length;
18451        if (size > 0) {
18452            // Send broadcasts here
18453            Bundle extras = new Bundle();
18454            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18455            if (uidArr != null) {
18456                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18457            }
18458            if (replacing) {
18459                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18460            }
18461            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18462                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18463            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18464        }
18465    }
18466
18467   /*
18468     * Look at potentially valid container ids from processCids If package
18469     * information doesn't match the one on record or package scanning fails,
18470     * the cid is added to list of removeCids. We currently don't delete stale
18471     * containers.
18472     */
18473    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18474            boolean externalStorage) {
18475        ArrayList<String> pkgList = new ArrayList<String>();
18476        Set<AsecInstallArgs> keys = processCids.keySet();
18477
18478        for (AsecInstallArgs args : keys) {
18479            String codePath = processCids.get(args);
18480            if (DEBUG_SD_INSTALL)
18481                Log.i(TAG, "Loading container : " + args.cid);
18482            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18483            try {
18484                // Make sure there are no container errors first.
18485                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18486                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18487                            + " when installing from sdcard");
18488                    continue;
18489                }
18490                // Check code path here.
18491                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18492                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18493                            + " does not match one in settings " + codePath);
18494                    continue;
18495                }
18496                // Parse package
18497                int parseFlags = mDefParseFlags;
18498                if (args.isExternalAsec()) {
18499                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18500                }
18501                if (args.isFwdLocked()) {
18502                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18503                }
18504
18505                synchronized (mInstallLock) {
18506                    PackageParser.Package pkg = null;
18507                    try {
18508                        // Sadly we don't know the package name yet to freeze it
18509                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18510                                SCAN_IGNORE_FROZEN, 0, null);
18511                    } catch (PackageManagerException e) {
18512                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18513                    }
18514                    // Scan the package
18515                    if (pkg != null) {
18516                        /*
18517                         * TODO why is the lock being held? doPostInstall is
18518                         * called in other places without the lock. This needs
18519                         * to be straightened out.
18520                         */
18521                        // writer
18522                        synchronized (mPackages) {
18523                            retCode = PackageManager.INSTALL_SUCCEEDED;
18524                            pkgList.add(pkg.packageName);
18525                            // Post process args
18526                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18527                                    pkg.applicationInfo.uid);
18528                        }
18529                    } else {
18530                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18531                    }
18532                }
18533
18534            } finally {
18535                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18536                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18537                }
18538            }
18539        }
18540        // writer
18541        synchronized (mPackages) {
18542            // If the platform SDK has changed since the last time we booted,
18543            // we need to re-grant app permission to catch any new ones that
18544            // appear. This is really a hack, and means that apps can in some
18545            // cases get permissions that the user didn't initially explicitly
18546            // allow... it would be nice to have some better way to handle
18547            // this situation.
18548            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18549                    : mSettings.getInternalVersion();
18550            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18551                    : StorageManager.UUID_PRIVATE_INTERNAL;
18552
18553            int updateFlags = UPDATE_PERMISSIONS_ALL;
18554            if (ver.sdkVersion != mSdkVersion) {
18555                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18556                        + mSdkVersion + "; regranting permissions for external");
18557                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18558            }
18559            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18560
18561            // Yay, everything is now upgraded
18562            ver.forceCurrent();
18563
18564            // can downgrade to reader
18565            // Persist settings
18566            mSettings.writeLPr();
18567        }
18568        // Send a broadcast to let everyone know we are done processing
18569        if (pkgList.size() > 0) {
18570            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18571        }
18572    }
18573
18574   /*
18575     * Utility method to unload a list of specified containers
18576     */
18577    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18578        // Just unmount all valid containers.
18579        for (AsecInstallArgs arg : cidArgs) {
18580            synchronized (mInstallLock) {
18581                arg.doPostDeleteLI(false);
18582           }
18583       }
18584   }
18585
18586    /*
18587     * Unload packages mounted on external media. This involves deleting package
18588     * data from internal structures, sending broadcasts about disabled packages,
18589     * gc'ing to free up references, unmounting all secure containers
18590     * corresponding to packages on external media, and posting a
18591     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18592     * that we always have to post this message if status has been requested no
18593     * matter what.
18594     */
18595    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18596            final boolean reportStatus) {
18597        if (DEBUG_SD_INSTALL)
18598            Log.i(TAG, "unloading media packages");
18599        ArrayList<String> pkgList = new ArrayList<String>();
18600        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18601        final Set<AsecInstallArgs> keys = processCids.keySet();
18602        for (AsecInstallArgs args : keys) {
18603            String pkgName = args.getPackageName();
18604            if (DEBUG_SD_INSTALL)
18605                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18606            // Delete package internally
18607            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18608            synchronized (mInstallLock) {
18609                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18610                final boolean res;
18611                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18612                        "unloadMediaPackages")) {
18613                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18614                            null);
18615                }
18616                if (res) {
18617                    pkgList.add(pkgName);
18618                } else {
18619                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18620                    failedList.add(args);
18621                }
18622            }
18623        }
18624
18625        // reader
18626        synchronized (mPackages) {
18627            // We didn't update the settings after removing each package;
18628            // write them now for all packages.
18629            mSettings.writeLPr();
18630        }
18631
18632        // We have to absolutely send UPDATED_MEDIA_STATUS only
18633        // after confirming that all the receivers processed the ordered
18634        // broadcast when packages get disabled, force a gc to clean things up.
18635        // and unload all the containers.
18636        if (pkgList.size() > 0) {
18637            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18638                    new IIntentReceiver.Stub() {
18639                public void performReceive(Intent intent, int resultCode, String data,
18640                        Bundle extras, boolean ordered, boolean sticky,
18641                        int sendingUser) throws RemoteException {
18642                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18643                            reportStatus ? 1 : 0, 1, keys);
18644                    mHandler.sendMessage(msg);
18645                }
18646            });
18647        } else {
18648            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18649                    keys);
18650            mHandler.sendMessage(msg);
18651        }
18652    }
18653
18654    private void loadPrivatePackages(final VolumeInfo vol) {
18655        mHandler.post(new Runnable() {
18656            @Override
18657            public void run() {
18658                loadPrivatePackagesInner(vol);
18659            }
18660        });
18661    }
18662
18663    private void loadPrivatePackagesInner(VolumeInfo vol) {
18664        final String volumeUuid = vol.fsUuid;
18665        if (TextUtils.isEmpty(volumeUuid)) {
18666            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18667            return;
18668        }
18669
18670        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18671        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18672        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18673
18674        final VersionInfo ver;
18675        final List<PackageSetting> packages;
18676        synchronized (mPackages) {
18677            ver = mSettings.findOrCreateVersion(volumeUuid);
18678            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18679        }
18680
18681        for (PackageSetting ps : packages) {
18682            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18683            synchronized (mInstallLock) {
18684                final PackageParser.Package pkg;
18685                try {
18686                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18687                    loaded.add(pkg.applicationInfo);
18688
18689                } catch (PackageManagerException e) {
18690                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18691                }
18692
18693                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18694                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18695                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18696                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18697                }
18698            }
18699        }
18700
18701        // Reconcile app data for all started/unlocked users
18702        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18703        final UserManager um = mContext.getSystemService(UserManager.class);
18704        for (UserInfo user : um.getUsers()) {
18705            final int flags;
18706            if (um.isUserUnlocked(user.id)) {
18707                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18708            } else if (um.isUserRunning(user.id)) {
18709                flags = StorageManager.FLAG_STORAGE_DE;
18710            } else {
18711                continue;
18712            }
18713
18714            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18715            synchronized (mInstallLock) {
18716                reconcileAppsDataLI(volumeUuid, user.id, flags);
18717            }
18718        }
18719
18720        synchronized (mPackages) {
18721            int updateFlags = UPDATE_PERMISSIONS_ALL;
18722            if (ver.sdkVersion != mSdkVersion) {
18723                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18724                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18725                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18726            }
18727            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18728
18729            // Yay, everything is now upgraded
18730            ver.forceCurrent();
18731
18732            mSettings.writeLPr();
18733        }
18734
18735        for (PackageFreezer freezer : freezers) {
18736            freezer.close();
18737        }
18738
18739        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18740        sendResourcesChangedBroadcast(true, false, loaded, null);
18741    }
18742
18743    private void unloadPrivatePackages(final VolumeInfo vol) {
18744        mHandler.post(new Runnable() {
18745            @Override
18746            public void run() {
18747                unloadPrivatePackagesInner(vol);
18748            }
18749        });
18750    }
18751
18752    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18753        final String volumeUuid = vol.fsUuid;
18754        if (TextUtils.isEmpty(volumeUuid)) {
18755            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18756            return;
18757        }
18758
18759        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18760        synchronized (mInstallLock) {
18761        synchronized (mPackages) {
18762            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18763            for (PackageSetting ps : packages) {
18764                if (ps.pkg == null) continue;
18765
18766                final ApplicationInfo info = ps.pkg.applicationInfo;
18767                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18768                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18769
18770                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18771                        "unloadPrivatePackagesInner")) {
18772                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18773                            false, null)) {
18774                        unloaded.add(info);
18775                    } else {
18776                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18777                    }
18778                }
18779            }
18780
18781            mSettings.writeLPr();
18782        }
18783        }
18784
18785        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18786        sendResourcesChangedBroadcast(false, false, unloaded, null);
18787    }
18788
18789    /**
18790     * Prepare storage areas for given user on all mounted devices.
18791     */
18792    void prepareUserData(int userId, int userSerial, int flags) {
18793        synchronized (mInstallLock) {
18794            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18795            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18796                final String volumeUuid = vol.getFsUuid();
18797                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18798            }
18799        }
18800    }
18801
18802    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18803            boolean allowRecover) {
18804        // Prepare storage and verify that serial numbers are consistent; if
18805        // there's a mismatch we need to destroy to avoid leaking data
18806        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18807        try {
18808            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18809
18810            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18811                UserManagerService.enforceSerialNumber(
18812                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18813            }
18814            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18815                UserManagerService.enforceSerialNumber(
18816                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18817            }
18818
18819            synchronized (mInstallLock) {
18820                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18821            }
18822        } catch (Exception e) {
18823            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18824                    + " because we failed to prepare: " + e);
18825            destroyUserDataLI(volumeUuid, userId,
18826                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18827
18828            if (allowRecover) {
18829                // Try one last time; if we fail again we're really in trouble
18830                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18831            }
18832        }
18833    }
18834
18835    /**
18836     * Destroy storage areas for given user on all mounted devices.
18837     */
18838    void destroyUserData(int userId, int flags) {
18839        synchronized (mInstallLock) {
18840            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18841            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18842                final String volumeUuid = vol.getFsUuid();
18843                destroyUserDataLI(volumeUuid, userId, flags);
18844            }
18845        }
18846    }
18847
18848    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18849        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18850        try {
18851            // Clean up app data, profile data, and media data
18852            mInstaller.destroyUserData(volumeUuid, userId, flags);
18853
18854            // Clean up system data
18855            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18856                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18857                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18858                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18859                }
18860                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18861                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18862                }
18863            }
18864
18865            // Data with special labels is now gone, so finish the job
18866            storage.destroyUserStorage(volumeUuid, userId, flags);
18867
18868        } catch (Exception e) {
18869            logCriticalInfo(Log.WARN,
18870                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18871        }
18872    }
18873
18874    /**
18875     * Examine all users present on given mounted volume, and destroy data
18876     * belonging to users that are no longer valid, or whose user ID has been
18877     * recycled.
18878     */
18879    private void reconcileUsers(String volumeUuid) {
18880        final List<File> files = new ArrayList<>();
18881        Collections.addAll(files, FileUtils
18882                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18883        Collections.addAll(files, FileUtils
18884                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18885        for (File file : files) {
18886            if (!file.isDirectory()) continue;
18887
18888            final int userId;
18889            final UserInfo info;
18890            try {
18891                userId = Integer.parseInt(file.getName());
18892                info = sUserManager.getUserInfo(userId);
18893            } catch (NumberFormatException e) {
18894                Slog.w(TAG, "Invalid user directory " + file);
18895                continue;
18896            }
18897
18898            boolean destroyUser = false;
18899            if (info == null) {
18900                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18901                        + " because no matching user was found");
18902                destroyUser = true;
18903            } else if (!mOnlyCore) {
18904                try {
18905                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18906                } catch (IOException e) {
18907                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18908                            + " because we failed to enforce serial number: " + e);
18909                    destroyUser = true;
18910                }
18911            }
18912
18913            if (destroyUser) {
18914                synchronized (mInstallLock) {
18915                    destroyUserDataLI(volumeUuid, userId,
18916                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18917                }
18918            }
18919        }
18920    }
18921
18922    private void assertPackageKnown(String volumeUuid, String packageName)
18923            throws PackageManagerException {
18924        synchronized (mPackages) {
18925            final PackageSetting ps = mSettings.mPackages.get(packageName);
18926            if (ps == null) {
18927                throw new PackageManagerException("Package " + packageName + " is unknown");
18928            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18929                throw new PackageManagerException(
18930                        "Package " + packageName + " found on unknown volume " + volumeUuid
18931                                + "; expected volume " + ps.volumeUuid);
18932            }
18933        }
18934    }
18935
18936    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18937            throws PackageManagerException {
18938        synchronized (mPackages) {
18939            final PackageSetting ps = mSettings.mPackages.get(packageName);
18940            if (ps == null) {
18941                throw new PackageManagerException("Package " + packageName + " is unknown");
18942            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18943                throw new PackageManagerException(
18944                        "Package " + packageName + " found on unknown volume " + volumeUuid
18945                                + "; expected volume " + ps.volumeUuid);
18946            } else if (!ps.getInstalled(userId)) {
18947                throw new PackageManagerException(
18948                        "Package " + packageName + " not installed for user " + userId);
18949            }
18950        }
18951    }
18952
18953    /**
18954     * Examine all apps present on given mounted volume, and destroy apps that
18955     * aren't expected, either due to uninstallation or reinstallation on
18956     * another volume.
18957     */
18958    private void reconcileApps(String volumeUuid) {
18959        final File[] files = FileUtils
18960                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18961        for (File file : files) {
18962            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18963                    && !PackageInstallerService.isStageName(file.getName());
18964            if (!isPackage) {
18965                // Ignore entries which are not packages
18966                continue;
18967            }
18968
18969            try {
18970                final PackageLite pkg = PackageParser.parsePackageLite(file,
18971                        PackageParser.PARSE_MUST_BE_APK);
18972                assertPackageKnown(volumeUuid, pkg.packageName);
18973
18974            } catch (PackageParserException | PackageManagerException e) {
18975                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18976                synchronized (mInstallLock) {
18977                    removeCodePathLI(file);
18978                }
18979            }
18980        }
18981    }
18982
18983    /**
18984     * Reconcile all app data for the given user.
18985     * <p>
18986     * Verifies that directories exist and that ownership and labeling is
18987     * correct for all installed apps on all mounted volumes.
18988     */
18989    void reconcileAppsData(int userId, int flags) {
18990        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18991        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18992            final String volumeUuid = vol.getFsUuid();
18993            synchronized (mInstallLock) {
18994                reconcileAppsDataLI(volumeUuid, userId, flags);
18995            }
18996        }
18997    }
18998
18999    /**
19000     * Reconcile all app data on given mounted volume.
19001     * <p>
19002     * Destroys app data that isn't expected, either due to uninstallation or
19003     * reinstallation on another volume.
19004     * <p>
19005     * Verifies that directories exist and that ownership and labeling is
19006     * correct for all installed apps.
19007     */
19008    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19009        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19010                + Integer.toHexString(flags));
19011
19012        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19013        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19014
19015        boolean restoreconNeeded = false;
19016
19017        // First look for stale data that doesn't belong, and check if things
19018        // have changed since we did our last restorecon
19019        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19020            if (!isUserKeyUnlocked(userId)) {
19021                throw new RuntimeException(
19022                        "Yikes, someone asked us to reconcile CE storage while " + userId
19023                                + " was still locked; this would have caused massive data loss!");
19024            }
19025
19026            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19027
19028            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19029            for (File file : files) {
19030                final String packageName = file.getName();
19031                try {
19032                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19033                } catch (PackageManagerException e) {
19034                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19035                    try {
19036                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19037                                StorageManager.FLAG_STORAGE_CE, 0);
19038                    } catch (InstallerException e2) {
19039                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19040                    }
19041                }
19042            }
19043        }
19044        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19045            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19046
19047            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19048            for (File file : files) {
19049                final String packageName = file.getName();
19050                try {
19051                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19052                } catch (PackageManagerException e) {
19053                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19054                    try {
19055                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19056                                StorageManager.FLAG_STORAGE_DE, 0);
19057                    } catch (InstallerException e2) {
19058                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19059                    }
19060                }
19061            }
19062        }
19063
19064        // Ensure that data directories are ready to roll for all packages
19065        // installed for this volume and user
19066        final List<PackageSetting> packages;
19067        synchronized (mPackages) {
19068            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19069        }
19070        int preparedCount = 0;
19071        for (PackageSetting ps : packages) {
19072            final String packageName = ps.name;
19073            if (ps.pkg == null) {
19074                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19075                // TODO: might be due to legacy ASEC apps; we should circle back
19076                // and reconcile again once they're scanned
19077                continue;
19078            }
19079
19080            if (ps.getInstalled(userId)) {
19081                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19082
19083                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19084                    // We may have just shuffled around app data directories, so
19085                    // prepare them one more time
19086                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19087                }
19088
19089                preparedCount++;
19090            }
19091        }
19092
19093        if (restoreconNeeded) {
19094            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19095                SELinuxMMAC.setRestoreconDone(ceDir);
19096            }
19097            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19098                SELinuxMMAC.setRestoreconDone(deDir);
19099            }
19100        }
19101
19102        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19103                + " packages; restoreconNeeded was " + restoreconNeeded);
19104    }
19105
19106    /**
19107     * Prepare app data for the given app just after it was installed or
19108     * upgraded. This method carefully only touches users that it's installed
19109     * for, and it forces a restorecon to handle any seinfo changes.
19110     * <p>
19111     * Verifies that directories exist and that ownership and labeling is
19112     * correct for all installed apps. If there is an ownership mismatch, it
19113     * will try recovering system apps by wiping data; third-party app data is
19114     * left intact.
19115     * <p>
19116     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19117     */
19118    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19119        final PackageSetting ps;
19120        synchronized (mPackages) {
19121            ps = mSettings.mPackages.get(pkg.packageName);
19122            mSettings.writeKernelMappingLPr(ps);
19123        }
19124
19125        final UserManager um = mContext.getSystemService(UserManager.class);
19126        for (UserInfo user : um.getUsers()) {
19127            final int flags;
19128            if (um.isUserUnlocked(user.id)) {
19129                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19130            } else if (um.isUserRunning(user.id)) {
19131                flags = StorageManager.FLAG_STORAGE_DE;
19132            } else {
19133                continue;
19134            }
19135
19136            if (ps.getInstalled(user.id)) {
19137                // Whenever an app changes, force a restorecon of its data
19138                // TODO: when user data is locked, mark that we're still dirty
19139                prepareAppDataLIF(pkg, user.id, flags, true);
19140            }
19141        }
19142    }
19143
19144    /**
19145     * Prepare app data for the given app.
19146     * <p>
19147     * Verifies that directories exist and that ownership and labeling is
19148     * correct for all installed apps. If there is an ownership mismatch, this
19149     * will try recovering system apps by wiping data; third-party app data is
19150     * left intact.
19151     */
19152    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19153            boolean restoreconNeeded) {
19154        if (pkg == null) {
19155            Slog.wtf(TAG, "Package was null!", new Throwable());
19156            return;
19157        }
19158        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19159        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19160        for (int i = 0; i < childCount; i++) {
19161            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19162        }
19163    }
19164
19165    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19166            boolean restoreconNeeded) {
19167        if (DEBUG_APP_DATA) {
19168            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19169                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19170        }
19171
19172        final String volumeUuid = pkg.volumeUuid;
19173        final String packageName = pkg.packageName;
19174        final ApplicationInfo app = pkg.applicationInfo;
19175        final int appId = UserHandle.getAppId(app.uid);
19176
19177        Preconditions.checkNotNull(app.seinfo);
19178
19179        try {
19180            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19181                    appId, app.seinfo, app.targetSdkVersion);
19182        } catch (InstallerException e) {
19183            if (app.isSystemApp()) {
19184                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19185                        + ", but trying to recover: " + e);
19186                destroyAppDataLeafLIF(pkg, userId, flags);
19187                try {
19188                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19189                            appId, app.seinfo, app.targetSdkVersion);
19190                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19191                } catch (InstallerException e2) {
19192                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19193                }
19194            } else {
19195                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19196            }
19197        }
19198
19199        if (restoreconNeeded) {
19200            try {
19201                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19202                        app.seinfo);
19203            } catch (InstallerException e) {
19204                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19205            }
19206        }
19207
19208        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19209            try {
19210                // CE storage is unlocked right now, so read out the inode and
19211                // remember for use later when it's locked
19212                // TODO: mark this structure as dirty so we persist it!
19213                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19214                        StorageManager.FLAG_STORAGE_CE);
19215                synchronized (mPackages) {
19216                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19217                    if (ps != null) {
19218                        ps.setCeDataInode(ceDataInode, userId);
19219                    }
19220                }
19221            } catch (InstallerException e) {
19222                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19223            }
19224        }
19225
19226        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19227    }
19228
19229    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19230        if (pkg == null) {
19231            Slog.wtf(TAG, "Package was null!", new Throwable());
19232            return;
19233        }
19234        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19235        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19236        for (int i = 0; i < childCount; i++) {
19237            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19238        }
19239    }
19240
19241    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19242        final String volumeUuid = pkg.volumeUuid;
19243        final String packageName = pkg.packageName;
19244        final ApplicationInfo app = pkg.applicationInfo;
19245
19246        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19247            // Create a native library symlink only if we have native libraries
19248            // and if the native libraries are 32 bit libraries. We do not provide
19249            // this symlink for 64 bit libraries.
19250            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19251                final String nativeLibPath = app.nativeLibraryDir;
19252                try {
19253                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19254                            nativeLibPath, userId);
19255                } catch (InstallerException e) {
19256                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19257                }
19258            }
19259        }
19260    }
19261
19262    /**
19263     * For system apps on non-FBE devices, this method migrates any existing
19264     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19265     * requested by the app.
19266     */
19267    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19268        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19269                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19270            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19271                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19272            try {
19273                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19274                        storageTarget);
19275            } catch (InstallerException e) {
19276                logCriticalInfo(Log.WARN,
19277                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19278            }
19279            return true;
19280        } else {
19281            return false;
19282        }
19283    }
19284
19285    public PackageFreezer freezePackage(String packageName, String killReason) {
19286        return new PackageFreezer(packageName, killReason);
19287    }
19288
19289    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19290            String killReason) {
19291        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19292            return new PackageFreezer();
19293        } else {
19294            return freezePackage(packageName, killReason);
19295        }
19296    }
19297
19298    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19299            String killReason) {
19300        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19301            return new PackageFreezer();
19302        } else {
19303            return freezePackage(packageName, killReason);
19304        }
19305    }
19306
19307    /**
19308     * Class that freezes and kills the given package upon creation, and
19309     * unfreezes it upon closing. This is typically used when doing surgery on
19310     * app code/data to prevent the app from running while you're working.
19311     */
19312    private class PackageFreezer implements AutoCloseable {
19313        private final String mPackageName;
19314        private final PackageFreezer[] mChildren;
19315
19316        private final boolean mWeFroze;
19317
19318        private final AtomicBoolean mClosed = new AtomicBoolean();
19319        private final CloseGuard mCloseGuard = CloseGuard.get();
19320
19321        /**
19322         * Create and return a stub freezer that doesn't actually do anything,
19323         * typically used when someone requested
19324         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19325         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19326         */
19327        public PackageFreezer() {
19328            mPackageName = null;
19329            mChildren = null;
19330            mWeFroze = false;
19331            mCloseGuard.open("close");
19332        }
19333
19334        public PackageFreezer(String packageName, String killReason) {
19335            synchronized (mPackages) {
19336                mPackageName = packageName;
19337                mWeFroze = mFrozenPackages.add(mPackageName);
19338
19339                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19340                if (ps != null) {
19341                    killApplication(ps.name, ps.appId, killReason);
19342                }
19343
19344                final PackageParser.Package p = mPackages.get(packageName);
19345                if (p != null && p.childPackages != null) {
19346                    final int N = p.childPackages.size();
19347                    mChildren = new PackageFreezer[N];
19348                    for (int i = 0; i < N; i++) {
19349                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19350                                killReason);
19351                    }
19352                } else {
19353                    mChildren = null;
19354                }
19355            }
19356            mCloseGuard.open("close");
19357        }
19358
19359        @Override
19360        protected void finalize() throws Throwable {
19361            try {
19362                mCloseGuard.warnIfOpen();
19363                close();
19364            } finally {
19365                super.finalize();
19366            }
19367        }
19368
19369        @Override
19370        public void close() {
19371            mCloseGuard.close();
19372            if (mClosed.compareAndSet(false, true)) {
19373                synchronized (mPackages) {
19374                    if (mWeFroze) {
19375                        mFrozenPackages.remove(mPackageName);
19376                    }
19377
19378                    if (mChildren != null) {
19379                        for (PackageFreezer freezer : mChildren) {
19380                            freezer.close();
19381                        }
19382                    }
19383                }
19384            }
19385        }
19386    }
19387
19388    /**
19389     * Verify that given package is currently frozen.
19390     */
19391    private void checkPackageFrozen(String packageName) {
19392        synchronized (mPackages) {
19393            if (!mFrozenPackages.contains(packageName)) {
19394                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19395            }
19396        }
19397    }
19398
19399    @Override
19400    public int movePackage(final String packageName, final String volumeUuid) {
19401        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19402
19403        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19404        final int moveId = mNextMoveId.getAndIncrement();
19405        mHandler.post(new Runnable() {
19406            @Override
19407            public void run() {
19408                try {
19409                    movePackageInternal(packageName, volumeUuid, moveId, user);
19410                } catch (PackageManagerException e) {
19411                    Slog.w(TAG, "Failed to move " + packageName, e);
19412                    mMoveCallbacks.notifyStatusChanged(moveId,
19413                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19414                }
19415            }
19416        });
19417        return moveId;
19418    }
19419
19420    private void movePackageInternal(final String packageName, final String volumeUuid,
19421            final int moveId, UserHandle user) throws PackageManagerException {
19422        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19423        final PackageManager pm = mContext.getPackageManager();
19424
19425        final boolean currentAsec;
19426        final String currentVolumeUuid;
19427        final File codeFile;
19428        final String installerPackageName;
19429        final String packageAbiOverride;
19430        final int appId;
19431        final String seinfo;
19432        final String label;
19433        final int targetSdkVersion;
19434        final PackageFreezer freezer;
19435
19436        // reader
19437        synchronized (mPackages) {
19438            final PackageParser.Package pkg = mPackages.get(packageName);
19439            final PackageSetting ps = mSettings.mPackages.get(packageName);
19440            if (pkg == null || ps == null) {
19441                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19442            }
19443
19444            if (pkg.applicationInfo.isSystemApp()) {
19445                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19446                        "Cannot move system application");
19447            }
19448
19449            if (pkg.applicationInfo.isExternalAsec()) {
19450                currentAsec = true;
19451                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19452            } else if (pkg.applicationInfo.isForwardLocked()) {
19453                currentAsec = true;
19454                currentVolumeUuid = "forward_locked";
19455            } else {
19456                currentAsec = false;
19457                currentVolumeUuid = ps.volumeUuid;
19458
19459                final File probe = new File(pkg.codePath);
19460                final File probeOat = new File(probe, "oat");
19461                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19462                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19463                            "Move only supported for modern cluster style installs");
19464                }
19465            }
19466
19467            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19468                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19469                        "Package already moved to " + volumeUuid);
19470            }
19471            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19472                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19473                        "Device admin cannot be moved");
19474            }
19475
19476            if (mFrozenPackages.contains(packageName)) {
19477                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19478                        "Failed to move already frozen package");
19479            }
19480
19481            codeFile = new File(pkg.codePath);
19482            installerPackageName = ps.installerPackageName;
19483            packageAbiOverride = ps.cpuAbiOverrideString;
19484            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19485            seinfo = pkg.applicationInfo.seinfo;
19486            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19487            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19488            freezer = new PackageFreezer(packageName, "movePackageInternal");
19489        }
19490
19491        final Bundle extras = new Bundle();
19492        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19493        extras.putString(Intent.EXTRA_TITLE, label);
19494        mMoveCallbacks.notifyCreated(moveId, extras);
19495
19496        int installFlags;
19497        final boolean moveCompleteApp;
19498        final File measurePath;
19499
19500        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19501            installFlags = INSTALL_INTERNAL;
19502            moveCompleteApp = !currentAsec;
19503            measurePath = Environment.getDataAppDirectory(volumeUuid);
19504        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19505            installFlags = INSTALL_EXTERNAL;
19506            moveCompleteApp = false;
19507            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19508        } else {
19509            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19510            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19511                    || !volume.isMountedWritable()) {
19512                freezer.close();
19513                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19514                        "Move location not mounted private volume");
19515            }
19516
19517            Preconditions.checkState(!currentAsec);
19518
19519            installFlags = INSTALL_INTERNAL;
19520            moveCompleteApp = true;
19521            measurePath = Environment.getDataAppDirectory(volumeUuid);
19522        }
19523
19524        final PackageStats stats = new PackageStats(null, -1);
19525        synchronized (mInstaller) {
19526            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19527                freezer.close();
19528                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19529                        "Failed to measure package size");
19530            }
19531        }
19532
19533        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19534                + stats.dataSize);
19535
19536        final long startFreeBytes = measurePath.getFreeSpace();
19537        final long sizeBytes;
19538        if (moveCompleteApp) {
19539            sizeBytes = stats.codeSize + stats.dataSize;
19540        } else {
19541            sizeBytes = stats.codeSize;
19542        }
19543
19544        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19545            freezer.close();
19546            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19547                    "Not enough free space to move");
19548        }
19549
19550        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19551
19552        final CountDownLatch installedLatch = new CountDownLatch(1);
19553        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19554            @Override
19555            public void onUserActionRequired(Intent intent) throws RemoteException {
19556                throw new IllegalStateException();
19557            }
19558
19559            @Override
19560            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19561                    Bundle extras) throws RemoteException {
19562                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19563                        + PackageManager.installStatusToString(returnCode, msg));
19564
19565                installedLatch.countDown();
19566                freezer.close();
19567
19568                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19569                switch (status) {
19570                    case PackageInstaller.STATUS_SUCCESS:
19571                        mMoveCallbacks.notifyStatusChanged(moveId,
19572                                PackageManager.MOVE_SUCCEEDED);
19573                        break;
19574                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19575                        mMoveCallbacks.notifyStatusChanged(moveId,
19576                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19577                        break;
19578                    default:
19579                        mMoveCallbacks.notifyStatusChanged(moveId,
19580                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19581                        break;
19582                }
19583            }
19584        };
19585
19586        final MoveInfo move;
19587        if (moveCompleteApp) {
19588            // Kick off a thread to report progress estimates
19589            new Thread() {
19590                @Override
19591                public void run() {
19592                    while (true) {
19593                        try {
19594                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19595                                break;
19596                            }
19597                        } catch (InterruptedException ignored) {
19598                        }
19599
19600                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19601                        final int progress = 10 + (int) MathUtils.constrain(
19602                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19603                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19604                    }
19605                }
19606            }.start();
19607
19608            final String dataAppName = codeFile.getName();
19609            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19610                    dataAppName, appId, seinfo, targetSdkVersion);
19611        } else {
19612            move = null;
19613        }
19614
19615        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19616
19617        final Message msg = mHandler.obtainMessage(INIT_COPY);
19618        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19619        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19620                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19621                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19622        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19623        msg.obj = params;
19624
19625        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19626                System.identityHashCode(msg.obj));
19627        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19628                System.identityHashCode(msg.obj));
19629
19630        mHandler.sendMessage(msg);
19631    }
19632
19633    @Override
19634    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19635        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19636
19637        final int realMoveId = mNextMoveId.getAndIncrement();
19638        final Bundle extras = new Bundle();
19639        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19640        mMoveCallbacks.notifyCreated(realMoveId, extras);
19641
19642        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19643            @Override
19644            public void onCreated(int moveId, Bundle extras) {
19645                // Ignored
19646            }
19647
19648            @Override
19649            public void onStatusChanged(int moveId, int status, long estMillis) {
19650                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19651            }
19652        };
19653
19654        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19655        storage.setPrimaryStorageUuid(volumeUuid, callback);
19656        return realMoveId;
19657    }
19658
19659    @Override
19660    public int getMoveStatus(int moveId) {
19661        mContext.enforceCallingOrSelfPermission(
19662                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19663        return mMoveCallbacks.mLastStatus.get(moveId);
19664    }
19665
19666    @Override
19667    public void registerMoveCallback(IPackageMoveObserver callback) {
19668        mContext.enforceCallingOrSelfPermission(
19669                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19670        mMoveCallbacks.register(callback);
19671    }
19672
19673    @Override
19674    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19675        mContext.enforceCallingOrSelfPermission(
19676                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19677        mMoveCallbacks.unregister(callback);
19678    }
19679
19680    @Override
19681    public boolean setInstallLocation(int loc) {
19682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19683                null);
19684        if (getInstallLocation() == loc) {
19685            return true;
19686        }
19687        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19688                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19689            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19690                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19691            return true;
19692        }
19693        return false;
19694   }
19695
19696    @Override
19697    public int getInstallLocation() {
19698        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19699                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19700                PackageHelper.APP_INSTALL_AUTO);
19701    }
19702
19703    /** Called by UserManagerService */
19704    void cleanUpUser(UserManagerService userManager, int userHandle) {
19705        synchronized (mPackages) {
19706            mDirtyUsers.remove(userHandle);
19707            mUserNeedsBadging.delete(userHandle);
19708            mSettings.removeUserLPw(userHandle);
19709            mPendingBroadcasts.remove(userHandle);
19710            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19711            removeUnusedPackagesLPw(userManager, userHandle);
19712        }
19713    }
19714
19715    /**
19716     * We're removing userHandle and would like to remove any downloaded packages
19717     * that are no longer in use by any other user.
19718     * @param userHandle the user being removed
19719     */
19720    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19721        final boolean DEBUG_CLEAN_APKS = false;
19722        int [] users = userManager.getUserIds();
19723        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19724        while (psit.hasNext()) {
19725            PackageSetting ps = psit.next();
19726            if (ps.pkg == null) {
19727                continue;
19728            }
19729            final String packageName = ps.pkg.packageName;
19730            // Skip over if system app
19731            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19732                continue;
19733            }
19734            if (DEBUG_CLEAN_APKS) {
19735                Slog.i(TAG, "Checking package " + packageName);
19736            }
19737            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19738            if (keep) {
19739                if (DEBUG_CLEAN_APKS) {
19740                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19741                }
19742            } else {
19743                for (int i = 0; i < users.length; i++) {
19744                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19745                        keep = true;
19746                        if (DEBUG_CLEAN_APKS) {
19747                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19748                                    + users[i]);
19749                        }
19750                        break;
19751                    }
19752                }
19753            }
19754            if (!keep) {
19755                if (DEBUG_CLEAN_APKS) {
19756                    Slog.i(TAG, "  Removing package " + packageName);
19757                }
19758                mHandler.post(new Runnable() {
19759                    public void run() {
19760                        deletePackageX(packageName, userHandle, 0);
19761                    } //end run
19762                });
19763            }
19764        }
19765    }
19766
19767    /** Called by UserManagerService */
19768    void createNewUser(int userHandle) {
19769        synchronized (mInstallLock) {
19770            mSettings.createNewUserLI(this, mInstaller, userHandle);
19771        }
19772        synchronized (mPackages) {
19773            applyFactoryDefaultBrowserLPw(userHandle);
19774            primeDomainVerificationsLPw(userHandle);
19775        }
19776    }
19777
19778    void newUserCreated(final int userHandle) {
19779        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19780        // If permission review for legacy apps is required, we represent
19781        // dagerous permissions for such apps as always granted runtime
19782        // permissions to keep per user flag state whether review is needed.
19783        // Hence, if a new user is added we have to propagate dangerous
19784        // permission grants for these legacy apps.
19785        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19786            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19787                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19788        }
19789    }
19790
19791    @Override
19792    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19793        mContext.enforceCallingOrSelfPermission(
19794                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19795                "Only package verification agents can read the verifier device identity");
19796
19797        synchronized (mPackages) {
19798            return mSettings.getVerifierDeviceIdentityLPw();
19799        }
19800    }
19801
19802    @Override
19803    public void setPermissionEnforced(String permission, boolean enforced) {
19804        // TODO: Now that we no longer change GID for storage, this should to away.
19805        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19806                "setPermissionEnforced");
19807        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19808            synchronized (mPackages) {
19809                if (mSettings.mReadExternalStorageEnforced == null
19810                        || mSettings.mReadExternalStorageEnforced != enforced) {
19811                    mSettings.mReadExternalStorageEnforced = enforced;
19812                    mSettings.writeLPr();
19813                }
19814            }
19815            // kill any non-foreground processes so we restart them and
19816            // grant/revoke the GID.
19817            final IActivityManager am = ActivityManagerNative.getDefault();
19818            if (am != null) {
19819                final long token = Binder.clearCallingIdentity();
19820                try {
19821                    am.killProcessesBelowForeground("setPermissionEnforcement");
19822                } catch (RemoteException e) {
19823                } finally {
19824                    Binder.restoreCallingIdentity(token);
19825                }
19826            }
19827        } else {
19828            throw new IllegalArgumentException("No selective enforcement for " + permission);
19829        }
19830    }
19831
19832    @Override
19833    @Deprecated
19834    public boolean isPermissionEnforced(String permission) {
19835        return true;
19836    }
19837
19838    @Override
19839    public boolean isStorageLow() {
19840        final long token = Binder.clearCallingIdentity();
19841        try {
19842            final DeviceStorageMonitorInternal
19843                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19844            if (dsm != null) {
19845                return dsm.isMemoryLow();
19846            } else {
19847                return false;
19848            }
19849        } finally {
19850            Binder.restoreCallingIdentity(token);
19851        }
19852    }
19853
19854    @Override
19855    public IPackageInstaller getPackageInstaller() {
19856        return mInstallerService;
19857    }
19858
19859    private boolean userNeedsBadging(int userId) {
19860        int index = mUserNeedsBadging.indexOfKey(userId);
19861        if (index < 0) {
19862            final UserInfo userInfo;
19863            final long token = Binder.clearCallingIdentity();
19864            try {
19865                userInfo = sUserManager.getUserInfo(userId);
19866            } finally {
19867                Binder.restoreCallingIdentity(token);
19868            }
19869            final boolean b;
19870            if (userInfo != null && userInfo.isManagedProfile()) {
19871                b = true;
19872            } else {
19873                b = false;
19874            }
19875            mUserNeedsBadging.put(userId, b);
19876            return b;
19877        }
19878        return mUserNeedsBadging.valueAt(index);
19879    }
19880
19881    @Override
19882    public KeySet getKeySetByAlias(String packageName, String alias) {
19883        if (packageName == null || alias == null) {
19884            return null;
19885        }
19886        synchronized(mPackages) {
19887            final PackageParser.Package pkg = mPackages.get(packageName);
19888            if (pkg == null) {
19889                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19890                throw new IllegalArgumentException("Unknown package: " + packageName);
19891            }
19892            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19893            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19894        }
19895    }
19896
19897    @Override
19898    public KeySet getSigningKeySet(String packageName) {
19899        if (packageName == null) {
19900            return null;
19901        }
19902        synchronized(mPackages) {
19903            final PackageParser.Package pkg = mPackages.get(packageName);
19904            if (pkg == null) {
19905                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19906                throw new IllegalArgumentException("Unknown package: " + packageName);
19907            }
19908            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19909                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19910                throw new SecurityException("May not access signing KeySet of other apps.");
19911            }
19912            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19913            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19914        }
19915    }
19916
19917    @Override
19918    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19919        if (packageName == null || ks == null) {
19920            return false;
19921        }
19922        synchronized(mPackages) {
19923            final PackageParser.Package pkg = mPackages.get(packageName);
19924            if (pkg == null) {
19925                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19926                throw new IllegalArgumentException("Unknown package: " + packageName);
19927            }
19928            IBinder ksh = ks.getToken();
19929            if (ksh instanceof KeySetHandle) {
19930                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19931                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19932            }
19933            return false;
19934        }
19935    }
19936
19937    @Override
19938    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19939        if (packageName == null || ks == null) {
19940            return false;
19941        }
19942        synchronized(mPackages) {
19943            final PackageParser.Package pkg = mPackages.get(packageName);
19944            if (pkg == null) {
19945                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19946                throw new IllegalArgumentException("Unknown package: " + packageName);
19947            }
19948            IBinder ksh = ks.getToken();
19949            if (ksh instanceof KeySetHandle) {
19950                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19951                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19952            }
19953            return false;
19954        }
19955    }
19956
19957    private void deletePackageIfUnusedLPr(final String packageName) {
19958        PackageSetting ps = mSettings.mPackages.get(packageName);
19959        if (ps == null) {
19960            return;
19961        }
19962        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19963            // TODO Implement atomic delete if package is unused
19964            // It is currently possible that the package will be deleted even if it is installed
19965            // after this method returns.
19966            mHandler.post(new Runnable() {
19967                public void run() {
19968                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19969                }
19970            });
19971        }
19972    }
19973
19974    /**
19975     * Check and throw if the given before/after packages would be considered a
19976     * downgrade.
19977     */
19978    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19979            throws PackageManagerException {
19980        if (after.versionCode < before.mVersionCode) {
19981            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19982                    "Update version code " + after.versionCode + " is older than current "
19983                    + before.mVersionCode);
19984        } else if (after.versionCode == before.mVersionCode) {
19985            if (after.baseRevisionCode < before.baseRevisionCode) {
19986                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19987                        "Update base revision code " + after.baseRevisionCode
19988                        + " is older than current " + before.baseRevisionCode);
19989            }
19990
19991            if (!ArrayUtils.isEmpty(after.splitNames)) {
19992                for (int i = 0; i < after.splitNames.length; i++) {
19993                    final String splitName = after.splitNames[i];
19994                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19995                    if (j != -1) {
19996                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19997                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19998                                    "Update split " + splitName + " revision code "
19999                                    + after.splitRevisionCodes[i] + " is older than current "
20000                                    + before.splitRevisionCodes[j]);
20001                        }
20002                    }
20003                }
20004            }
20005        }
20006    }
20007
20008    private static class MoveCallbacks extends Handler {
20009        private static final int MSG_CREATED = 1;
20010        private static final int MSG_STATUS_CHANGED = 2;
20011
20012        private final RemoteCallbackList<IPackageMoveObserver>
20013                mCallbacks = new RemoteCallbackList<>();
20014
20015        private final SparseIntArray mLastStatus = new SparseIntArray();
20016
20017        public MoveCallbacks(Looper looper) {
20018            super(looper);
20019        }
20020
20021        public void register(IPackageMoveObserver callback) {
20022            mCallbacks.register(callback);
20023        }
20024
20025        public void unregister(IPackageMoveObserver callback) {
20026            mCallbacks.unregister(callback);
20027        }
20028
20029        @Override
20030        public void handleMessage(Message msg) {
20031            final SomeArgs args = (SomeArgs) msg.obj;
20032            final int n = mCallbacks.beginBroadcast();
20033            for (int i = 0; i < n; i++) {
20034                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20035                try {
20036                    invokeCallback(callback, msg.what, args);
20037                } catch (RemoteException ignored) {
20038                }
20039            }
20040            mCallbacks.finishBroadcast();
20041            args.recycle();
20042        }
20043
20044        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20045                throws RemoteException {
20046            switch (what) {
20047                case MSG_CREATED: {
20048                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20049                    break;
20050                }
20051                case MSG_STATUS_CHANGED: {
20052                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20053                    break;
20054                }
20055            }
20056        }
20057
20058        private void notifyCreated(int moveId, Bundle extras) {
20059            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20060
20061            final SomeArgs args = SomeArgs.obtain();
20062            args.argi1 = moveId;
20063            args.arg2 = extras;
20064            obtainMessage(MSG_CREATED, args).sendToTarget();
20065        }
20066
20067        private void notifyStatusChanged(int moveId, int status) {
20068            notifyStatusChanged(moveId, status, -1);
20069        }
20070
20071        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20072            Slog.v(TAG, "Move " + moveId + " status " + status);
20073
20074            final SomeArgs args = SomeArgs.obtain();
20075            args.argi1 = moveId;
20076            args.argi2 = status;
20077            args.arg3 = estMillis;
20078            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20079
20080            synchronized (mLastStatus) {
20081                mLastStatus.put(moveId, status);
20082            }
20083        }
20084    }
20085
20086    private final static class OnPermissionChangeListeners extends Handler {
20087        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20088
20089        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20090                new RemoteCallbackList<>();
20091
20092        public OnPermissionChangeListeners(Looper looper) {
20093            super(looper);
20094        }
20095
20096        @Override
20097        public void handleMessage(Message msg) {
20098            switch (msg.what) {
20099                case MSG_ON_PERMISSIONS_CHANGED: {
20100                    final int uid = msg.arg1;
20101                    handleOnPermissionsChanged(uid);
20102                } break;
20103            }
20104        }
20105
20106        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20107            mPermissionListeners.register(listener);
20108
20109        }
20110
20111        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20112            mPermissionListeners.unregister(listener);
20113        }
20114
20115        public void onPermissionsChanged(int uid) {
20116            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20117                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20118            }
20119        }
20120
20121        private void handleOnPermissionsChanged(int uid) {
20122            final int count = mPermissionListeners.beginBroadcast();
20123            try {
20124                for (int i = 0; i < count; i++) {
20125                    IOnPermissionsChangeListener callback = mPermissionListeners
20126                            .getBroadcastItem(i);
20127                    try {
20128                        callback.onPermissionsChanged(uid);
20129                    } catch (RemoteException e) {
20130                        Log.e(TAG, "Permission listener is dead", e);
20131                    }
20132                }
20133            } finally {
20134                mPermissionListeners.finishBroadcast();
20135            }
20136        }
20137    }
20138
20139    private class PackageManagerInternalImpl extends PackageManagerInternal {
20140        @Override
20141        public void setLocationPackagesProvider(PackagesProvider provider) {
20142            synchronized (mPackages) {
20143                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20144            }
20145        }
20146
20147        @Override
20148        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20149            synchronized (mPackages) {
20150                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20151            }
20152        }
20153
20154        @Override
20155        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20156            synchronized (mPackages) {
20157                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20158            }
20159        }
20160
20161        @Override
20162        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20163            synchronized (mPackages) {
20164                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20165            }
20166        }
20167
20168        @Override
20169        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20170            synchronized (mPackages) {
20171                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20172            }
20173        }
20174
20175        @Override
20176        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20177            synchronized (mPackages) {
20178                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20179            }
20180        }
20181
20182        @Override
20183        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20184            synchronized (mPackages) {
20185                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20186                        packageName, userId);
20187            }
20188        }
20189
20190        @Override
20191        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20192            synchronized (mPackages) {
20193                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20194                        packageName, userId);
20195            }
20196        }
20197
20198        @Override
20199        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20200            synchronized (mPackages) {
20201                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20202                        packageName, userId);
20203            }
20204        }
20205
20206        @Override
20207        public void setKeepUninstalledPackages(final List<String> packageList) {
20208            Preconditions.checkNotNull(packageList);
20209            List<String> removedFromList = null;
20210            synchronized (mPackages) {
20211                if (mKeepUninstalledPackages != null) {
20212                    final int packagesCount = mKeepUninstalledPackages.size();
20213                    for (int i = 0; i < packagesCount; i++) {
20214                        String oldPackage = mKeepUninstalledPackages.get(i);
20215                        if (packageList != null && packageList.contains(oldPackage)) {
20216                            continue;
20217                        }
20218                        if (removedFromList == null) {
20219                            removedFromList = new ArrayList<>();
20220                        }
20221                        removedFromList.add(oldPackage);
20222                    }
20223                }
20224                mKeepUninstalledPackages = new ArrayList<>(packageList);
20225                if (removedFromList != null) {
20226                    final int removedCount = removedFromList.size();
20227                    for (int i = 0; i < removedCount; i++) {
20228                        deletePackageIfUnusedLPr(removedFromList.get(i));
20229                    }
20230                }
20231            }
20232        }
20233
20234        @Override
20235        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20236            synchronized (mPackages) {
20237                // If we do not support permission review, done.
20238                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20239                    return false;
20240                }
20241
20242                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20243                if (packageSetting == null) {
20244                    return false;
20245                }
20246
20247                // Permission review applies only to apps not supporting the new permission model.
20248                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20249                    return false;
20250                }
20251
20252                // Legacy apps have the permission and get user consent on launch.
20253                PermissionsState permissionsState = packageSetting.getPermissionsState();
20254                return permissionsState.isPermissionReviewRequired(userId);
20255            }
20256        }
20257
20258        @Override
20259        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20260            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20261        }
20262
20263        @Override
20264        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20265                int userId) {
20266            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20267        }
20268    }
20269
20270    @Override
20271    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20272        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20273        synchronized (mPackages) {
20274            final long identity = Binder.clearCallingIdentity();
20275            try {
20276                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20277                        packageNames, userId);
20278            } finally {
20279                Binder.restoreCallingIdentity(identity);
20280            }
20281        }
20282    }
20283
20284    private static void enforceSystemOrPhoneCaller(String tag) {
20285        int callingUid = Binder.getCallingUid();
20286        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20287            throw new SecurityException(
20288                    "Cannot call " + tag + " from UID " + callingUid);
20289        }
20290    }
20291
20292    boolean isHistoricalPackageUsageAvailable() {
20293        return mPackageUsage.isHistoricalPackageUsageAvailable();
20294    }
20295
20296    /**
20297     * Return a <b>copy</b> of the collection of packages known to the package manager.
20298     * @return A copy of the values of mPackages.
20299     */
20300    Collection<PackageParser.Package> getPackages() {
20301        synchronized (mPackages) {
20302            return new ArrayList<>(mPackages.values());
20303        }
20304    }
20305
20306    /**
20307     * Logs process start information (including base APK hash) to the security log.
20308     * @hide
20309     */
20310    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20311            String apkFile, int pid) {
20312        if (!SecurityLog.isLoggingEnabled()) {
20313            return;
20314        }
20315        Bundle data = new Bundle();
20316        data.putLong("startTimestamp", System.currentTimeMillis());
20317        data.putString("processName", processName);
20318        data.putInt("uid", uid);
20319        data.putString("seinfo", seinfo);
20320        data.putString("apkFile", apkFile);
20321        data.putInt("pid", pid);
20322        Message msg = mProcessLoggingHandler.obtainMessage(
20323                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20324        msg.setData(data);
20325        mProcessLoggingHandler.sendMessage(msg);
20326    }
20327}
20328